Advanced Cloud Code

Using cloud functions to send WhatsApp messages through Twilio API

Introduction

In this guide, we will explain how you can use Twilio’s streamlined REST API to send WhatsApp messages easily. After completing this tutorial, you can use a cloud code function to send WhatsApp messages to your customers. So, let’s get down to business.

Prerequisites

To complete this tutorial, you will need:

Let’s get started!

As you may know, WhatsApp has recently released the first version of an API to use this service to the Business API, which allows large businesses to manage and send non-promotional messages to customers.

Since WhatsApp is providing an API, Twilio that offers cloud communication is providing a feature that communicates with that service, at the moment, the Twilio API for WhatsApp is in BETA and is only possible to send text messages to a WhatsApp user. In other words still not possible to send images, videos and send messages to a group of users.

The feature used to send messages is called as Twilio Sandbox and emulates a user that will send messages to a real WhatsApp number.

Note: The Twilio Sandbox for WhatsApp that have some limitations, only will work to receive messages from your specific Sandbox that you will activate at step 1, if you want to Activate your own number to others users receive the messages, you need to request it directly at Twilio Console.

In this guide, we will show how you can integrate your App to send messages directly to WhatsApp using Twilio as an middleware. We will write a Cloud Function that will connect to a Twilio API to send those messages. Once this function will be triggered by a saving event we call this function an AfterSave.

To create or access an Account in Twilio, check the links given below:

Create a new account - Log in to your account

Step 1 - Activate your WhatsApp Beta

After logging in to an existing account, you will be redirected to your Project. But, if you are a new user, you’ll first need to create a project and select programmable SMS from products. You should now see the recently created project on your console. Next, you must click on the programmable SMS and select the 4th option WhatsApp Beta and then follow the Steps given in that section to activate the Twilio Sandbox for WhatsApp. Same as shown below:

Activating the Twilio Sandbox for WhatsApp

Step 2 - Get Account SID and Auth Token

To find your Account SID and Auth Token, log in to your Twilio Account, go to your Dashboard and click on Settings. All the important information about your Project will be available in that section. Make sure that all these instructions are followed as shown in the image below:

Account Settings

Now, you can Copy your SID and Authentication Token for the Cloud Code.

Step 3 - Install Module from Twilio

After configuring the environment for the Command Line Interface in your computer, create a file called package.json, and inside this file, you need to install the Twilio module, like:

1
2
3
4
5
{
  "dependencies": {
    "twilio": "*"
  }
}

Step 4 - Implement Cloud Code

In this section, we will show you know how to work with the Cloud Functions.

We will build an afterSave Trigger function to activate and send the confirmation message that the object has been saved.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
Parse.Cloud.afterSave("Contact",function(request){

    // Requiring the values to send
    var 
        getPhoneTo   = request.object.get("phone"),
        getFirstName = request.object.get("firstName"),
        getPhoneFrom = "+Your Phone number", //Remember to replace your number enable on Twilio Sandbox
        accountSid = 'AccountSID',
        authToken  = 'AuthToken',
        getMessage   = "Welcome " + getFirstName +" to our Platform! Thank you for your interest, our team will contact you ASAP! ;)";

    //require the Twilio module and create a REST client
    var client = require('twilio')(accountSid, authToken);

    client.messages
        .create(
        {
            from: "whatsapp:" + getPhoneFrom, 
            body: getMessage, 
            to: "whatsapp:" + getPhoneTo
        })
        .then(message => console.log(message.sid))
        .done();  
});

Step 5 - Test the AfterSave Trigger

Now that we have created and activated the afterSave trigger, it’s time to test the function whether it’s working faultlessly or not. You can also test the function in client SDKs, but for now, we will use the REST API command to save a new User:

curl -X POST \
  -H "X-Parse-Application-Id: ${APPLICATION_ID}" \
  -H "X-Parse-REST-API-Key: ${REST_API_KEY}" \
  -H "Content-Type: application/json" \
  -d '{"firstName":"Natália", "phone":"+0000000000000"}' \
  https://parseapi.back4app.com/classes/Contact

And the result will be similar to the screenshot below.

Send SMS using Twilio

Step 6 - It’s done!

With the guide described above, you’ll be able to use Twilio with a Cloud Code Function in Back4App and send WhatsApp messages to your opted-in customers!

In case you need any help or a function/link doesn’t work, please contact our team via chat!