Skip to contentSkip to navigationSkip to topbar
On this pageProducts used

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 APILink to code sample: Create a WhatsApp Address via the API
1
// Download the helper library from https://www.twilio.com/docs/node/install
2
const twilio = require("twilio"); // Or, for ESM: import twilio from "twilio";
3
4
// Find your Account SID and Auth Token at twilio.com/console
5
// and set the environment variables. See http://twil.io/secure
6
const accountSid = process.env.TWILIO_ACCOUNT_SID;
7
const authToken = process.env.TWILIO_AUTH_TOKEN;
8
const client = twilio(accountSid, authToken);
9
10
async function createConfigurationAddress() {
11
const addressConfiguration =
12
await client.conversations.v1.addressConfigurations.create({
13
address: "whatsapp:+13115552368",
14
"autoCreation.enabled": true,
15
"autoCreation.studioFlowSid": "FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
16
"autoCreation.studioRetryCount": 3,
17
"autoCreation.type": "studio",
18
type: "whatsapp",
19
});
20
21
console.log(addressConfiguration.sid);
22
}
23
24
createConfigurationAddress();

Output

1
{
2
"account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
3
"sid": "IGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
4
"address": "whatsapp:+13115552368",
5
"type": "whatsapp",
6
"friendly_name": "My Test Configuration",
7
"address_country": "CA",
8
"auto_creation": {
9
"enabled": true,
10
"type": "webhook",
11
"conversation_service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
12
"webhook_url": "https://example.com",
13
"webhook_method": "POST",
14
"webhook_filters": [
15
"onParticipantAdded",
16
"onMessageAdded"
17
]
18
},
19
"date_created": "2016-03-24T21:05:50Z",
20
"date_updated": "2016-03-24T21:05:50Z",
21
"url": "https://conversations.twilio.com/v1/Configuration/Addresses/IGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
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

      1
      /* Handles WhatsApp messages by
      2
      * 1. Creating a conversation
      3
      * 2. Adding the participant that sent that message
      4
      * 3. Adding the message to the conversation
      5
      * If any of these fail, the conversation is deleted
      6
      */
      7
      exports.handler = async function(context, event, callback) {
      8
      const isConfigured = context.STUDIO_FLOW_SID;
      9
      const response = new Twilio.Response();
      10
      response.appendHeader('Access-Control-Allow-Origin', '*');
      11
      response.appendHeader('Access-Control-Allow-Methods', 'GET,POST,OPTIONS');
      12
      response.appendHeader('Content-Type', 'application/json');
      13
      response.appendHeader('Access-Control-Allow-Headers', 'Content-Type');
      14
      15
      console.log(`Received Event: ${JSON.stringify(event)}`);
      16
      17
      if ( !isConfigured) {
      18
      response.setBody({
      19
      status: 500,
      20
      message: "Studio Flow SID is not configured"
      21
      });
      22
      callback(null, response);
      23
      return;
      24
      }
      25
      26
      const client = context.getTwilioClient();
      27
      28
      let conversation;
      29
      const webhookConfiguration = {
      30
      'target': 'studio',
      31
      'configuration.flowSid': context.STUDIO_FLOW_SID,
      32
      'configuration.replayAfter': 0,
      33
      'configuration.filters': ['onMessageAdded']
      34
      };
      35
      36
      try {
      37
      conversation = await client.conversations.v1.conversations.create({'xTwilioWebhookEnabled':true,});
      38
      console.log(`Created Conversation with sid ${conversation.sid}`);
      39
      try {
      40
      console.log(`Adding studio webhook to conversation ${conversation.sid}`);
      41
      await client.conversations.v1.conversations(conversation.sid)
      42
      .webhooks
      43
      .create(webhookConfiguration);
      44
      } catch(error) {
      45
      console.log(`Got error when configuring webhook ${error}`);
      46
      response.setStatusCode(500);
      47
      return callback(error, response);
      48
      }
      49
      } catch( error) {
      50
      console.log(`Couldnt create conversation ${error}`)
      51
      return callback(error)
      52
      }
      53
      54
      try {
      55
      const participant = await client.conversations.v1.conversations(conversation.sid)
      56
      .participants
      57
      .create({
      58
      'messagingBinding.address': `${event.From}`,
      59
      'messagingBinding.proxyAddress': `${event.To}`
      60
      });
      61
      console.log(`Added Participant successfully to conversation`)
      62
      } catch(error) {
      63
      console.log(`Failed to add Participant to conversation, ${error}`)
      64
      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.`)
      65
      try {
      66
      await client.conversations.v1.conversations(conversation.sid).remove();
      67
      console.log("Deleted conversation successfully")
      68
      } catch (error) {
      69
      console.log(`Failed to remove conversation, ${error}`)
      70
      }
      71
      return callback(null,"");
      72
      }
      73
      74
      // Now add the message to the conversation
      75
      try {
      76
      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';
      77
      console.log(`Setting body to ${body}`)
      78
      const message = await client.conversations.v1.conversations(conversation.sid)
      79
      .messages
      80
      .create({
      81
      'author': `${event.From}`,
      82
      'body': `${body}`,
      83
      'xTwilioWebhookEnabled':true,
      84
      });
      85
      console.log(`Added message successfully to conversation`)
      86
      } catch(error) {
      87
      console.log(`Failed to add message to conversation, ${error}`)
      88
      try {
      89
      await client.conversations.v1.conversations(conversation.sid).remove();
      90
      } catch (error) {
      91
      console.log(`Failed to remove conversation, ${error}`)
      92
      }
      93
      return callback(null, `${error}`);
      94
      }
      95
      96
      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. Under Sandbox Configuration , 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.

Need some help?

Terms of service

Copyright © 2024 Twilio Inc.