Skip to content

Instantly share code, notes, and snippets.

@nettofarah
Forked from sudheendrach/twilio-destination.js
Created February 8, 2021 20:42
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nettofarah/c316cfe3a120ac220a4b6621472665e7 to your computer and use it in GitHub Desktop.
Save nettofarah/c316cfe3a120ac220a4b6621472665e7 to your computer and use it in GitHub Desktop.
async function onTrack(event, settings) {
if (event.event !== settings.eventName) {
return;
}
const product = event.properties.products[0];
const itemPurchased = `${product.brand} ${product.name}`;
const Body = `Thank you for purchasing ${itemPurchased} from our site. We will follow-up with the tracking details shortly.`;
const To = settings.twilioDestinationNumber;
if (settings.twilioFrom) {
await sendText(
{
From: settings.twilioFrom,
To,
Body,
},
settings
);
}
if (settings.twilioWhatsAppFrom) {
// Learn more at: https://www.twilio.com/docs/whatsapp
await sendText(
{
To: "whatsapp:" + To,
From: settings.twilioWhatsAppFrom,
Body,
},
settings
);
}
}
/**
* Sends SMS or WhatsApp message with Twilio
*
* https://www.twilio.com/docs/sms
*
*/
async function sendText(params, settings) {
const endpoint = `https://api.twilio.com/2010-04-01/Accounts/${settings.twilioAccountId}/Messages.json`;
await fetch(endpoint, {
method: "POST",
headers: {
Authorization: `Basic ${btoa(
settings.twilioAccountId + ":" + settings.twilioToken
)}`,
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
},
body: toFormParams(params),
});
}
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