Torna alle notizie per sviluppatori

Send Interactive Messages on the WhatsApp Business Platform

21 novembre 2022DiRashed Talukder

With the introduction of the Cloud API, hosted by Meta, on the WhatsApp Business Platform, companies are finding new ways to leverage the power of WhatsApp in their projects. One of those discoveries is the WhatsApp interactive messaging feature – making communication even richer and allowing companies to engage with their customers beyond a standard text message.

This article highlights the WhatsApp interactive messaging features and explores how you can send interactive messages with the Cloud API. It demonstrates how to do this using a simple Node.js application.

Interactive Messages

Interactive messages are messages a user can interact with using prompts provided in the message. A user can, for example, select an item they would like from a list of product options.

Additionally, interactive messages enable you to provide tailored options for a user so they won’t have to go through an extensive list of products on your website. This type of messaging can help you achieve higher response rates.

The article looks at two interactive message features provided by the Cloud API — list messages and reply buttons — and how to use them.

List messages include a menu of up to ten options users can choose from. The menu offers an overview of options available to the user. These can include restaurant specials, delivery times, appointment times, t-shirt colors, and more.

Reply buttons offer a selection of up to three buttons in a message that a user can select from to reply to the message. The buttons quickly respond to messages with discrete answers, like yes or no.

You can chain these different message types in a conversation flow. For example, you can combine a list message and a reply button to allow the user to select an option and perform an action based on the selection.

These types of messages are limited to replies to a user-initiated conversation within a 24-hour window after user contact.

Adding Interactive Messages to an App

Now that you’re familiar with interactive messages, here is how you can implement these interactive messages in your applications. Before jumping into this tutorial, register as a Meta Developer and create an app. You can find more information here.

Creating a Meta app gets you a temporary access token, test phone number, and phone number ID. You must add a recipient phone number to receive the example messages. You'll need to keep note of these values for later.

Prerequisites

You must have Node.js and an Integrated Development Environment (IDE) installed that is able to parse the Javascript and other files. This article will demonstrate development on Visual Studio Code. You’ll need to launch part of the application as a Heroku app following steps outlined in their docs but using the application code referenced here.

To send and receive WhatsApp messages using a test phone number, complete the Set up Developer Assets and Platform Access tutorials. You’ll use the URI for your Heroku app to set up the webhook.

The complete code for this project is available on GitHub, including the Node.js application code.

Set Up the Environment

To send an interactive message, you’ll make an HTTP request to:

 https://graph.facebook.com/{{API_VERSION}}/{{YOUR_PHONE_NUMBER_ID}}/messages.

and attach a message object, set type=interactive, and add the interactive object.

To see this in action, you must create a Node.js application using the following steps.

Create a folder in which you will store the application. Open that folder in VS Code. Open a terminal window and run the command npm init to set up a new npm package for the project. Accept all the defaults and reply yes to the prompts. You should now have a project folder with a package.json file like this:

For the convenience of having all of your configuration in one place, and not scattered throughout code during development, place it in a file.

Create a .env file at the project root with the following configurations:

APP_ID=<<YOUR-WHATSAPP-BUSINESS-APP_ID>>
APP_SECRET=<<YOUR-WHATSAPP-BUSINESS-APP_SECRET>>
RECIPIENT_PHONE_NUMBER=<<THE-TEST-RECIPIENT-PHONE-NUMBER>>
VERSION=v13.0
PHONE_NUMBER_ID=<<YOUR-WHATSAPP-BUSINESS-PHONE-NUMBER-ID>>
ACCESS_TOKEN=<<YOUR-SYSTEM-USER-ACCESS-TOKEN>>

Now create a new file and call it index.js on the same level as package.json. Install Axios, to make asynchronous calls to the Graph API. Run the command npm install axios to install the latest version.

Now that you’ve got the environment set up, copy and paste this code into the index.js file:

const axios = require("axios");
require('dotenv').config();

const accessToken = process.env.ACCESS_TOKEN;
const apiVersion = process.env.VERSION;
const recipientNumber = process.env.RECIPIENT_PHONE_NUMBER;
const myNumberId = process.env.PHONE_NUMBER_ID;

// Update this variable to the interactive object to send
const interactiveObject = {}; 

let messageObject = {
    messaging_product: "whatsapp",
    recipient_type: "individual",
    to: `${recipientNumber}`,
    type: "interactive",
    interactive: listInteractiveObject
};
 
