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;
}
}