Created
April 26, 2023 10:39
-
-
Save IObert/6d3707713157e59f424fa2898396e3a3 to your computer and use it in GitHub Desktop.
Trigger Studio Flow via Segment Destination Function
This file contains hidden or 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 onIdentify(event, settings) { | |
let response; | |
try { | |
const profileApiResponse = await fetch( | |
`https://profiles.segment.com/v1/spaces/${ | |
event.context.personas.space_id | |
}/collections/users/profiles/user_id:${encodeURIComponent( | |
event.userId | |
)}/traits`, | |
{ | |
method: 'GET', | |
headers: { | |
Authorization: `Basic ${btoa(settings.profileApiKey + ':')}` | |
} | |
} | |
); | |
const profile = await profileApiResponse.json(); | |
const phone = profile.traits.isWhatsApp | |
? `whatsapp:${event.userId}` | |
: event.userId; | |
// Create the user in the system after | |
await fetch(`https://${settings.functionDomain}/users/add`, { | |
method: 'POST', | |
headers: { | |
'Content-Type': 'application/json' | |
}, | |
body: JSON.stringify({ phone }) | |
}); | |
response = await fetch( | |
`https://studio.twilio.com/v2/Flows/${settings.flowSid}/Executions `, | |
{ | |
method: 'POST', | |
headers: { | |
Authorization: `Basic ${btoa( | |
settings.twilioAccountId + ':' + settings.twilioAuthToken | |
)}`, | |
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' | |
}, | |
body: toFormParams({ | |
To: phone, | |
From: settings.messagingServiceSid | |
}) | |
} | |
); | |
} catch (error) { | |
// Retry on connection error | |
throw new RetryError(error.message); | |
} | |
if (response.status >= 500 || response.status === 429) { | |
// Retry on 5xx (server errors) and 429s (rate limits) | |
throw new RetryError(`Failed with ${response.status}`); | |
} | |
} | |
function toFormParams(params) { | |
return Object.entries(params) | |
.map(([key, value]) => { | |
const paramName = encodeURIComponent(key); | |
const param = encodeURIComponent(value); | |
return `${paramName}=${param}`; | |
}) | |
.join('&'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This function first retrieves the traits from the Profile API and then uses the Twilio API to trigger a Studio Flow:
This is the needed config:
