Hello Friends, In this article I will show you how to integrate WhatsApp with Salesforce. For this I will also show you how to read any API documentation and collect necessary information for any integration, how to parse JSON response. I will walk you through every single step so that you can gain confidence with integration.
It is a long article, but trust me its worth it as it covers every concept. I hope you enjoy the reading.
Target Audience
The target audience for this article is someone who has basic knowledge about HTTP and interested in Lightning web component (LWC)
Prerequisite
- Basic Knowledge about REST, HTTP Request, Response is an advantage
- Basic Knowledge of LWC is an advantage
Preface
In this article I will go through:
- Demo Video
- Explain the given scenario: Send Message from Salesforce to WhatsApp
- Different mediums used for Salesforce – Whatsapp integration
- Best Solution: Using Twilio API to integrate WhatsApp with Salesforce
- HTTP Protocol Basics
- How to read API documentation to send HTTP Request
- Ways to parse JSON
- Code Snippet
Learning
After going through this article you will be able to:
- Read any API documentation
- Understand Salesforce-Whatsapp integration
- Understand Lightning Web Component
Demo Video
Introduction
In Present scenario, most of the people use WhatsApp to communicate with each other. Now if business start providing services to clients directly on whatsapp then it will increase customer satisfaction to another level. So lets see what options we have for integration.
Integration Options
It is a managed package that integrates Salesforce with WhatsApp. It is $39 per month
I checked Facebook has released API for WhatsApp, which is free but they are not completely public yet and Facebook is conditionally providing access to businesses after carefully evaluating the application to be submitted by businesses before getting access to the APIs.
There is a free open source in github- yousum. However, many people who have tried yousum, there number have got instantly banned.
Twilio API for WhatsApp provides Sandbox numbers that we can use to try out our integration for sending and receiving messages to WhatsApp users. For this article we will use Twilio to integrate with Whatsapp.
Twilio provides both free and paid version. I am using free version in this case.
Section 1: HTTP Protocol Basics
For any integration, client sends HTTP request and gets HTTP response from the server. Therefore, its very important to understand what goes in HTTP request and response.
HTTP Request:
- Request Line : Method SP URI SP HTTP-Version
- Request Header
- Request Body
HTTP Response:
- Status-Line = HTTP-Version SP Status-Code SP Reason-Phrase CRLF
- Response Body
Please refer to HTTP Protocol Basics
Twilio API
Section 2: Reading API Documentation
In this Section I will show you how to read any API documentation and collect information needed to send in HTTP Request.Steps for collecting information remains almost the same for any integration.
Step 1: Refer Documentation
Step 2: Find Base URL
Step 3: Hit the Base URL
Step 4: Form the end point URL
Step 5: Type of Authentication
Step 6: Parameters passed in the request body
Step 7: Deserialize the values coming in response body
Confused? Don’t worry, we will collect all the information together.
Step 1: Refer Documentation
Whenever you want to connect to any API, first find its documentation. Here we will go to Twilio API documentation
Step 2: Find Base URL
In HTTP request we need to set the end point URL.
End point URL = Base URL + Resource(Action User Wants to Perform)
Here the base URL mentioned in documentation is
https://api.twilio.com/2010-04-01
Step 3: Hit the base URL
Hit the base URL to see if you are getting response. I am using postman to hit the URL
A. Observe the URL I have put
B. Observe I am getting 200 Ok Response, which means when client is making HTTP request then server is sending response.
Step 4: Form the End Point URL
End point URL = Base URL + Resource(Action User Wants to Perform)
I need to append base URL with the action we are going to perform. In this case I want to send message to WhatsApp so I will find the end point URL I need to hit so that I can send message.
Click on Post to the Message Resource.
It gives you: HTTP Method – POST. This means the browser will send the data to the web server to be processed.
Endpoint URL: https://api.twilio.com/2010-04-01/Accounts/{AccountSid}/Messages.json
Code Snippet:
Below Code shows how we add endpoint and method in the HTTP Request
HttpRequest req = new HttpRequest(); // be sure this is configured in "Remote Site Settings" req.setEndpoint('https://api.twilio.com/2010-04-01/Accounts/'+account+'/Messages.json'); req.setMethod('POST'); // This tells the API that we are sending and receiving the data as a JSON object req.setHeader('Content-Type','application/json'); req.setHeader('Content-Type','application/x-www-form-urlencoded');
Step 5: Type of Authentication
Now we need to see which kind of Authentication is needed. These are 4 most used authentications right now:
- Basic
- Bearer
- Digest
- OAuth
Example: for integrating with Twitter we were needing Oauth 1.0. You can refer to my previous article
In this case we are going to use Basic Authentication. How I know? Answer is simple. Twilio API Documentation
Some basics about Basic Authentication
This is the most straightforward method and easiest method
With this method, the sender places a username: password into the request header. The username and password are encoded with Base64, which is an encoding technique that converts the username and password into a set of 64 characters to ensure safe transmission.
This method does not require cookies, session IDs, login pages, and other specialty solutions. Because it uses the HTTP header itself, there’s no need for handshakes or other complex response systems.
In this case:
- Twilio Account SID will be used as username
- Auth Token as the password
In the later section, I will show you where you will find them.
Code Snippet:
Below code snippet shows how we add them in the request header while sending HTTP Request.
// define basic information for later, store these in a protected custom setting String account = 'XXXX'; String token = 'XXXX' // Add basic authentication to header // Create blob of user:pass Blob headerValue = Blob.valueOf(account + ':' + token); // Base 64 Encode the blob and prepend "Basic " String authorizationHeader = 'BASIC ' + EncodingUtil.base64Encode(headerValue); // Add the basic auth string to the Request Header req.setHeader('Authorization', authorizationHeader);
Step 6: Parameters passed in request Body
We need to understand the parameters for the request body.
It says that Request Body should contain
From : Twilio Number
Body : Message
To: The number to which you are sending message
Code Snippet:
Below code snippet shows how we will form request body .
// Set the body json with the description parameter, basically a string with a key value pair construction. // This will look very different for each integration resource. // Some APIs don't use a body to take the request, // they may simply take additional resources "/resource/order/Ord#" in the URI // or parameters "resource/?orderId=133" in the URI string jsonString='From='+EncodingUtil.urlEncode('whatsapp:+14155238886', 'UTF-8')+'&Body='+EncodingUtil.urlEncode(message, 'UTF-8')+'&To='+EncodingUtil.urlEncode('whatsapp:'+mobileno+'', 'UTF-8')+''; req.setBody(jsonString);
Step 7: Deserialize the values coming in response body
Data Structure
if you do System.debug(res.getBody()); , then you will be able to see the what response body is returned.
Http http = new Http(); HTTPResponse res = http.send(req); System.debug(res.getBody());
Lets see what we got in response body. I will open the logs and click debug only.
Logs
10:31:37:379 USER_DEBUG [55]|DEBUG|{"code": 63007, "message": "Twilio could not find a Channel with the specified From address", "more_info": "https://www.twilio.com/docs/errors/63007", "status": 400}
So you are getting :
Code
Message
More_info
Status
Option 1: Parse by yourself
JSON Types
JSON has multiple styles
Object
An unordered “name/value” assembly. An object begins with “{” and ends with “}”. Behind each “name”, there is a colon. And comma is used to separate much “name/value”. For example,
var user = {"name":"Smriti","gender":"Female"}
Array
Value order set. An array begins with “[” and end with “]”. And values are separated with commas.
var userlist = [{"user":{"name":"Smriti","gender":"female"}}, {"user":{"name":"Mohapatra","Male":"Female","birthday":"1987-7-7"}}]
String
Any quantity Unicode character assembly which is enclosed with quotation marks. It uses backslash to escape.
var userlist = "{\"ID\":1,\"Name\":\"Smriti\",\"Address\":\"US\"}"
In our case JSON is returned in form of object.
Create a wrapper class
Now we need to create a data structure to hold our the JSON we deserialize for this we will create a wrapper class
public class errorResponseWrapper{ String code; String message; String moreInfo; String status; }
Deserialize JSON
deserialize(jsonString, apexType): Deserializes the specified JSON string into an Apex object of the specified type.
Now we need to pull the data from the endpoint and using JSON deserialization push it into our data structure.
erw =(errorResponseWrapper)json.deserialize(res.getBody(),errorResponseWrapper.class); system.debug('Twilio error'+erw.message);
Option 2: Parse JSON by using tool
The JSON2Apex is a very handy tool for this.
This would give you a class with member variables from the JSON String. You can just use this class as is or you can paste it into your existing class like an inner class.
// // Generated by JSON2Apex http://json2apex.herokuapp.com/ // public class JSON2Apex { public Integer code; public String message; public String more_info; public Integer status; public static JSON2Apex parse(String json) { return (JSON2Apex) System.JSON.deserialize(json, JSON2Apex.class); } }
Now that we have collected all the information needed to make request header and request body, we Can move to next section.
Section 2: Complete registration process with Twilio
Step 1: Sign up to Twilio
We need to sign up to Twilio to create account and start the integration process.
Step 2: Verify Email
It will send email for verification. Verify email to continue. This will open below screen to verify phone number.
Verify mobile/phone number to process further. After verification and confirming some information , this popup will show. Confirm this also as it is for developers for testing Whatsapp messaging.
For connecting with Whatsapp you will need:
Trial Number
Account SID
Auth Token
Note: Once you click Dashboard of Twilio Sandbox, on right hand side, you will be able to find account SID and auth Token
Step 3: Create Sandbox environment
Developer can test WhatsApp messaging using Sandbox environment.
- Activate your sandbox
2. Send message to whatsapp
3.Once you send the message, you will link your WhatsApp number to sandbox environment.
4. Below screen show, how message will be delivered to your number.
5.After confirming that message is delivered to your WhatsApp number, go to the next step.
6.Send message from your WhatsApp number to verify two way communication.
Congratulations! Now sandbox environment is successfully setup.
Step 4: Create Apex for consuming API
Integrate Twilio API to send WhatsApp message using Apex by using Account SID and Account Token generated in earlier step.
Sample code is given in Twilio API Documentation
Add URL to Remote Site Settings
Using Lightning Web Component
I used Lightning web component to fetch values from UI. You can use aura or Visualforce. I have put the complete code in the git hub repository.
Github Link for the Code
Hope you enjoyed the article. For more articles like this, please subscribe to the blog.
Together we can learn faster
You can join Facebook group
You can join Twitter
You can join Instagram
Reference
Conversational message on Whatsapp
Authentication Method Explained
JSON Deseralization in Salesforce
Hi Mam,
I was going throught the developer API where it was written the Account SID is the username and the token is the Bearer….Even in the commented section of the code I was unable to figure out what should be the username and the password. This is a bit confusing. And also if you would tell how we can replicate the same in POSTMAN. PLease kindly help.
Regards,
SIddhartha
Hi, I am getting following error while activating sandbox – “There was a problem configuring your sandbox.”.
Can you please help?