This repository contains sample code for integrating Klaviyo with Twilio Programmable SMS.
The solution involves three main components:
- Twilio Messaging Service: responsible for sending out the SMS to the indended recipient. You can read more about the Messaging Service here.
- Twilio SMS Function: a serverless function deployed on Twilio, which calls the Messaging Service to initiate the sending of messages. The code of the function is included in this repository.
- Klaviyo Flow: configured within Klaviyo, the Flow includes a webhook action that calls the Twilio SMS Function with the desired message body and the recipient's phone number.
-
Configuring the Messaging Service for sending SMS:
- (Optional) Buy some numbers for sending SMS. If you are sending SMS to multiple different countries, it is best to purchase a number from each of those countries. If you already have phone numbers, you can skip this step.
- Create a Messaging Service. This can be done via the Console as well as the API. Take note of the service's unique identifier (
SID
). You will need it when setting up the SMS function. If sending SMS to multiple geographical destinations, turn on Country code geomatching on the messaging service. This will ensure that when sending the SMS messages, the Service automatically picks a local number from the sender pool (e.g. SMS to France will be sent from your French number). - Add your numbers to the Messaging Service's sender pool. The Messaging Service will use the numbers in its pool to send out messages.
-
Deploying the SMS function:
- Rename the
.env.example
file to.env
. - Configure the environment variables listed in the
.env
file:ACCOUNT_SID
={YOUR TWILIO ACCOUNT SID}AUTH_TOKEN
={YOUR TWILIO AUTH TOKEN}MESSAGING_SERVICE_SID
={MESSAGING SERVICE SID FROM THE PREVIOUS STEP}AUTH_USERNAME
={USERNAME TO SECURE YOUR FUNCTION} - can be any stringAUTH_PASSWORD
={PASSWORD TO SECURE YOUR FUNCTION} - can be any string
- Deploy the SMS function via the Serverless Toolkit by running the
twilio serverless:deploy
CLI command. After the deployment completes take note of your newly deployed function's URL. You will need it when setting up the Klaviyo webhook.
- Rename the
-
Setting up the Klaviyo flow to call the SMS function:
- Create a Klaviyo flow with the desired trigger.
- In the flow, add a webhook action with the following configuration:
- URL: your Twilio SMS function URL from the previous step
- HEADERS: add an authorization header:
- Key:
Authorization
- Value: the value should be a base64 encoded string of your
AUTH_USERNAME
andAUTH_PASSWORD
. You can use this link to generate that encoded string. The resulting string should begin with the wordBasic
.
- Key:
- JSON BODY: the body should contain two fields:
recipient_phone_number
: storing the recipients phone numbermessage
: storing the message body
- That's it! When your flow runs, it should send an SMS via Twilio to the users assigned to it!