メニュー

Manage Conversations WhatsApp Addresses

This Twilio product is currently available as a Beta release. Some features are not yet implemented and others may be changed before the product is declared as Generally Available. Use of this Beta release is subject to the relevant terms of the applicable license agreement. Beta products are not covered by a Twilio SLA. Learn more about beta product support.

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

Create a WhatsApp Address via Flex Console

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. 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.
    • You can use the same Studio Flow that you created earlier
  6. Click Submit to save your new Flex WhatsApp Address.

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

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 and v14 runtime:
    • Declare twilio as a dependency. This automatically imports related npm modules into your Function.
      Screen Shot 2022-03-09 at 2.19.17 PM.png
    • 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.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.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.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}`)
         try {
           await client.conversations.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.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.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
ページを評価:

ヘルプが必要ですか?

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.

フィードバックくださりありがとうございます!

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!

Refer us and get $10 in 3 simple steps!

ステップ1

Get link

Get a free personal referral link here

ステップ2:

Give $10

Your user signs up and upgrade using link

ステップ3

Get $10

1,250 free SMSes
OR 1,000 free voice mins
OR 12,000 chats
OR more