Last active
February 2, 2019 23:27
-
-
Save SalesforceBobLightning/e42c02fa91e29055441ba1fa61068ae4 to your computer and use it in GitHub Desktop.
How to return Twilio TwiML from a Salesforce Apex REST API Controller
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
@RestResource(urlMapping='/twilio/incoming-call/') | |
global without sharing class TwilioIncomingCallRESTController { | |
@HttpPost | |
global static void handlePost() | |
{ | |
String phoneNumber = getParam('From'); | |
String response = TwilioIncomingCallService.getResponse(phoneNumber); | |
RestContext.Response.addHeader('Content-Type','application/xml'); | |
RestContext.Response.statusCode = 200; | |
RestContext.Response.responseBody = Blob.valueOf(response); | |
} | |
private static String getParam(String key) { | |
return RestContext.request.params.get(key); | |
} | |
} |
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 without sharing class TwilioIncomingCallService { | |
public static String getResponse(String phoneNumber) { | |
TwilioTwiML.Response twiML = new TwilioTwiML.Response(); | |
Contact caller = getContact(phoneNumber); | |
if (caller == null) { | |
twiML.append(getUnknownCallerTwiML()); | |
} else { | |
twiML.append(getKnownCallerTwiML(caller)); | |
} | |
return twiML.toXML(); | |
} | |
private static TwilioTwiML.Verb getUnknownCallerTwiML() { | |
return new TwilioTwiML.Say('Welcome to ACME Inc, to help us route your call, please select from the following options'); | |
} | |
private static TwilioTwiML.Verb getKnownCallerTwiML(Contact caller) { | |
return new TwilioTwiML.Say('Hello ' + caller.FirstName + ', welcome back to ACME Inc, please press 1 to speak with your account manager ' + contact.Owner.Firstname + ' or press 2 to hear other options'); | |
} | |
private static Contact getContact(String phoneNumber) { | |
List<Contact> contacts = [SELECT Id, Firstname, Owner.Firstname | |
FROM Contact | |
WHERE Phone = :phoneNumber | |
OR OtherPhone = :phoneNumber | |
OR HomePhone = :phoneNumber | |
OR MobilePhone = :phoneNumber | |
ORDER BY CreatedDate DESC | |
LIMIT 1]; | |
if (contacts.size() == 0) { | |
return null; | |
} | |
return contacts[0]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment