Menu

Manage Conversations WhatsApp Addresses

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

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.

via the Flex Console

To get started, navigate to Messaging > Senders > WhatsApp senders 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:

  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.
    Screen Shot 2022-03-09 at 2.15.07 PM.png
  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.

via the API

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.

Loading Code Sample...
        
        

        Create a WhatsApp Address via the API

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

        Configuring WhatsApp Sandbox

        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
            /* Handles WhatsApp messages by
            * 1. Creating a conversation
            * 2. Adding the participant that sent that message
            * 3. Adding the message to the conversation
            * If any of these fail, the conversation is deleted
            */
            exports.handler = async function(context, event, callback) {
              const isConfigured = context.STUDIO_FLOW_SID;
              const response = new Twilio.Response();
             response.appendHeader('Access-Control-Allow-Origin', '*');
             response.appendHeader('Access-Control-Allow-Methods', 'GET,POST,OPTIONS');
             response.appendHeader('Content-Type', 'application/json');
             response.appendHeader('Access-Control-Allow-Headers', 'Content-Type');
            
             console.log(`Received Event: ${JSON.stringify(event)}`);
            
             if ( !isConfigured) {
                response.setBody({
                       status: 500,
                       message: "Studio Flow SID is not configured"
                   });
                   callback(null, response);
                   return;
             }
            
             const client = context.getTwilioClient();
            
             let conversation;
               const webhookConfiguration = {
               'target': 'studio',
               'configuration.flowSid': context.STUDIO_FLOW_SID,
               'configuration.replayAfter': 0,
               'configuration.filters': ['onMessageAdded']
             };
            
             try {
               conversation = await client.conversations.v1.conversations.create({'xTwilioWebhookEnabled':true,});
               console.log(`Created Conversation with sid ${conversation.sid}`);
               try {
                 console.log(`Adding studio webhook to conversation ${conversation.sid}`);
                 await client.conversations.v1.conversations(conversation.sid)
                     .webhooks
                     .create(webhookConfiguration);   
               } catch(error) {
                 console.log(`Got error when configuring webhook ${error}`);
                 response.setStatusCode(500);
                 return callback(error, response);
               }
             } catch( error) {
               console.log(`Couldnt create conversation ${error}`)
               return callback(error)
             }
            
             try {
               const participant = await client.conversations.v1.conversations(conversation.sid)
                               .participants
                               .create({
                                  'messagingBinding.address': `${event.From}`,
                                  'messagingBinding.proxyAddress': `${event.To}`
                                });
               console.log(`Added Participant successfully to conversation`)
             } catch(error) {
               console.log(`Failed to add Participant to conversation, ${error}`)
               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.`)
               try {
                 await client.conversations.v1.conversations(conversation.sid).remove();
                 console.log("Deleted conversation successfully")
               } catch (error) {
                 console.log(`Failed to remove conversation, ${error}`)
               }
               return callback(null,"");
             }
            
             // Now add the message to the conversation
            try {
               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';
               console.log(`Setting body to ${body}`)
               const message = await client.conversations.v1.conversations(conversation.sid)
                               .messages
                               .create({
                                  'author': `${event.From}`,
                                  'body': `${body}`,
                                  'xTwilioWebhookEnabled':true,
                                });
               console.log(`Added message successfully to conversation`)
             } catch(error) {
               console.log(`Failed to add message to conversation, ${error}`)
               try {
                 await client.conversations.v1.conversations(conversation.sid).remove();
               } catch (error) {
                 console.log(`Failed to remove conversation, ${error}`)
               }
               return callback(null, `${error}`);
             }
            
             return callback(null, "");
            };
        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 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.
          Screen Shot 2022-03-10 at 9.16.18 AM.png
        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.
          Screen Shot 2022-03-10 at 9.18.53 AM.png
        Rate this page:

        Need some help?

        We all do sometimes; code is hard. Get help now from our support team, or lean on the wisdom of the crowd by visiting Twilio's Stack Overflow Collective or browsing the Twilio tag on Stack Overflow.

        Thank you for your feedback!

        Please select the reason(s) for your feedback. The additional information you provide helps us improve our documentation:

        Sending your feedback...
        🎉 Thank you for your feedback!
        Something went wrong. Please try again.

        Thanks for your feedback!

        thanks-feedback-gif