SMS from Salesforce using Twilio API

SMS from Salesforce using Twilio API when new record inserted

Twilio API

Twilio is a cloud communication company that allows, software developers to programmatically make and receive phone calls, and send and receive text messages using its web service APIs

1.Setup Twilio 

* Sign up with Twilio:

First steps are, we need to have a Twilio account set up. You can have a free trial account created and use that for demo purposes. You need to provide a few basic details along with your email ID and phone number.

* Install Twilio in your Org:

After you have successfully signed up, you will get an option to install Twilio in your salesforce org.

Once you login to your org with the username and password. You need to choose whether you want to install it only for admin or for all users. This is the same as installing any other app/package from app exchange so nothing special.

Please note Twilio creates few components in your org e.g. It installs few Apex classes, permission sets, objects etc.

Get a Phone Number from Twilio and set up your account:

Don’t worry, you need to get a subscription for that but you will get a phone number immediately from your Twilio account. That phone number will be used for messaging service.

You will also need to set up a messaging service in your account. You will need this messaging service name in salesforce while setting up your flow.

Please refer to the image below for more information. Since I already got a trial phone number, on my screen you will see that you already have a trial phone number.

Once you get a phone number, create a message service in your account. You just need to provide a service name. That service name you will use later while building a solution in salesforce org.

 Get a Phone Number from Twilio and set up your account

Take a note of your Twilio account details:

Once logged in your account, you will see your account details. Two important things to note are :

1. Account ID 

2. Token.

These two things you will need in Salesforce while establishing connection between two platforms. So please take note of these. These are like username and password.

Take a note of your Twilio account

Configure Salesforce to use Twilio account:

In Point #2, we have installed the Twilio package in salesforce and now it’s time to check a few things.

Imp things which we need to check

  • Check that the user has the permission for required Twilio permission sets before using Twilio. If not, assign below permission set to users:
Permission set for twillo
  • Check that Twilio App is assigned to the user. If not please assign that. You need it to set up and configure the app.
  • Configure the Twilio account in Salesforce org:

From the app launcher select Twilio configuration. If you have done all above steps correctly and if the admin user which you are using for this configuration has the right permissions he will see below screen. If not, then please check that you haven’t missed any configuration for the user.

Here you need to enter Account ID and authentication token as noted above and validate the credentials.

Now we have successfully set up the Twilio app in our salesforce org and ready to use the functionality provided by it.

There can be multiple use cases for Twilio SMS alerts but the one which I picked up for this article is, if a high priority case gets created then send a text alert to the contact person and notify him about the case by sending a text message on his mobile phone.

2. Remote Site Settings

Create a Remote Site Settings in Salesforce for the this URL: https://api.twilio.com

3. Create an Apex Trigger and Apex Class

  In this class, we need to replace the value of the AccountSid variable with the ACCOUNT SID value, also replace the value of the token variable with the AUTH TOKEN, and replace the value of the fromPhNumber variable with the From phone number you got from the Twilio Account.

Apex Trigger(smsTwilioTrigger):

trigger smsTwilioTrigger on Contact (after insert) {
    
    for(Contact c: trigger.new){
        smsTwilioClass.processSms(c.MobilePhone,c.Phone);
    }
}

Apex Class(smsTwilioClass):

public class smsTwilioClass {     
    errorResponseWrapper erw;    
    @future(callout=true)
    public static void processSms(String fromPhNumber,string phNumber){
        String accountSid = 'AC9ec8c74171d8df7737a3ff79a5c49661';        
        String token = 'fd9ba49279f6fe5df163f24c02e2e0ae';
                
        HttpRequest req = new HttpRequest();
        
        req.setEndpoint('https://api.twilio.com/2010-04-01/Accounts/'+accountSid+'/SMS/Messages.json');        
        req.setMethod('POST');        
        String VERSION  = '3.2.0';        
        req.setHeader('X-Twilio-Client', 'salesforce-' + VERSION);        
        req.setHeader('User-Agent', 'twilio-salesforce/' + VERSION);        
        req.setHeader('Accept', 'application/json');        
        req.setHeader('Accept-Charset', 'utf-8');
        
        req.setHeader('Authorization','Basic '+
                      EncodingUtil.base64Encode(Blob.valueOf
                                                (accountSid+':' +token)));
        req.setBody('To='+EncodingUtil.urlEncode
                    (phNumber,'UTF-8')+'&From='+EncodingUtil.urlEncode
                    (fromPhNumber,'UTF-8')+'&Body="Hi from Salesforce!!"');
        
        Http http = new Http();       
        HTTPResponse res = http.send(req);        
        System.debug(res.getBody());        
    }    
    public class errorResponseWrapper{        
        String code;        
        String message;        
        String moreInfo;        
        String status;          
    }    
}

4: Receiving the SMS:

By using the Twilio account, we can send SMS to any country. In the trial account, Twilio provides only the SMS for free. If you want to make a call using the API, you need to upgrade your account.