Last active
June 29, 2023 12:10
-
-
Save dhaniksahni/47e1688ea0357431e96cc139755f4fc5 to your computer and use it in GitHub Desktop.
Twilio WhatsApp Message Integration in Salesforce Apex
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class WhatsAppMessageService { | |
@AuraEnabled | |
public static void sendMessage(string mobileno,string message) | |
{ | |
errorResponseWrapper erw; | |
final String fromNumber = '+14155238886'; | |
String account = 'ACa2e448aaa0e51ed81a56ff55b6635cca'; | |
String token = '<your token>'; | |
HttpRequest req = new HttpRequest(); | |
req.setEndpoint('https://api.twilio.com/2010-04-01/Accounts/'+account+'/Messages.json'); | |
req.setMethod('POST'); | |
req.setHeader('Content-Type','application/json'); | |
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); | |
if(mobileno != null) | |
{ | |
string jsonString='From='+EncodingUtil.urlEncode('whatsapp:+14155238886', 'UTF-8')+'&Body='+EncodingUtil.urlEncode(message, 'UTF-8')+'&To='+EncodingUtil.urlEncode('whatsapp:'+mobileno+'', 'UTF-8')+''; | |
req.setBody(jsonString); | |
try{ | |
Http http = new Http(); | |
HTTPResponse res = http.send(req); | |
System.debug(res.getBody()); | |
if(res.getStatusCode()==201) | |
system.debug('Twilio Success'+mobileno); | |
else{ | |
system.debug('Twilio failed'+mobileno); | |
erw =(errorResponseWrapper)json.deserialize(res.getBody(),errorResponseWrapper.class); | |
system.debug('Twilio error'+erw.message); | |
} | |
} | |
catch(Exception e){ | |
system.debug('Error :'+e); | |
} | |
} | |
} | |
public class errorResponseWrapper{ | |
String code; | |
String message; | |
String moreInfo; | |
String status; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment