This Content Is Only For Subscribers
Twilio API
Twilio brings a powerful API for phone services enabling companies to make and receive phone calls, and send and receive text messages. Twilio allows programmers to easily integrate various communication methods and to solve these communication problems quickly and reliably. that allows software developers to programmatically make and receive phone calls, and send and receive text messages using its web service APIs.
Salesforce Twilio SMS Integration Source Code
Within this article we are going to set up a twilio account and register for a “Twilio FREE Trial Account”.
Let’s DO This!..
Step1: Get The Twilio API Credentials
First, create a trial account in Twilio.com here and then get the API Credentials from the console for initiating the API calls.
Before sending SMS, you need to get a number to send the messages from that number to end users. From here Twilio Phone Numbers. (Note: While using Trial version you can only send SMS to Verified Numbers.)
How To Verify Numbers? Click Here to Verify Numbers and Add New Number and verify with OTP or By Using Call. Once you Verify numbers To See List of Verified Number Click Here.
That’s it We are done with the Twilio Setup.
Now Go to you Salesforce Org, and do the steps below.
Step 2: Create Remote Site Settings
What is Remote Site Setting? “list of Web addresses that your organization can invoke from salesforce.com”
Create a New Remote Site Settings in Org for the below URL. Name: https://api.twilio.com
From Setup, Search for the Remote Site Settings in the Quick Find Box.
Click New Remote Site Button from the table view.
Step 3 : New Component: SMSTwilioComponent.cmp
<aura:component controller='SMSTwilioApexController' implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
<aura:attribute name="MobileNumber" type="String" default="9624558568"/>
<aura:attribute name="CountryCode" type="String" default="+91" />
<aura:attribute name="MessageBody" type="String" default="Hello From Salesforce Cody"/>
<div class="slds-form-element">
<div class="slds-form-element__control">
<div class="slds-grid slds-gutters">
<div class="slds-col" style="width: 5vw;">
<lightning:input value="{!v.MobileNumber }" label="Mobile Number" />
</div>
<div class="slds-col" style="width: 2vw;">
<lightning:input value="{!v.CountryCode }" label="Country Code" />
</div>
<div class="slds-col" style="width: 14vw;">
<lightning:textarea name="input1" required="true" value="" placeholder="compose your Message" label="Message Body" maxlength="140" messageWhenTooLong="A maximum of 160 characters are allowed in a Message." messageWhenValueMissing="An empty Message can not be Sent." />
</div>
</div>
<center>
<button class="slds-button slds-button_brand" onclick="{! c.SendingSMScontroller }">Send Message</button>
</center>
</div>
<label class="slds-form-element__label" for="form-element-help-01">For More Blogs visit @<a href="https://salesforcecody.com/">salesforcecody.com</a></label><br/>
<label class="slds-form-element__label" for="form-element-help-02">Portfolio @ <a href="http://umeshbeti.com/">Umeshbeti.com</a></label>
</div>
</aura:component>
Step 4: New Component: SMSTwilioComponentController.js
({
SendingSMScontroller : function(component, event, helper) {
helper.SendSMShelperMethod(component, event);
}
})
Step 5 : SMSTwilioComponentHelper.js
({
SendSMShelperMethod : function(component, event) {
var action = component.get("c.SendSMS");
action.setParams({'MobileNumber':component.get("v.MobileNumber"),
'CountryCode':component.get("v.CountryCode"),
'MessageBody':component.get("v.MessageBody")
});
action.setCallback(this, function(data){
if(data.getState() == 'SUCCESS'){
var toastEvent = $A.get("e.force:showToast");
toastEvent.setParams({
mode: 'pester',
"title": "SMS Sent successfully!",
"message": data.getReturnValue(),
"type": "success"
});
toastEvent.fire();
}
else if(data.getState() == 'ERROR'){
var errors = data.getError();
if (errors) {
if (errors[0] && errors[0].message) {
console.log("Error message: " + errors[0].message);
}
} else {
console.log("Unknown error");
}
var toastEvent = $A.get("e.force:showToast");
toastEvent.setParams({
mode: 'pester',
"title": "Error while Sending SMS.",
"message": "There are while Sending SMS.",
"type": "error "
});
toastEvent.fire();
}
});
$A.enqueueAction(action);
}
})
Step 6: New Apex Class: SMSTwilioApexController.apxc
public class SMSTwilioApexController {
/**
* Author: Umesh Beti
* Blog : https://salesforcecody.com/
* Portfolio: http://umeshbeti.com/
* Date: 20/04/2020
*/
//Twilio API service is free, on the singup you will get $15, from this you can purchase number freely to develope your own
SMS product.
//@Description: This Credential could be placed in you are custom Settings, and you can pull from there to secure this
credentials.
//@Description: Twilio AccountSID, copy from twilio console dashboard from your project.
static String AccountSID = 'ACXXXXXXXXXXXXXXXXXXXXXXXf57';
//@Description: AuthToken: Get this auto token from twilio console dashboard from your project, default it will be hidden
need to click to copy.
static string AuthToken = 'c03XXXXXXXXXXXXXXXXXXXXXXXXX1e';
//@Description: The Twilio number: you can get this number from Phone number section or at the time account creation it
would ask you to get trial number.
static String fromTwilioNumber = '1XXXXXXXXX6';
/* @Description: To Catch the Twilio API errors. */
public class TwilioErrorResponseWrapper{
String Errorcode;
String Errormessage;
String moreInfo;
String statusCode;
}
/*Wrapper Class End */
/**
* @description: This method is used to send the message to the End User,
* If it's Twilio Trial Account only Verified Numbers you can send, If Non-trial You can send to anyone.
*/
@AuraEnabled
public static String SendSMS(String MobileNumber,String CountryCode,String MessageBody){
HttpRequest RestRequest = new HttpRequest();
//Set's the Account SID in the Twilio Message JSON
RestRequest.setEndpoint('https://api.twilio.com/2010-04-01/Accounts/'+AccountSID+'/SMS/Messages.json');
RestRequest.setMethod('POST');
//Version's of the Salesforce-Twilio
String TwilioVersionControll = '3.2.0';
RestRequest.setHeader('X-Twilio-Client', 'salesforce-' + TwilioVersionControll);
RestRequest.setHeader('User-Agent', 'twilio-salesforce/' + TwilioVersionControll);
RestRequest.setHeader('Accept', 'application/json');
RestRequest.setHeader('Accept-Charset', 'utf-8');
//Set Authorization to call the Twilio API with AccountSID and AUTH Token
RestRequest.setHeader('Authorization','Basic '+EncodingUtil.base64Encode(Blob.valueOf(AccountSID+':' +AuthToken)));
RestRequest.setBody('To='+EncodingUtil.urlEncode(CountryCode+MobileNumber,'UTF-8')+'&From='+EncodingUtil.urlEncode(fromTwilioNumber,'UTF-8')+'&Body='+MessageBody);
Http http = new Http();
HTTPResponse RestResponse = http.send(RestRequest);
if(RestResponse.getStatusCode()==201){
return 'We Have Sent Message Successfully To '+CountryCode + '-' + MobileNumber;
}else{
TwilioErrorResponseWrapper ErrorWrapper =(TwilioErrorResponseWrapper)json.deserialize(RestResponse.getBody(),TwilioErrorResponseWrapper.class);
return ErrorWrapper.Errormessage+', For This Number'+CountryCode+ '-' + MobileNumber;
}
}
}
Output:
Salesforce Twilio SMS Integration Source Code
In the Next Blog we will learn how to Call from Salesforce using Salesforce.
Subscribe Notification for new post updates. & Just Don’t forget to bookmark this site for your future reference.
if you have any suggestions or issue with it, you can share your thoughts in comment box please.
Happy Learning ! Stay Tuned ! #stayhomesafe
Affordable Ways to Boost Your Resume Affordable Ways to Demonstrate Your Salesforce Knowledge Affordable Ways to Enhance Your Career Affordable Ways to Get Certified Affordable Ways to Validate Your Salesforce Skills Apex Buy Your Certification Vouchers Today Discounted Certification Exam Vouchers Discounted Exam Vouchers Discounted Exam Vouchers for Salesforce Certifications Discounted Salesforce Certification Exams Discounted Vouchers for Salesforce Certifications Get Certified and Boost Your Career Get Certified and Boost Your Earnings Get Certified and Get Ahead Get Certified and Stand Out from the Crowd Get Certified at a Discount Get Certified at a Discounted Price Invest in Your Career with Certification Invest in Your Future with Salesforce Certification Maximize Your Salesforce Career Potential Saleforce crm Salesforce Salesforce Certification salesforce certification coupon codes Salesforce Certification Preparation salesforce certification vouchers SalesforceCody Salesforce Cody Salesforce Exam Salesforce Interview Salesforce Interview Questions Salesforce Trigger Salesforce Trigger Advance Salesforce Trigger Basics Salesforce Trigger Example Salesforce Triggers Tasks Salesforce Trigger Tasks Salesforce Updates Save Money and Get Certified Save Money on Certification Exams Save Money on Salesforce Certification Exams Save Money on Your Exams Trigger Trigger Tasks Apex