Personalize SMS Marketing Communications with Twilio and Segment

April 16, 2021
Written by
Paul Kamp
Twilion
Reviewed by
Ju Lee
Twilion

personalize SMS Twilio Segment

Personalized communications are powerful. The right message, at the right time, on the right channel is the difference between a customer for life – and a lifelong detractor. Whether you're in real estate, medicine, finance, retail, or really any industry, timely and useful communications are essential to keep your customers happy.

This post will show you how to personalize an SMS to a customer on an e-commerce page using Segment and Twilio Programmable Messaging.

Let's build something timely!

Prerequisites

Before we get started, you'll need to sign up for a few accounts.

And with that, let's get started!

Set up a source in Segment

With Segment, you create a source for every site or app (or device!) you'd like to track using Twilio Segment's platform. Our made-up e-commerce app will be our source for this demo, and we'll collect data from a shopping page.

On the Segment console's left side, click the 'Sources' link, then click the blue 'Add Source' button on the following screen's right side.

Adding a Source to Twilio Segment

Select the "Javascript/Website" default source, then click 'Add Source' on the modal that appears. Name it something incredible you’ll remember, then continue.

You can leave that tab up for now – let's continue and set up a number with Twilio we can use for SMS.

Prepare a Twilio phone number for SMS

If you don't have yet have an SMS-enabled phone number you'd like to use, head on over to the phone numbers console inside Twilio. Click the blue 'Buy a Number' button, and pick something using your favorite combination of filters.

When satisfied your number is perfect, purchase said number. We'll later use that number to test our app.

If you plan to send a large volume of marketing messages over a long code in the United States, you will need to obey dedicated application-to-person rules. Read more about A2P 10DLC on Twilio's information hub.

Build a demo e-commerce page

Why reinvent the wheel? For this demo, I based my e-commerce app on the frustrated shopper notifications demo from my amazing colleagues Tido Carriero and Netto Farah.

We'll take their web page and mock it up to add an out-of-stock item. When a customer tries to buy that item, we'll commiserate and send them a 10% off coupon of apology!

Paste the following HTML into a file locally on your computer (adding the .html extension):

<html lang="en">
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta charset="utf-8"><title>Owl Mall</title>
    <!-- PASTE YOUR SEGMENT JAVASCRIPT CODE HERE -->
</head>
<body>
    <form>
      <label for="fname">First name:</label><br><input type="text" value="You" id="fname" name="fname"><br />
      <label for="phone">Cell Phone:</label><br><input type="text" value = "+18885551212" id="phone" name="phone"><br />
      <input type="button" value="Buy Out of Stock Thing" onclick="buyThing(this.form);">
    </form>
    <script>
    var clickedButton = 0;
    function buyThing(form) {
        if (form.fname.value.length > 0 && form.phone.value.length > 0) {
            // Insert your data validation here
            analytics.track("Checkout Step Completed", 
                {item: '3245Out of Stock', "firstName": form.fname.value, "phoneNumber": form.phone.value}
            );
        }
    }
    </script>
</body>
</html>

Now, go back to the Segment 'source' tab you left open. Copy everything from the "Install Segment snippet on your website" section, and paste it where I added <!-- PASTE YOUR SEGMENT JAVASCRIPT CODE HERE --> in the code. That’s the magic glue that holds the app together – your custom code which enables Segment analytics.

Switch your Segment console to the 'Debugger' – it's one of the tabs in 'Sources'.

In another tab, load up your .html file in your browser now. Enter your first name and cell phone number in E.164 format, then hit 'Buy Out of Stock Thing'.

Debugger events inside Segment showing a cart failure

Well, it's a bummer that item is out of stock – but voila! You should now see some events in your Debugger tab – a Track, Identify, and Page entry. Let's move on and hook up Twilio.

Set up a Segment destination function

We're going to use a custom Segment Function to deliver our coupon via SMS.

In the left sidebar, click the 'Catalog' link, then the 'Functions' tab. Hit the '+ New Function' button to continue.

Move the selector to 'Destination', then hit the blue 'Build' button.

In the IDE that appears, select the 'Templates' tab on the right side of the screen, then click the 'Twilio' template.

Delete the await phoneCall(), if (settings.twilioWhatsAppFrom), and async function phoneCall(params, settings) blocks. Your code should now look something like this:

/**
 * @param {SpecTrack} event The track event
 * @param {Object.<string, any>} settings Custom settings
 * @return void
 */
async function onTrack(event, settings) {
  const Body = "Sorry about your experience with Owl Mall, "+event.properties.firstName+", – enter 'rickroll' for 10% off next time."
  const To = event.properties.phoneNumber

  if (settings.twilioFrom) {
    await sendText({
      From: settings.twilioFrom,
      To,
      Body
    }, settings)
  }
}

/** 
 * Sends SMS or WhatsApp message with Twilio
 * 
 * https://www.twilio.com/docs/sms
 * https://www.twilio.com/docs/whatsapp
 * 
 */
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)
  })
}

/** 
 * Places a Twilio phone call.
 * 
 * https://www.twilio.com/docs/voice 
 * 
 */
async function phoneCall(params, settings) {
  const endpoint = `https://api.twilio.com/2010-04-01/Accounts/${settings.twilioAccountId}/Calls.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('&')
}

Configure and send a test event

Next, switch to 'Settings.' In turn, fill in your Twilio Account ID and Twilio Auth Token, found in the Twilio console. In the 'Twilio From Number', enter the Twilio number you purchased – or already had – again, in E.164 format.

Save those credentials somewhere handy; you'll use them again in a second.

Now, go to 'Test.' Run with a sample event, selecting the "Checkout Step Completed" with your name and number.

Fingers crossed – you should get an SMS with a coupon in a second!

Test the personalized SMS shopper flow

Scroll down and select the blue 'Configure' button. Name your function and give it a good description so you'll remember it later, then click 'Create Function.'

In the modal that appears, click 'Connect Destination'. Then, click the source you created for this e-commerce page, followed by the 'Confirm Source' button.

Once again, fill in your Twilio Account ID, Auth Token, and From Number from the console. Then, click the disabled 'Slider' next to the download and trash button.

Enable a destination function in Segment using the slider

Click on 'Sources' in the sidebar, and you'll see your app with 'Enabled' status.

Now, reload your custom Owl Mall web page – it's time for the moment of truth. Hit the button and wait…

💥. You should now have a message offering you a coupon, all tied to your actions on the checkout page. Pretty awesome!

Timely communication with Twilio and Segment

Now you've learned to personalize an SMS message for a disappointing shopping experience. You used Twilio Segment sources and event tracking connected to a Twilio Programmable SMS integration to deliver coupon codes. And – most importantly – you turned a potentially sad customer into a fan for life.

However you end up personalizing your messages (and enhancing your own analytics), I know you'll design a much better customer experience. For more information on how to build with Segment (and Twilio!) check out the Segment Recipes here.

Thank you for following along – I can't wait to see how you expand my code!

Paul Kamp is the Editor-in-Chief of the Twilio blog. In a typical week, he's disappointed with company communications between 2 and 38 times. He can be reached at pkamp [at] twilio.com.