Last active
June 13, 2024 16:10
-
-
Save jme783/918109df59d6b1decdc0fa3477b299bd to your computer and use it in GitHub Desktop.
send-awv-sms-twilio.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
async function onTrack(event, settings) { | |
// Function settings | |
const { | |
twilioMessagingServiceSid, | |
twilioAccountSid, | |
twilioAuthToken, | |
contentTemplateSid, | |
segmentUnifySpaceId, | |
segmentUnifyAccessToken, | |
toPhoneNumberOverride, | |
pcpNameOverride | |
} = settings; | |
let { triggerEventName } = settings; | |
triggerEventName = triggerEventName || 'Trigger Annual Wellness Visit Nudge'; | |
// End Settings block | |
const { userId, event: eventName } = event; | |
if (eventName !== triggerEventName) { | |
throw new EventNotSupported(`Event not supported: ${eventName}`); | |
} | |
if (!userId) { | |
throw new ValidationError('Missing userId'); | |
} | |
// Fetch the patient engagement profile from Segment | |
const segmentProfilesEndpoint = `https://profiles.segment.com/v1/spaces/${segmentUnifySpaceId}/collections/users/profiles/user_id:${userId}/traits?limit=200`; | |
let response; | |
const options = { | |
method: 'GET', | |
headers: { | |
'Content-Type': 'application/json', | |
Authorization: `Basic ${Buffer.from(`${segmentUnifyAccessToken}:`).toString('base64')}` | |
} | |
}; | |
try { | |
response = await fetch(segmentProfilesEndpoint, options); | |
if (!response.ok) { | |
throw new RetryError(`Profile API call failed with status ${response.status}`); | |
} | |
const fetchedProfile = await response.json(); | |
console.log('Response from Profile API: ', fetchedProfile); | |
const { phone, name, generalPractitioner } = fetchedProfile.traits; | |
if (!name || !phone) { | |
throw new ValidationError('Missing required profile traits: name or phone'); | |
} | |
// Use the Profile data to construct the Send SMS API call to Twilio | |
const From = twilioMessagingServiceSid; | |
const To = toPhoneNumberOverride ? toPhoneNumberOverride : phone; | |
const contentVariables = { | |
firstName: name.split(' ')[0], | |
pcpName: generalPractitioner || pcpNameOverride | |
}; | |
const twilioSendSMSRequestURL = `https://api.twilio.com/2010-04-01/Accounts/${twilioAccountSid}/Messages.json`; | |
const smsResponse = await fetch(twilioSendSMSRequestURL, { | |
method: 'POST', | |
headers: { | |
'Authorization': `Basic ${Buffer.from(`${twilioAccountSid}:${twilioAuthToken}`).toString('base64')}`, | |
'Content-Type': 'application/x-www-form-urlencoded' | |
}, | |
body: new URLSearchParams({ | |
To: To, | |
From: From, | |
ContentSid: contentTemplateSid, | |
ContentVariables: JSON.stringify(contentVariables) | |
}).toString() | |
}); | |
if (!smsResponse.ok) { | |
const errorData = await smsResponse.json(); | |
console.log(errorData); | |
throw new RetryError(`Twilio SMS sending failed with status ${smsResponse.status}`); | |
} | |
const smsResult = await smsResponse.json(); | |
console.log('Successfully sent SMS', smsResult); | |
} catch (error) { | |
console.error('Error:', error); | |
if (response && (response.status >= 500 || response.status === 429)) { | |
throw new RetryError(`Failed with ${response.status}`); | |
} else if (error instanceof RetryError) { | |
throw error; | |
} else { | |
throw new Error(error.message); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment