In this post, we’ll explore how to integrate Twilio with Salesforce using REST API to send SMS messages directly from Salesforce. Twilio is a cloud communications platform that allows you to send SMS, make voice calls, and perform various communication tasks. Salesforce’s integration with Twilio opens up powerful communication capabilities for your CRM.
Step-by-Step Guide to Integrate Twilio with Salesforce
Prerequisites:
- Twilio Account: Sign up for a Twilio account and note down your Account SID, Auth Token, and Twilio Phone Number.
- Salesforce Developer Org: Have access to a Salesforce Developer Org for testing.
- Postman (Optional): This is for testing API requests.
- Learn how to integrate Postman with Salesforce: How to Integrate Postman with Salesforce
Step 1: Setting Up Twilio
- Sign Up for Twilio:
- Go to Twilio and create a free account.
- Get a Twilio Phone Number:
- In the Twilio Console, click on Twilio Phone Number
- Navigate to your Twilio dashboard, where you’ll see your Account SID and Auth Token. These will be used for authentication in Salesforce.
Step 2: Configure Salesforce to Call Twilio API
To send SMS from Salesforce, we’ll create an Apex class that sends an HTTP request to Twilio’s API.
- Create a Remote Site Setting:
- Go to Setup > Security > Remote Site Settings.
- Click New Remote Site and enter the following details:
- Remote Site Name: Twilio
- Remote Site URL:
https://api.twilio.com
- Save the remote site setting.
Create an Apex Class to Call Twilio’s API
- Navigate to Developer Console or Setup > Apex Classes > New.
- Create a class named
TwilioSMSService
and add the following code:
public class TwilioSMSService {
private static final String TWILIO_SID = 'Your_Twilio_Account_SID'; // Your Twilio Account SID
private static final String TWILIO_AUTH_TOKEN = 'Your_Twilio_Auth_Token'; // Your Twilio Auth Token
private static final String TWILIO_PHONE_NUMBER = 'Your_Twilio_Phone_Number'; // Twilio phone number
public static void sendSMS(String toPhoneNumber, String messageBody) {
try {
String endpoint = 'https://api.twilio.com/2010-04-01/Accounts/' + TWILIO_SID + '/Messages.json';
String auth = TWILIO_SID + ':' + TWILIO_AUTH_TOKEN;
String encodedAuth = EncodingUtil.base64Encode(Blob.valueOf(auth));
HttpRequest req = new HttpRequest();
req.setEndpoint(endpoint);
req.setMethod('POST');
req.setHeader('Authorization', 'Basic ' + encodedAuth);
req.setHeader('Content-Type', 'application/x-www-form-urlencoded');
String body = 'To=' + EncodingUtil.urlEncode(toPhoneNumber, 'UTF-8') +
'&From=' + EncodingUtil.urlEncode(TWILIO_PHONE_NUMBER, 'UTF-8') +
'&Body=' + EncodingUtil.urlEncode(messageBody, 'UTF-8');
req.setBody(body);
Http http = new Http();
HttpResponse res = http.send(req);
if (res.getStatusCode() == 201) {
System.debug('SMS sent successfully');
} else {
System.debug('Failed to send SMS: ' + res.getBody());
}
} catch (Exception e) {
System.debug('Error sending SMS: ' + e.getMessage());
}
}
}
Explanation:
- The Twilio API is invoked using a POST request to send an SMS.
- The
HttpRequest
is built with headers and body parameters, including To, From, and Body. - Base64 Encoding is used for Twilio authentication.
- The response status code
201
indicates success.
Step 3: Test the Integration in Salesforce
To test the integration, you can call the TwilioSMSService
class from an anonymous Apex block or trigger it from a Salesforce record event.
- Test with Anonymous Apex:
- Open Developer Console.
- In the Execute Anonymous Window, write the following code:
TwilioSMSService.sendSMS('+1234567890', 'Hello from Salesforce!');
Replace +1234567890
with the recipient’s phone number.
Step 4: Create a Visualforce page or Lightning component for sending SMS.
SendWhatsappMessage.html
<template>
<lightning-card title="Send Message">
<lightning-input type = "text" label="Enter Message" ></lightning-input>
<lightning-button variant="brand" label ="Send Message" onclick={handleSendMessage}></lightning-button>
</lightning-card>
</template>
SendWhatsappMessage.js
import { LightningElement } from 'lwc';
import sendMessage from '@salesforce/apex/TwilioWhatsappIntegration.sendMessage';
export default class SendWhatsappMessage extends LightningElement {
handleSendMessage(){
sendMessage({msg : this.template.querySelector('lightning-input').value})
.then(res =>{
console.log('res' + res);
})
.catch(err => {
console.error(JSON.stringify(error));
})
}
}
TwilioWhatsappIntegration.apxc
/**
* @File Name : TwilioWhatsappIntegration.cls
* @Description :
* @Author :
* @Last Modified By :
* @Last Modified On : September 4, 2024
* @Modification Log :
*==============================================================================
* Ver | Date | Author | Modification
*==============================================================================
* 1.0 | September 4, 2024 | | Initial Version
**/
public class TwilioWhatsappIntegration {
@AuraEnabled
Public static void sendMessage(String msg){
String accountSid = '';
string token = '';
String fromPhNumber = '+12169301758';
String toNumber = '+4121452211';
Http http = new Http();
HttpRequest request = new HttpRequest();
HttpResponse response;
request.setEndpoint('https://api.twilio.com/2010-04-01/Accounts/' + TWILIO_SID + '/Messages.json');
request.setMethod('POST');
request.setHeader('Authorization','Basic '+ EncodingUtil.base64Encode(Blob.valueOf(accountSid+':' +token)));
request.setHeader('Content-Type', 'application/x-www-form-urlencoded');
String VERSION = '3.2.0';
request.setBody('To='+EncodingUtil.urlEncode(toNumber,'UTF-8')+'&From='+EncodingUtil.urlEncode(fromPhNumber,'UTF-8')+'&Body='+msg);
System.debug('request----->' + request);
response = http.send(request);
System.debug('response----->' + response);
try{
response = http.send(request);
if(response.getStatusCode()==201){
System.Debug('Message sending successful');
}
else{
System.Debug('Message '+response.getStatusCode());
System.Debug('Message sending Unsuccessful');
//return res;
}
} catch (Exception e){
throw new AuraHandledException(e.getMessage());
}
}
}
Conclusion
Integrating Twilio with Salesforce using REST API opens up new communication channels for your business. With this simple integration, you can send SMS notifications, alerts, and marketing messages directly from Salesforce to your customers. This is just the start; you can extend the functionality to fit your specific business needs.
If you have any questions or need further assistance with this integration, feel free to drop a comment!