Skip to contentSkip to navigationSkip to topbar
Rate this page:
On this page

Manage Conversations WhatsApp Addresses


(information)

Info

Flex Conversations requires Flex UI 2.0. If you are on Flex UI 1.x, please refer to Chat and Messaging pages.

Connect your WhatsApp sender number to Flex Conversations by following one of the two approaches outlined below. For numbers already registered with WhatsApp, use the Create a WhatsApp address via Flex Console instructions. For numbers using the WhatsApp sandbox, use the Configuring Whatsapp Sandbox instructions.


Create a WhatsApp Address

create-a-whatsapp-address page anchor

In order to create a Conversations Address for WhatsApp, you need to have a WhatsApp sender registered on your Twilio account. This is unfortunately not a quick process and includes registration and vetting on the WhatsApp side. For testing using the WhatsApp Sandbox, see the next step. You can create a WhatsApp Conversations Address via the Flex Console or via the API.


To get started, navigate to Messaging > Senders > WhatsApp senders(link takes you to an external page) in the Twilio Console. The rest assumes you already have a registered WhatsApp number on your account.

You can create WhatsApp Addresses via Flex Console > Manage > Messaging(link takes you to an external page):

  1. Click + Add new Address from the Conversations Addresses tab.
  2. Select WhatsApp as the Address type.
  3. You can optionally enter a friendly name.

    Create new Address.
  4. Choose your WhatsApp number (sender) in the dropdown.
  5. Configure the integration to Flex - either by using Studio or Webhook . Unless you have removed or reconfigured it, you should be good to use the out-of-box Studio Flow "Messaging Flow" . To learn more about configuring Studio Flows, see Configure pre-agent workflow with Studio.
  6. Click Submit to save your new Flex WhatsApp Address.

You can edit or delete WhatsApp Addresses at any point using the Flex Console.


The Conversations API's Address Configuration Resource allows you to create and manage WhatsApp addresses for your Twilio account. On address creation, you can specify autocreation of a Conversation upon receipt of an inbound message. The following example shows you the programmatic version of our Console example with a retry count. To learn more about the different resource properties, see Address Configuration Resource.

Create a WhatsApp Address via the API

create-a-whatsapp-address-via-the-api page anchor
Node.js
Python
C#
Java
Go
PHP
Ruby
twilio-cli
curl

_17
// Download the helper library from https://www.twilio.com/docs/node/install
_17
// Find your Account SID and Auth Token at twilio.com/console
_17
// and set the environment variables. See http://twil.io/secure
_17
const accountSid = process.env.TWILIO_ACCOUNT_SID;
_17
const authToken = process.env.TWILIO_AUTH_TOKEN;
_17
const client = require('twilio')(accountSid, authToken);
_17
_17
client.conversations.v1.addressConfigurations
_17
.create({
_17
'autoCreation.enabled': true,
_17
'autoCreation.type': 'studio',
_17
'autoCreation.studioFlowSid': 'FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
_17
'autoCreation.studioRetryCount': 3,
_17
type: 'whatsapp',
_17
address: 'whatsapp:+13115552368'
_17
})
_17
.then(address_configuration => console.log(address_configuration.sid));

Output

_22
{
_22
"account_sid": "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
_22
"sid": "IGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
_22
"address": "whatsapp:+13115552368",
_22
"type": "whatsapp",
_22
"friendly_name": "My Test Configuration",
_22
"address_country": "CA",
_22
"auto_creation": {
_22
"enabled": true,
_22
"type": "webhook",
_22
"conversation_service_sid": "ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
_22
"webhook_url": "https://example.com",
_22
"webhook_method": "POST",
_22
"webhook_filters": [
_22
"onParticipantAdded",
_22
"onMessageAdded"
_22
]
_22
},
_22
"date_created": "2016-03-24T21:05:50Z",
_22
"date_updated": "2016-03-24T21:05:50Z",
_22
"url": "https://conversations.twilio.com/v1/Configuration/Addresses/IGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
_22
}

For deleting a WhatsApp address via the API, see Delete Address Configuration.


Configuring WhatsApp Sandbox

configuring-whatsapp-sandbox page anchor

