Send SMS using Twilio Salesforce Library




SMS is still one of the best way to connect with customer .
This blog will be explaining how to use the twilio-salesforce helper library to send SMS. As usual we will implement a small application for it. We will add “Send SMS” button on Account. After clicking “Send SMS” button Salesforce user can type message and send to phone number of that Account.

Steps:
1) download the twilio-salesforce library from GitHub.
 
2) If you don’t have Force.com migration tool install from here.

3) Extract downloaded twilio-salesforce zip file and edit install/build.properties
  to insert your Salesforce username and password. append security token to
    your password.

   Open command line to the install folder, then deploy using Ant:    
    Command : $ ant deployTwilio

4) Sign up for twilio account by trial pack you can send SMS to verified phone
     numbers only.
     (If you need you can get paid service so you can send SMS without
     verifying phone numbers).

5) Get first number :
     Log in to twilio Click on Phone Numbers and get first number(SMS will be
     send from this Number ).
     In verified Caller Ids sub-tab you can verify phone numbers(You will need
     verified numbers to send SMS if you are using trial pack).

6) Create Custom Object SMS :
     Object Name SMS (API Name : SMS__c)
     Create fields as below, this object will be used to save SMS log.


 

7) Create Visualforce Page : Send_SMS
<apex:page standardController="Account" Extensions="Send_SMS_Controller"
  showHeader="false" sidebar="false">
     <apex:form >
           <apex:pageBlock id="msgs"> 
                <apex:pageMessages ></apex:pageMessages>
                 Body : <br/>
                <apex:inputText id="smsBody" value="{!smsBody}"   
      style="width:400px; height:50px;"/>
                       <br/>
                <apex:commandButton action="{!send}" value="Send" 
     id="sendButton" reRender="msgs" rendered="{!hasNumber}"/>
                <apex:commandButton action="{!getReturn}" value="Return to Account"
      id="returnButton" reRender="msgs" rendered="{!NOT(hasNumber)}"/>
             </apex:pageBlock>
       </apex:form>
  </apex:page>


8) Create Apex Class : Send_SMS_Controller
public class Send_SMS_Controller {
    public String smsBody {get; set;}
    public boolean hasNumber {get; set;}
    private final String  fromNumber = '+19545732804';// get it from twilio
      //after login click Phone Numbers tab in left sidebar

    private string dialCode = '+91'; // Add your dial Code of your country.
    public Send_SMS_Controller(ApexPages.StandardController controller) {
       hasNumber = true;
    }
    public PageReference Send()
    {
        String account = ‘your twilio Account SID’; // Account SID on home tab
        String token   =   'twilio Account AUTH Token';//AUTH Token on home tab
        TwilioRestClient client = new TwilioRestClient(account, token);
        
        Id accountId = ApexPages.currentPage().getParameters().get('id');
        String baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
        Account a = [select Phone from Account where Id = :accountId];
 
        if(a.Phone != null)
        {
            String phoneNumber = a.Phone;
            if(!phoneNumber.Contains(dialCode))
            phoneNumber = dialCode+phoneNumber;// If by default dialCode is not 
             //on Phone number we will ad it.
            System.debug('phoneNumber'+phoneNumber);
             Map<String,String> params = new Map<String,String> {
            'To'   => phoneNumber,
            'From' => fromNumber,
            'Body' => smsBody
             };
             TwilioSMS sms = client.getAccount().getSMSMessages().create(params);
             SMS__c sentSMS = new SMS__c(From__c = fromNumber,To__c = phoneNumber,
        Account__c = accountId, Body__c = smsBody);
             insert sentSMS;
             
             
        }
        else
        {
             ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'This Account have No Phone Number Click Return to Account'));
             System.debug('Message is set');
             hasNumber = false;
             return null;
        }
        
        pagereference redirect = new PageReference(baseUrl+'/'+accountId);
        return redirect;
    }
     public PageReference getReturn()
     {
        return new PageReference(URL.getSalesforceBaseUrl().toExternalForm()+'/'+ApexPages.currentPage().getParameters().get('id'));
     }

}


9) Create “Send SMS” button of type Detail Page Button on account opening
        in existing window add Send SMS visualfoce page to it.

10) Add Send SMS button and related list of SMS on Account page layout

Quick demo :


Comments

  1. I've followed the same stepa and it showing the status code 201 in debug log. But I'm not receiving any message on mobile. Receiver number is verified in twilio.

    ReplyDelete
  2. Hey anyway to do this for a lead when the lead gets updated to a working lead? Ive got it working perfectly for an account but cant seem to figure it out for that. Let me know please!

    ReplyDelete
  3. These ways are very simple and very much useful, as a beginner level these helped me a lot thanks fore sharing these kinds of useful and knowledgeable information.
    Digital Mobile Marketing
    SMS API
    SMS Marketing

    ReplyDelete
  4. You have provided an nice article, Thank you very much for this one. And i hope this will be useful for many people.. and i am waiting for your next post keep on updating these kinds of knowledgeable things...
    iOS App Development Company
    Android App Development Company

    ReplyDelete
  5. You have provided an nice article, Thank you very much for this one. And i hope this will be useful for many people.. and i am waiting for your next post keep on updating these kinds of knowledgeable things...
    Sms marketing
    Text message marketing
    Fitness SMS

    ReplyDelete
  6. Yeah!! Send SMS Attachment will help you in optimizing your campaign performance. You can send files via SMS and improve your business prospects simply by understanding the behavior of your customers. This way, you will put in efforts in working towards fulfilling the requirements of your consumers.

    ReplyDelete
  7. Yeah!! Send SMS attachments within Bulk messages shall provide business houses with a new way of interacting with the target audience and sharing their business word. As the name indicates, SMS attachments are the files, images or any informative detail that can be sent in the SMS along with the regular text. These attachments majorly include PDF, word files, excels, pictures (.jpg, .png), audios, directive links, gifs (.gif), and many more.

    ReplyDelete
  8. Really Good tips and advises you have just shared. Thank you so much for taking the time to share such a piece of nice information. Looking forward for more views and ideas, Keep up the good work! Visit here for Product Engineering Services | Product Engineering Solutions

    ReplyDelete

Post a Comment

Popular posts from this blog

Uploading multiple files as attachments using chaining of actionfunction in single click.

New Way of Pagination

Component Events in Lightning