0

I'm using Twilio to send SMS through salesforce.

I'm able to send the sms by calling http callout to Twilio API.

but, Now I've send bulk sms, when I inserting bulk record in salesforce.

I'm calling http callout in apex class & apex called from trigger. Currently I'm doing http.send(req) in for loop. but I think it will not work when I insert bulk record in salesforce due to governor limit.

I've refered this post. but, in this post also jeff calling http callout in for loop so this will work for bulk operation?

Is my code is correct? and If not what is workaround to call bulk http callout.

Trigger

trigger UpdateContacts on Package__c(after insert) {

if (Trigger.isAfter) 
{
    list<ID> contactID = new list<ID>();
    list<string> phone = new list<string>();
    for (Package__c a : Trigger.new)
    {
       contactID.add(a.Contact__c);
    }
    for(Contact c : [Select ID, Customer_ID__c,Phone  from Contact Where ID IN :contactID])
    { 
      phone.add(c.Phone);
    }  

    SendSMS.send(phone);
}
}

Apex class

public class SendSMS
{
@future (callout=true)
public static void send(list<string> Phone )
{
    errorResponseWrapper erw;
    String smsBody='SMS body. Please don\'t reply.';

    final String  fromNumber = 'MG056832f0a17f71903b32'; 
    String account = 'AC226031e6233a3a';  
    String token   = 'token';

    HttpRequest req = new HttpRequest();
    req.setEndpoint('https://api.twilio.com/2010-04-01/Accounts/'+account+'/Messages');
    req.setMethod('POST'); 
    req.setHeader('Content-Type', 'application/x-www-form-urlencoded');
    Blob headerValue = Blob.valueOf(account + ':' + token);
    String authorizationHeader = 'BASIC ' +
    EncodingUtil.base64Encode(headerValue);
    req.setHeader('Authorization', authorizationHeader);

    for( string PhoneNo : Phone )
    {  
       if(PhoneNo != null)
       {
            req.setBody('To='+EncodingUtil.urlEncode(PhoneNo,'UTF-8')+'&From='+fromNumber+'&Body='+smsBody);
            try{
                Http http = new Http();
                HTTPResponse res = http.send(req);
                System.debug(res.getBody());
                if(res.getStatusCode()==201)
                  system.debug('@@@Twilio Success'+PhoneNo);
                else{
                    system.debug('@@@Twilio failed'+PhoneNo);
                     erw =(errorResponseWrapper)json.deserialize(res.getBody(),errorResponseWrapper.class);
                     system.debug('@@@Twilio error'+erw.message);
                    }
            }
            catch(Exception e){
                system.debug('@@@@'+e);
            } 
        }
    }
}
public class errorResponseWrapper{
    String code;
    String message;
    String moreInfo;
    String status;    
}
}

1 Answer 1

0

As Twilio API doesn't support bulk message so we need to make request inside for loop. But you can try few thing. eg: In single transaction we can make 100 request so you can add these checks

for(Contact c : [Select ID, Customer_ID__c,Phone  from Contact Where ID IN :contactID])
    { 
      phone.add(c.Phone);
      if(phone.size() == 100) {
         SendSMS.send(phone);
          phone = new list<string>();
      }
    }  
if(phone.size() > 0)
    SendSMS.send(phone);

So whenever the list size reach 100 you call the method and clear the list. This will save you from getting exception.

6
  • your logic look good, but we are calling SendSMs(phone) from same trigger. so it is suppose to single transaction correct?. no? and salesforce allow 100 request in single transaction. So this will work here?
    – Amol
    Jan 12, 2018 at 6:52
  • @Amol as you are making request from future. So that will be separate transaction. So it work. Jan 12, 2018 at 6:56
  • I've a small concern, their is limit of future annotation allowed per Apex invocation is 50. so this will affect our functionality to throw exception for bulk operation.? I'm trying to test this by writing test class for bulk operation.
    – Amol
    Jan 15, 2018 at 6:05
  • @amol This can handle 5000 records at a time. If you need to process more records at a time. Then write a batch and schedule it. That it will run hourly/daily and based on some condition it will fetch record and send message. Jan 15, 2018 at 7:26
  • means I can easily insert upto 5000 record through data loader. no need to worry about this functionality, it will work correct?
    – Amol
    Jan 15, 2018 at 7:35

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .