Programmable WhatsApp Message
Learn how Twilio can be used for messaging with the WhatsApp Business API.
WhatsApp is an internationally-available free messaging app. We can use the different endpoints available in Twilio to send and receive messages from WhatsApp in our applications.
Send an outbound WhatsApp message
We can send messages to a WhatsApp number through Twilio. The base URL used to send outbound WhatsApp messages is as follows:
https://api.twilio.com/2010-04-01/Accounts/{ACCOUNT_SID}/Messages.json
To send messages with WhatsApp in production, WhatsApp has to formally approve our account. However, that doesn’t mean we have to wait to start building. Twilio Sandbox for WhatsApp lets us test our application in a developer environment.
Join the Sandbox
We need to join Twilio Sandbox to send or receive WhatsApp messages from the Sandbox. To do this, send the “join <your Sandbox keyword>” message to the WhatsApp Sandbox number (+1-415-523-8886). Our Sandbox keyword is a unique string that can be found on the WhatsApp Sandbox page, as shown below:
Note: Sandbox isn’t intended for production usage. Sandbox sessions expire after three days.
After sending the message, we’ll receive the following message:
If we received the message, it means our WhatsApp phone number is now linked to our Sandbox. It also means that we can send and receive messages from the WhatsApp Sandbox to our WhatsApp number.
Request parameters
We need to provide some mandatory request parameters to send a WhatsApp message from our Twilio phone number. Details of these parameters are given in the table below.
Name | Type | Category | Description |
| String | Mandatory | The Twilio WhatsApp number we will use to send the message. |
| String | Mandatory | The message we want to send. |
| String | Mandatory | The WhatsApp number we want to send the message to in the form “%2B [country code] [phone number].” Here, “%2B” is the code for the plus (+) sign. |
Let’s send a WhatsApp message using Twilio in the following code. Click “Edit” and provide a WhatsApp number. Make sure to include the “%2 B” sign with your number. Don’t forget to click “Save” when you’re done.
import fetch from "node-fetch";//Define the header parametersconst header = {'Authorization': 'Basic ' + Buffer.from('{{ACCOUNT_SID}}'+':'+'{{AUTH_TOKEN}}').toString('base64'),'Content-Type': 'application/x-www-form-urlencoded',};//Endoint URLconst url = new URL('https://api.twilio.com/2010-04-01/Accounts/{{ACCOUNT_SID}}/Messages.json');//Define the body parametersconst body = 'Body=Hi there&From=whatsapp:{{TWILIO_WHATSAPP_NUMBER}}&To=whatsapp:{{YOUR_WHATSAPP_NUMBER}}';//Set API call optionsconst options = {method: 'POST',headers: header,body: body};async function WhatsAppEndpoint() {try {const response = await fetch(url, options);// Custom function for printing the API responseprintResponse(response);} catch (error) {console.log(`Error: ${err}`);}}WhatsAppEndpoint();
Note: We’ve included a
whatsapp:
tag in theFrom
andTo
fields before providing the WhatsApp number because Twilio uses this tag to identify the messaging channel.
In the code above:
Lines 4–7: We define the header parameter, which includes the access tokens.
Line 10: We define the endpoint URL and provide the
ACCOUNT_SID
.Line 13: We define the body parameters and set the message body, source WhatsApp number, and destination WhatsApp number.
Lines 16–20: We define the options parameters and set the request type as
POST
.Lines 22–30: We define the function
WhatsAppEndpoint
, which calls the endpoint.Line 32: We call the
WhatsAppEndpoint
function.
Response fields
The following table gives details about the attributes in the response object.
Name | Type | Description |
| String | The sent message. |
| String | The number of segments the message is divided into if the message body is too large to fit into one message. |
| Enum | The direction of the message. Possible output is |
| String | The phone number from which the message was sent. |
| String | The last date the message was updated. |
| String | Amount charged for sending a message. |
| String | Description of the error code in case the message is not sent. |
| String | The URI of the message, relative to Twilio. |
| String | The SID of the account that sent the message. |
| String | The number of media files attached to the message. Maximum number of files we can attach is 10. |
| String | The WhatsApp number we send the message to. |
| String | The date on which the message was created. |
| Enum | The status of the message sent. |
| String | The ID associated with the message. |
| String | The date the message was received by the phone number defined in the |
| String | The SID of the service used. Null in case no service is used. |
| Integer | The error code in case the message is not delivered. |
| String | Currency in which the |
| String | Version of the Twilio API used. |
This reply is sent with the help of some TwiML instructions defined by a webhook URL. This inbound URL is set up in the WhatsApp Sandbox against the “WHEN A MESSAGE COMES IN” field. By default, this URL is as follows:
https://timberwolf-mastiff-9776.twil.io/demo-reply
To send custom responses to incoming WhatsApp messages, we need to configure this webhook URL by providing the URL for our app. To do this, we need to paste the URL given below against the “WHEN A MESSAGE COMES IN” field.
{{EDUCATIVE_LIVE_VM_URL}}
Let’s try to send custom responses to our WhatsApp messages. Follow the steps given below to see how Twilio sends custom responses to WhatsApp messages.
Press the “Run” button in the following widget to start the server.
When we see an output similar to
'Express server listening on port 3000'
in the terminal, it means that the server has started.Send a WhatsApp message to our Twilio phone number.
After a while, we’ll receive a customized reply from our Twilio number containing the text we set up in the following widget in lines 12–20.
const express = require('express'); const bodyParser = require('body-parser'); const { MessagingResponse } = require('twilio').twiml; const app = express(); app.use(bodyParser.urlencoded({ extended: false })); app.post('/', (req, res) => { const twiml = new MessagingResponse(); if (req.body.Body == 'Hello') { twiml.message('Hi!'); } else if (req.body.Body == 'Bye') { twiml.message('Goodbye'); } else { twiml.message( 'No Body param match, Twilio sends this in the request to your server.' ); } res.type('text/xml').send(twiml.toString()); }); app.listen(3000, () => { console.log('Express server listening on port 3000'); });