These instructions are for setting up WhatsApp Sandbox to work with Flex Conversations. If you have a registered WhatsApp number, refer to the instructions above rather than this section. Registered WhatsApp numbers are set up similarly to SMS.

  1. Since we don't have auto-create support for WhatsApp Sandbox, we will need to intercept incoming messages to create Conversations. Create another function with the following code. This uses the same Studio Flow as the SMS instructions and has been tested on Node v12, v14, and v16 runtime:

    • Declare twilio as a dependency. This automatically imports related npm modules into your Function.

      node-runtime-flex.
    • Set STUDIO_FLOW_SID as an environment variable using the unique ID (prefixed by FW) of your newly created Studio Flow.

      • Please note that this function does not handle creating a conversation correctly when the first WhatsApp message is an attachment. This may result in warnings/errors logged by the Studio Flow. This is not an issue for non-sandbox WhatsApp addresses.
    • whatsapp.protected.js


      _97
      /* Handles WhatsApp messages by
      _97
      * 1. Creating a conversation
      _97
      * 2. Adding the participant that sent that message
      _97
      * 3. Adding the message to the conversation
      _97
      * If any of these fail, the conversation is deleted
      _97
      */
      _97
      exports.handler = async function(context, event, callback) {
      _97
      const isConfigured = context.STUDIO_FLOW_SID;
      _97
      const response = new Twilio.Response();
      _97
      response.appendHeader('Access-Control-Allow-Origin', '*');
      _97
      response.appendHeader('Access-Control-Allow-Methods', 'GET,POST,OPTIONS');
      _97
      response.appendHeader('Content-Type', 'application/json');
      _97
      response.appendHeader('Access-Control-Allow-Headers', 'Content-Type');
      _97
      _97
      console.log(`Received Event: ${JSON.stringify(event)}`);
      _97
      _97
      if ( !isConfigured) {
      _97
      response.setBody({
      _97
      status: 500,
      _97
      message: "Studio Flow SID is not configured"
      _97
      });
      _97
      callback(null, response);
      _97
      return;
      _97
      }
      _97
      _97
      const client = context.getTwilioClient();
      _97
      _97
      let conversation;
      _97
      const webhookConfiguration = {
      _97
      'target': 'studio',
      _97
      'configuration.flowSid': context.STUDIO_FLOW_SID,
      _97
      'configuration.replayAfter': 0,
      _97
      'configuration.filters': ['onMessageAdded']
      _97
      };
      _97
      _97
      try {
      _97
      conversation = await client.conversations.v1.conversations.create({'xTwilioWebhookEnabled':true,});
      _97
      console.log(`Created Conversation with sid ${conversation.sid}`);
      _97
      try {
      _97
      console.log(`Adding studio webhook to conversation ${conversation.sid}`);
      _97
      await client.conversations.v1.conversations(conversation.sid)
      _97
      .webhooks
      _97
      .create(webhookConfiguration);
      _97
      } catch(error) {
      _97
      console.log(`Got error when configuring webhook ${error}`);
      _97
      response.setStatusCode(500);
      _97
      return callback(error, response);
      _97
      }
      _97
      } catch( error) {
      _97
      console.log(`Couldnt create conversation ${error}`)
      _97
      return callback(error)
      _97
      }
      _97
      _97
      try {
      _97
      const participant = await client.conversations.v1.conversations(conversation.sid)
      _97
      .participants
      _97
      .create({
      _97
      'messagingBinding.address': `${event.From}`,
      _97
      'messagingBinding.proxyAddress': `${event.To}`
      _97
      });
      _97
      console.log(`Added Participant successfully to conversation`)
      _97
      } catch(error) {
      _97
      console.log(`Failed to add Participant to conversation, ${error}`)
      _97
      console.log(`In case the error is something about "A binding for this participant and proxy address already exists", check if you havent used the Sandbox in any other instance you have. As Whatsapp Sandbox uses the same number across all accounts, could be that the binding of [Your Phone] + [Sandbox WA number] is already created in the other instance.`)
      _97
      try {
      _97
      await client.conversations.v1.conversations(conversation.sid).remove();
      _97
      console.log("Deleted conversation successfully")
      _97
      } catch (error) {
      _97
      console.log(`Failed to remove conversation, ${error}`)
      _97
      }
      _97
      return callback(null,"");
      _97
      }
      _97
      _97
      // Now add the message to the conversation
      _97
      try {
      _97
      const body = event.Body !== '' ? event.Body : 'Empty body, maybe an attachment. Sorry this function doesnt support adding media to the conversation. This should work post private beta';
      _97
      console.log(`Setting body to ${body}`)
      _97
      const message = await client.conversations.v1.conversations(conversation.sid)
      _97
      .messages
      _97
      .create({
      _97
      'author': `${event.From}`,
      _97
      'body': `${body}`,
      _97
      'xTwilioWebhookEnabled':true,
      _97
      });
      _97
      console.log(`Added message successfully to conversation`)
      _97
      } catch(error) {
      _97
      console.log(`Failed to add message to conversation, ${error}`)
      _97
      try {
      _97
      await client.conversations.v1.conversations(conversation.sid).remove();
      _97
      } catch (error) {
      _97
      console.log(`Failed to remove conversation, ${error}`)
      _97
      }
      _97
      return callback(null, `${error}`);
      _97
      }
      _97
      _97
      return callback(null, "");
      _97
      };

  2. Set your function as protected and deploy your Function and copy the Function URL. If you are using the Twilio Console to add your function, you can click on the three dots next to the Function name and select "Copy URL".
  3. Go to WhatsApp Sandbox Settings(link takes you to an external page) and register the number you are using for testing. In the Sandbox Configuration section, paste the Function URL into the "WHEN A MESSAGE COMES IN" field.
  4. If you haven't registered your WhatsApp number in the sandbox, do that now by following the instructions in the WhatsApp Participants section. For example, in the case below, you would send "join cloud-forgot" to the number +1 415 523 8886 from your WhatsApp.

    Register the WhatsApp number in the sandbox.
  5. Note that this registration is valid for 3 days and you will have to re-register after that period.
  6. Save your settings.
  7. You can now test the WhatsApp integration by sending a message from your WhatsApp to your Sandbox phone number.
  8. If everything has been configured correctly, this should render as an incoming WhatsApp task in your Flex application. Follow steps 1 and 2 of "Send your first SMS" to accept the incoming task and test WhatsApp in Flex.

    Incoming WhatsApp task in your Flex application.

Rate this page: