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.

Press + to interact

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:

Press + to interact
WhatsApp Sandbox keyword
WhatsApp Sandbox keyword

Note: Sandbox isn’t intended for production usage. Sandbox sessions expire after three days.

After sending the message, we’ll receive the following message:

Press + to interact
WhatsApp confirmation message
WhatsApp confirmation 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

From

String

Mandatory

The Twilio WhatsApp number we will use to send the message.

Body

String

Mandatory

The message we want to send.

To

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.

Press + to interact
import fetch from "node-fetch";
//Define the header parameters
const header = {
'Authorization': 'Basic ' + Buffer.from('{{ACCOUNT_SID}}'+':'+'{{AUTH_TOKEN}}').toString('base64'),
'Content-Type': 'application/x-www-form-urlencoded',
};
//Endoint URL
const url = new URL('https://api.twilio.com/2010-04-01/Accounts/{{ACCOUNT_SID}}/Messages.json');
//Define the body parameters
const body = 'Body=Hi there&From=whatsapp:{{TWILIO_WHATSAPP_NUMBER}}&To=whatsapp:{{YOUR_WHATSAPP_NUMBER}}';
//Set API call options
const options = {
method: 'POST',
headers: header,
body: body
};
async function WhatsAppEndpoint() {
try {
const response = await fetch(url, options);
// Custom function for printing the API response
printResponse(response);
} catch (error) {
console.log(`Error: ${err}`);
}
}
WhatsAppEndpoint();

Note: We’ve included a whatsapp: tag in the From and To 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

body

String

The sent message.

num_segments

String

The number of segments the message is divided into if the message body is too large to fit into one message.

direction

Enum

The direction of the message. Possible output is inbound for incoming messages, outbound-api for messages initiated using an API, outbound-call for messages initiated during a phone call, and outbound-reply for messages sent as responses to an incoming message.

from

String

The phone number from which the message was sent.

date_updated

String

The last date the message was updated.

price

String

Amount charged for sending a message.

error_message

String

Description of the error code in case the message is not sent.

uri

String

The URI of the message, relative to Twilio.

account_sid

String

The SID of the account that sent the message.

num_media

String

The number of media files attached to the message. Maximum number of files we can attach is 10.

to

String

The WhatsApp number we send the message to.

date_created

String

The date on which the message was created.

status

Enum

The status of the message sent.

sid

String

The ID associated with the message.

date_sent

String

The date the message was received by the phone number defined in the To field.

message_service_sid

String

The SID of the service used. Null in case no service is used.

error_code

Integer

The error code in case the message is not delivered.

price_unit

String

Currency in which the price is set.

api_version

String

Version of the Twilio API used.

Respond to incoming WhatsApp messages

When we send a WhatsApp message from our device to a Twilio WhatsApp number, we receive a particular message in reply in the following format:

Press + to interact
Default WhatsApp reply
Default WhatsApp reply

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
Press + to interact
WhatsApp Sandbox configuration
WhatsApp Sandbox configuration

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.

Press + to interact
{{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.

  1. Press the “Run” button in the following widget to start the server.

  2. When we see an output similar to 'Express server listening on port 3000' in the terminal, it means that the server has started.

  3. Send a WhatsApp message to our Twilio phone number.

  4. 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');
});
Custom response to incoming WhatsApp message