Salesforce WhatsApp Integration via Twilio

Introduction
Salesforce WhatsApp Integration via Twilio

In one of the previous post on inteygrate we made an attempt to integrate Salesforce with WhatsApp using an unofficial library Yowsup. We were successfully able to make the connection using a middleware code in Python and send messages from Salesforce to WhatsApp. But lately after many upgrades of WhatsApp the library isn't being supported well and has got many issues during registration, also leading to the numbers being blocked by WhatsApp.

So can we no longer integrate Salesforce with WhatsApp? Yes we can; because now Facebook has officially released APIs for WhatsApp. But, hold on! You cannot start using it right away 😥. Its because they are not completely public yet and Facebook is conditionally providing access to businesses after scrutinising the application to be submitted by businesses before getting access to the APIs.


So, What is Twilio?

Fortunately, we have Twilio - a middleware, a cloud communications platform as a service that allows software developers to programmatically make and receive phone calls, send and receive text messages, and perform other communication functions using its web service APIs. There are other middleware's as well like Zapier, Smooch etc. and these tools expect you to already have your Business WhatsApp number approved for API access. Whereas Twilio API for WhatsApp provides Sandbox numbers that we can use to try out our integration for sending and receiving messages to WhatsApp users.

Watch the below video to understand how Twilio helps businesses to manage Customer engagement across Channels in one single place.

What is Twilio?

Now let us quickly see a Demo of the integration using Twilio and we will then take a look at the steps for the same.

Demo

Case creation when customer reports an issue

Reply to customer when a comment is added

Subsequent replies from Customer Saved as Comments on the Case

Get Started with the Twilio API for WhatsApp

The Twilio API for WhatsApp is the quickest way to integrate two-way messaging on WhatsApp into any web application including Salesforce using 6 popular web languages (Python, C#/.NET, PHP, Java, Node.js, Ruby). In the below Quickstart we will see how to do this using the Twilio Sandbox for WhatsApp, Python, the Twilio Python helper library, and the Flask web framework.


Twilio API for WhatsApp Python Quickstart

Sign up for Twilio and activate the Sandbox

Before you can send a WhatsApp message from your web language, you'll need to sign up for a Twilio account or sign into your existing account and activate the Twilio Sandbox for WhatsApp. It allows you to prototype with WhatsApp immediately using a shared phone number, without waiting for a dedicated number to be approved by WhatsApp.

Gather your Twilio account information:

Once you signup for Twilio, it will launch Twilio Console. Make a note of following details from Console which will be used in the Heroku app.

Twilio Account SID and Auth Token

Opt-in to the Sandbox

Twilio Sandbox Number for WhatsApp

Once you join the sandbox by sending the message, you will receive a confirmation message as shown below:

Register Your WhatsApp with Twilio Sandbox

Send Messages from Salesforce to WhatsApp

In our demo case whenever an executive adds a comment to the Case or when a new case is created the corresponding trigger handler makes a callout to the Heroku app that has the Twilio Python wrapper code hosted.

Below is the Apex code making callout to Heroku

public class CaseCommentTriggerHandler{
    @future(callout=true)
    public static void createCaseComment(List<Id> csIds){
        List<CaseComment> csList = new List<CaseComment>();
        if(csIds != null && csIds.size() > 0){
            csList = [SELECT id, 
                             CommentBody,
                             Parent.CaseNumber,
                             Parent.Subject,
                             Parent.Description,
                             Parent.ContactPhone 
                             FROM
                             CaseComment WHERE Id IN :csIds];
        }
        
        Http h = new Http();
        HttpResponse response = new Httpresponse();
        HttpRequest req = new HttpRequest();     
        req.setMethod('GET');
        String endpoint = '';
        if(csList != null && csList.size () > 0){
            String caseComments = EncodingUtil.URLENCODE('Salesforce Case '+csList[0].Parent.CaseNumber+' has been updated for you with the comments: '+csList[0].CommentBody,'UTF-8');
            endpoint ='https://<your-heroku-app-url>/?to='+csList[0].Parent.ContactPhone+'&msg='+caseComments;
        }
        req.setEndpoint(endpoint);
        response = h.send(req);
    }
}

And below is the Twilio Python wrapper code and following are the Auth parameters configured in Heroku in Config Vars

from flask import Flask
from flask import request
import os
from twilio.rest import Client
app = Flask(__name__)

@app.route('/')
def twilio_heroku_app():
    account_sid = os.environ.get('account_sid', None)
    auth_token = os.environ.get('auth_token', None)
    sandbox_number = os.environ.get('sandbox_number', None)
    to_number = request.args.get('to')
    msg_body = request.args.get('msg')
    
    client = Client(account_sid, auth_token)

    message = client.messages.create(
                                  body=msg_body,
                                  from_='whatsapp:'+sandbox_number,
                                  to='whatsapp:+91'+to_number
                              )

    return message.sid

if __name__ == '__main__':
    app.run()
Heroku Config Vars

Capture Replies from WhatsApp in Salesforce

When a customer replies to your WhatsApp Sandbox number, the same can be captured in Salesforce by configuring a web service in Salesforce with Twilio Webhook as shown below. The Salesforce web service must accept POST request and will have the business logic to perform desired actions like logging cases in Salesforce etc.

Twilio Webhook Configuration for WhatsApp

The web service in Salesforce will receive the Message text, the From number, the To number and other details in the body of the request that can be used to create a Case or add comment to an open case for the existing customer (that can be identified from the Contact and/or Account created with the From number) upon receiving a message in WhatsApp.

In subsequent articles I will explore the other communication channels available with Twilio and integrate the same with Salesforce.


Author

Prathyusha Narla

I strongly believe in David H Wilson's quote "..things grow stronger when we integrate them". And so at inteygrate.com I am exploring the middleware's to integrate Salesforce to the World

View Comments
Previous Post

Salesforce Code Quality Monitoring with Bluefactory.io