Skip to content

Instantly share code, notes, and snippets.

@IObert
Created April 26, 2023 10:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save IObert/6d3707713157e59f424fa2898396e3a3 to your computer and use it in GitHub Desktop.
Save IObert/6d3707713157e59f424fa2898396e3a3 to your computer and use it in GitHub Desktop.
Trigger Studio Flow via Segment Destination Function
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('&');
}
@IObert
Copy link
Author

IObert commented Apr 26, 2023

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:
triggerFlowSettings

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment