8.6 C
New York
Friday, October 30, 2020
Home Apex How To Send SMS Using Lightning Component from Twilio API

How To Send SMS Using Lightning Component from Twilio API

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.

Twilio Project Dashboard, Twilio Account Sid, Twilio Auth Token, Twilo Trial Balance, Twilio Trial Number

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.

Remote Site Settings, New Remote Site setting,Web Address.

Click New Remote Site Button from the table view.

New Remote site setting, Twilio API

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 class="slds-col" style="width: 2vw;">
                    <lightning:input value="{!v.CountryCode }" label="Country Code" />
                <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." />
            <button class="slds-button slds-button_brand" onclick="{! c.SendingSMScontroller }">Send Message</button>
        <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>

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.setCallback(this, function(data){
            if(data.getState() == 'SUCCESS'){
                var toastEvent = $A.get("e.force:showToast");
                    mode: 'pester',
                    "title": "SMS Sent successfully!",
                    "message": data.getReturnValue(),
                    "type": "success"
            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");
                    mode: 'pester',
                    "title": "Error while Sending SMS.",
                    "message": "There are while Sending SMS.",
                    "type": "error "

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 
    //@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.
    public static String SendSMS(String MobileNumber,String CountryCode,String MessageBody){
        HttpRequest RestRequest = new HttpRequest();
        //Set's the Account SID in the Twilio Message JSON
        //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)));
        Http http = new Http();
        HTTPResponse RestResponse = http.send(RestRequest);
            return 'We Have Sent Message Successfully To '+CountryCode + '-' + MobileNumber;
            TwilioErrorResponseWrapper ErrorWrapper =(TwilioErrorResponseWrapper)json.deserialize(RestResponse.getBody(),TwilioErrorResponseWrapper.class);
            return ErrorWrapper.Errormessage+', For This Number'+CountryCode+ '-' + MobileNumber;


Following video shows how to send SMS from any record details page. you can use it anywhere in the Salesforce Tabs,Components.
Screenshot of Twilio Message

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

Apex Aura Component code deploy using workbench Custom Tab getDescribe getName getSObjectType Javascript Lightning package development Saleforce crm Salesforce SalesforceCody Salesforce Cody SalesforceID Salesforce Interview Salesforce Interview Questions Salesforce Record ID Salesforce Schema SObject Twilio API Twilio SMS Services Visualforce workbench



Please enter your comment!
Please enter your name here

Most Popular

Salesforce Interview Question Answers | Part 2

Salesforce Interview Question Answers Question 1. Mention How Many Relationships Are Included In Sfdc And What Are They?

Salesforce Interview Question Answers | Part 1

Salesforce Interview Question Answers | Part 1 Are you preparing for your'e Salesforce Developer Interview? Your'e at right place....

Salesforce Object Key Prefix List

Salesforce Object Key Prefix List, What are the Key Prefix in Salesforce Standard Object NameObject Key Prefixes001Account002Note003Contact005User006Opporunity007Activity 500Case701Campaigns00BListView...

How to Get Object Type from ID

Find Object Type from Record ID RecordID would be your Record Id of any type of Salesforce Object. Reference...

Recent Comments