axios
  .post(
    `https://graph.facebook.com/${apiVersion}/${myNumberId}/messages`,
    messageObject,
    {
      headers: {
        Authorization: `Bearer ${accessToken}`,
      },
    }
  );

Now, create an interactive object for each message type.

List Messages

Modify interactiveObject as follows:

const interactiveObject = {
  type: "list",
  header: {
    type: "text",
    text: "Select the food item you would like.",
  },
  body: {
    text: "You will be presented with a list of options to choose from",
  },
  footer: {
    text: "All of them are freshly packed",
  },
  action: {
    button: "Order",
    sections: [
      {
        title: "Section 1 - Fruit",
        rows: [
          {
            id: "1",
            title: "Apple",
            description: "Dozen",
          },
          {
            id: "2",
            title: "Orange",
            description: "Dozen",
          },
        ],
      },
      {
        title: "Section 2 - Vegetables",
        rows: [
          {
            id: "3",
            title: "Spinach",
            description: "1kg ",
          },
          {
            id: "2",
            title: "Broccoli",
            description: "1kg",
          },
        ],
      },
    ],
  },
};

The object above defines a list message with items grouped into the two categories of fruits and vegetables. Each category has two items.

Now, you’re ready to send a list message. But remember, you can send lists and buttons only as a reply to a user-initiated message. So first, send a message from your test recipient's phone number to your test business number. Once you’ve initiated the conversation, run the command node index.js in the terminal.

The recipient receives a message as follows and can respond by clicking the Send button:

With list messages, the user can select their preferred items from a provided list — here, one dozen oranges. However, current list capabilities only allow selecting one item at a time, and a customer who needs multiple selections will need to reuse the same list for each choice.

Reply Buttons

Next, let’s look at how to use reply buttons to reply quickly to messages or questions you send.

To send a message with reply buttons, assign the reply buttons object to interactiveObject as follows:

const interactiveObject = {
  "type": "button",
  "header": {
      "type": "text",
      "text": "Dear valued customer."
  },
  "body": {
      "text": "Would you like to receive marketing messages from us in the future?"
  },
  "footer": {
      "text": "Please select an option"
  },
  "action": {
      "buttons": [
          {
              "type": "reply",
              "reply": {
                  "id": "1",
                  "title": "Yes"
              }
          },
          {
              "type": "reply",
              "reply": {
                  "id": "2",
                  "title": "No"
              }
          },
          {
              "type": "reply",
              "reply": {
                  "id": "3",
                  "title": "Never"
              }
          }
      ]
  }
}

This defines a message with three buttons that a user can click as a response.

Again, run the command node index.js. The recipient receives a message and can reply by clicking one of the buttons as follows:

Combine List Messages and Reply Buttons

So far, you've seen how to send both lists and reply buttons in separate messages. To make this more exciting and engaging for your users, you can combine the list message and reply buttons into a single message flow. To do that, you have to be able to respond to messages coming in with the appropriate message.

For instance, based on the previous examples, when a user initiates a conversation, you send a list message with options for them to choose. When they respond with an option, you can then send a message with reply buttons so they can confirm their choice.

For this to work, you must know when a user sends a message. You’ll receive these notifications by setting up webhooks, a feature of the WhatsApp Business Platform.

While the article above goes into greater detail, here is a basic build to use in this tutorial:

  • Create an endpoint on a secure server that can process HTTPS requests. For this tutorial, you can create a Node.js application.
  • Add the code provided below and deploy it to Heroku. You can find more information here about how you can deploy a Node.js application to Heroku. You must create a free Heroku account before you can deploy.
  • Save the project in a GitHub repository and use the GitHub method to deploy it to Heroku.

Now, you’re ready to add the code to your application. Replace the index.js file with the index.js file on GitHub.

Run the command npm install body-parser dotenv express x-hub-signature axios to install the required dependencies. Now, commit this code and deploy it to Heroku. The flow then works as follows:

And there you have it! You’ve created an engaging, interactive message flow by combining list messages and button replies.

Conclusion

This article looked at two types of interactive messages, list messages and button replies, and showed how you could implement them in a Node.js application. It also looked at a more practical scenario where you combined the two message types into a single flow.

You can provide an engaging messaging experience to your customers with interactive messages. These engagement-boosting menu options, like list messages and button replies, help create a richer user experience.

With the WhatsApp Business Platform, you can fully automate customer interactions and achieve significantly higher response rates. Head to our Cloud API Documentation to learn more about building production-ready applications.