AWS Messaging & Targeting Blog
Adding WhatsApp as an Amazon Pinpoint Channel
10/29/24 – Update – WhatsApp is now available through AWS End User Messaging. Visit here to get started.
8/19/2020 – Updated for clarity on Twilio sandbox requirements
Amazon Pinpoint recently announced the general availability of custom channels. Custom channels enable you to extend the capabilities of Amazon Pinpoint via a webhook or AWS Lambda function. Among many other possibilities, you can use custom channels to send messages to your customers through any API-enabled service, for example WhatsApp. With these new channels, you have full control over the message delivery to the endpoints associated with each custom channel campaign.
In this post, we provide a quick overview of the features and capabilities of using a custom channel as part of campaigns. We also provide a blueprint that you can use to build your first sandbox integration with WhatsApp as a custom channel.
Note: Twilio and WhatsApp are third-party services subject to additional terms and charges. Amazon Web Services isn’t responsible for any third-party service that you use to send messages with custom channels.
Prerequisites
Before creating your new custom channel, you must have the integration ready and an Amazon Identity and Account Management (IAM) user created with the necessary permissions. First set up the following:
- Create an IAM administrator. For more information, see Creating your first IAM admin user and group in the IAM User Guide. Specify the credentials of this IAM user when you set up the AWS Command Line Interface (CLI).
- Follow the steps at https://www.twilio.com/docs/whatsapp/api to create a new Twilio account. Join your WhatsApp account to the sandbox to be able to receive messages. Save the account SID and Auth token as both are needed in a later step. Remember to review the terms of use for both Twilio and WhatsApp, as well as Twilio sandbox limitations.
- Configure the AWS CLI. For more information about setting up the AWS CLI, see Configuring the AWS CLI.
Step 1: Create an Amazon Pinpoint project.
In this section, you create and configure a project in Amazon Pinpoint. Later, you use this data to create segments and campaigns.
To set up the Amazon Pinpoint project
- Sign in to the Amazon Pinpoint console at http://console.thinkwithwp.com/pinpoint/.
- On the All projects page, choose Create a project. Enter a name for the project, and then choose Create.
- On the Configure features page, under SMS and Voice, choose Configure.
- Under General settings, select Enable the SMS channel for this project, and then choose Save changes.
- In the navigation pane, under Settings, choose General settings. In the Project details section, copy the value under Project ID. You need this value for later.
Step 2: Create an endpoint.
In Amazon Pinpoint, an endpoint represents a specific method of contacting a customer. This could be their email address (for email messages) or their phone number (for SMS messages) or a custom endpoint type. Endpoints can also contain custom attributes, and you can associate multiple endpoints with a single user. In this step, we create an SMS endpoint that is used to send a WhatsApp message.
To create an endpoint using AWS CLI, at the command line, enter the following command:
aws pinpoint update-endpoint --application-id <project-id> \
--endpoint-id 12456 --endpoint-request "Address='<mobile-number>', \
ChannelType='SMS',Attributes={username=['testUser'],integrations=['WhatsApp']}"
In the preceding example, replace <project-id>
with the Amazon Pinpoint Project ID that you copied in step 1. Replace <mobile-number>
with your phone number, formatted in E.164 format (for example, +12065550142). For the WhatsApp integration to work, you must use the mobile number that you registered in the WhatsApp sandbox in the prerequisite steps.
Step 3: Create an AWS Lambda.
You must create an AWS Lambda that has the code that calls Twilio and sends a message to the endpoint.
1. Open the AWS Lambda console at http://console.thinkwithwp.com/AWSLambda, and then click on Create Function.
2. Choose Author from scratch.
3. For Function Name, enter ‘WhatsAppTest’.
4. For Runtime, select Python 3.7.
5. Click Create Function.
6. For the function code, copy the following and paste into the code browser in your AWS Lambda function:
import base64
import json
import os
import urllib
from urllib import request, parse
TWILIO_SMS_URL = "https://api.twilio.com/2010-04-01/Accounts/{}/Messages.json"
TWILIO_ACCOUNT_SID = os.environ.get("TWILIO_ACCOUNT_SID")
TWILIO_AUTH_TOKEN = os.environ.get("TWILIO_AUTH_TOKEN")
TWILIO_FROM_NUMBER = os.environ.get("TWILIO_FROM_NUMBER")
def lambda_handler(event, context):
if not TWILIO_ACCOUNT_SID:
return "Unable to access Twilio Account SID."
elif not TWILIO_AUTH_TOKEN:
return "Unable to access Twilio Auth Token."
elif not TWILIO_FROM_NUMBER:
return "Unable to access Twilio WhatsApp From Number."
# Lets print out the event for our logs
print("Received event: {}".format(event))
# insert Twilio Account SID into the REST API URL
populated_url = TWILIO_SMS_URL.format(TWILIO_ACCOUNT_SID)
for key in event['Endpoints'].keys():
to_number = event['Endpoints'][key]['Address']
# Example body and using an attribute from the endpoint
username = event['Endpoints'][key]['Attributes']['username'][0]
body = "Hello {}, here is your weekly 10% discount coupon: SAVE10".format(username)
post_params = {"To": "whatsapp:" + to_number, "From": "whatsapp:" + TWILIO_FROM_NUMBER, "Body": body}
# encode the parameters for Python's urllib
data = parse.urlencode(post_params).encode()
req = request.Request(populated_url)
# add authentication header to request based on Account SID + Auth Token
authentication = "{}:{}".format(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN)
base64string = base64.b64encode(authentication.encode('utf-8'))
req.add_header("Authorization", "Basic %s" % base64string.decode('ascii'))
print("Request: " + str(request))
try:
# perform HTTP POST request
with request.urlopen(req, data) as f:
print("Twilio returned {}".format(str(f.read().decode('utf-8'))))
except Exception as e:
# something went wrong!
return e
return "WhatsApp messages sent successfully"
7. Add environment variables for your Twilio Account SID, Auth token, and From Number that you acquired from the prerequisite steps.
8. Add permissions to your AWS Lambda to allow Amazon Pinpoint to invoke it:
aws lambda add-permission \
--function-name WhatsAppTest \
--statement-id sid \
--action lambda:InvokeFunction \
--principal pinpoint.us-east-1.amazonaws.com \
--source-arn arn:aws:mobiletargeting:us-east-1:<account-id>:apps/*
Step 4: Create a segment and campaign in Amazon Pinpoint.
Now that we have an endpoint, we must add it to a segment so that we can use it within a campaign. By sending a campaign, we can verify that our Amazon Pinpoint project is configured correctly, and that we created the endpoint correctly.
To create the segment and campaign:
1. Open the Amazon Pinpoint console at http://console.thinkwithwp.com/pinpoint, and then choose the project that you created in step 1.
2. In the navigation pane, choose Segments, and then choose Create a segment.
3. Name the segment “WhatsAppTest.” Under Segment group 1, on the Add a filter menu, choose Filter by endpoint.
4. For Choose an endpoint attribute, choose integrations, then for values, choose WhatsApp.
5. Confirm that the Segment estimate section shows that there is one eligible endpoint, and then choose Create segment.
6. In the navigation pane, choose Campaigns, and then choose Create a campaign.
7. Name the campaign “WhatsAppTest.” Under Choose a channel for this campaign, choose Custom, and then choose Next.
8. On the Choose a segment page, choose the “WhatsAppTest” segment that you just created, and then choose Next.
9. In Create your message, choose the AWS Lambda function we just created, ‘WhatsAppTest.’ Select SMS in the Endpoint Options. On the Choose when to send the campaign page, keep all of the default values, and then choose Next. On the Review and launch page, choose Launch campaign.
Within a few seconds, you should receive a WhatsApp message at the phone number that you specified when you created the endpoint.
Next steps
Your Custom channel solution for WhatsApp is now ready to use. But first, review and upgrade your Twilio sandbox. This post is simply a walkthrough to show you how quickly you can prototype and start sending WhatsApp messages with Pinpoint and Twilio. However, for production usage, you need to make sure to review all of the additional terms and charges. Start here to understand more: https://www.twilio.com/docs/whatsapp/sandbox#twilio-sandbox-limitations
There are several ways you can make this solution your own.
- Customize your messaging: This post used an example message to be sent to your endpoints within the AWS Lambda. You can customize that message to fit your needs.
- Expand endpoints in your application: This post only used one endpoint for the integration. You can use your WhatsApp integration with new endpoints by importing a segment that can be used with a new campaign. Learn how to import a segment here: https://docs.thinkwithwp.com/pinpoint/latest/userguide/segments-importing.html
- Use new integrations: This post focused on integrating your custom channel with WhatsApp but there are many other integrations that are possible when using AWS Lambda.
Amazon Pinpoint is a flexible and scalable outbound and inbound marketing communications service. Learn more here: https://thinkwithwp.com/pinpoint/