Leverage Cloud-Computing, Saas, and Better Business Processes to Drive Change in Your Industry

Clint Lee

Subscribe to Clint Lee: eMailAlertsEmail Alerts
Get Clint Lee: homepageHomepage mobileMobile rssRSS facebookFacebook twitterTwitter linkedinLinkedIn

Related Topics: Cloud Computing, Salesforce.com Journal

Cloud Computing: Blog Post

Salesforce + Twilio + Receiving Incoming Texts

A quick how-to

In order to process these incoming SMS messages you first need an Apex Controller and Visualforce page.  The request will get sent to this page and the parameters will be stored.  Using the stored parameters we'll create a closed task and associate it with the appropriate Contact.   The code for the Controller and VF page are below.

Apex Class
This controller will grab the three parameters From, To, and Body when the Twilio
HTTP request is made. Once we have the From number (which is the sender's number)
we can use it to query Salesforce for a Contact matching that (presumably) mobile
number. When we've found a matching Contact we create a closed Task to record the
message of the incoming text, and it will now show up under the Activity History
related list for this Contact
public with sharing class TwilioRequestControllerContacts {

// Set instance variables to capture the To, From, and Body Parameters that Twilio sends in the HTTP request
public String fromNumber = ApexPages.currentPage().getParameters().get('From');
public String toNumber = ApexPages.currentPage().getParameters().get('To');
public String body = ApexPages.currentPage().getParameters().get('Body');
public PageReference response = new PageReference('http://your_site_url/TwilioResponse');

// This is the initial method that gets called when the TwilioResponse page loads
public PageReference init()
// Helpful with debugging
System.debug('FROM: ' + fromNumber);
System.debug('TO: ' + toNumber);
System.debug('BODY: ' + body);

// If we capture all of the parameters successfully, call the saveIncomingText() method
if(fromNumber != null && toNumber != null && body != null)
response = saveIncomingText();
return response;

return null;

private PageReference saveIncomingText()
// Call the method to clean the incoming phone number
String cleanFromNumber = formatPhone(fromNumber);

// Query the student whose phone number matches the incoming phone number
List <Contact> contactList = [SELECT Id, FirstName, LastName
FROM Contact
WHERE MobilePhone =: cleanFromNumber limit 1];

// Move forward only if we find at least one match.
if(contactList.size() > 0)
for (Contact contact : contactList)
System.debug(contact.FirstName + ' ' + contact.LastName);

// Create a new Task to store the record of the incoming text, then attach it to the appropriate Contact
Task text = new Task();
text.Subject = body;
text.WhoId = contact.Id;
text.Status = 'Completed';
text.Type = 'Incoming Text';

// Insert the Incoming Text object and return the response page.
insert text;
return response;
catch(DmlException e)
System.debug('INSERT TASK FAILED: ' + e);

return response;

// Twilio sends the phone number as +15555551234. We have to reformat the string to (555) 555-1234
private String formatPhone(String fromNumber)
String areaCode = fromNumber.substring(2,5);
String prefix = fromNumber.substring(5,8);
String last4 = fromNumber.substring(8);
String formattedPhone = '(' + areaCode +')' + ' ' + prefix + '-' + last4;
System.debug('FORMATTED PHONE IS: ' + formattedPhone);
return formattedPhone;

<!--Visualforce Page-->
<!--This is a simple page that calls the init method when it loads-->
<apex:page controller="TwilioRequestControllerContacts" action="{!init}" showHeader="false" sidebar="false">
<apex:pageBlock title="Twilio Request Listener"></apex:pageBlock>

The next step is to give your Site access to this page and controller. If you've not worked with Salesforce Sites it is pretty simple to set one up.  Utilizing Sites is how we can expose our Visualforce page to the outside world, thus letting the Twilio HTTP request hit our page.  You should also make sure that your Public Access Settings on the Site give at least read access to the Contact object.

The last step is to tell Twilio where to send the request.  Log in to your Twilio account and click 'My Account'.  Under the heading Developer Tools you'll see a field titled SMS URL.  Paste the full URL path to your Visualforce page into that field.

As always, any feedback or questions are welcome.  If you've implemented a different solution to handle this issue I'd love to hear about it, too.

More Stories By Clint Lee

Clint is a Principal and Founder of The Flywheel Group, a premier provider of innovative solutions to the franchise industry. The FranchiseFlywheel™ application was developed out of the industry's need for a cutting-edge and affordable franchise management tool for franchisors. Spending several years in the franchise industry directing daily activities related to franchise and business development processes, marketing, lead-generation, and contract administration, and an understanding of the needs of peers and colleagues, led to the development of the application. The Flywheel Group is focused on improving best practices and driving change in the franchise industry by introducing industry-leading solutions and working with its clients to re-engineer business processes that will ultimately enhance revenue and improve bottom line efficiency. Clint actively writes and shares his thoughts on the Flywheel Blog.