Upload
phamkiet
View
238
Download
3
Embed Size (px)
Citation preview
twilio-salesforce DocumentationRelease 1.0
Twilio Inc.
February 02, 2016
Contents
1 Installation 3
2 Getting Started 5
3 User Guide 7
4 Support and Development 27
i
ii
twilio-salesforce Documentation, Release 1.0
Get ready to unleash the power of the Twilio cloud communications platform in Salesforce and Force.com! Soonyou’ll be building powerful voice and text messaging apps in Apex and Visualforce.
With this toolkit you’ll be able to:
• Make requests to Twilio’s REST API
• Control phone calls and respond to text messages in real time with TwiML
• Embed Twilio Client in-browser calling in your Salesforce and Force.com apps
Contents 1
twilio-salesforce Documentation, Release 1.0
2 Contents
CHAPTER 1
Installation
We’ve made it easy to get started. Just grab the code from GitHub and deploy it to your Salesforce org with theincluded Ant script.
1. Checkout or download the twilio-salesforce library from GitHub.
$ git clone [email protected]:twilio/twilio-salesforce.git
2. Install the Force.com Migration Tool plugin for Ant, if you don’t already have it.
3. Edit install/build.properties to insert your Salesforce username and password. Since you will beusing the API to access Salesforce, remember to append your Security Token to your password.
4. Open your command line to the install folder, then deploy using Ant:
$ ant deployTwilio
Now all the library code is in your org and you’re ready to start coding!
3
twilio-salesforce Documentation, Release 1.0
4 Chapter 1. Installation
CHAPTER 2
Getting Started
The quickstart will get you up and running in a few quick minutes.
2.1 Quickstart
Getting started with the Twilio API couldn’t be easier. Create a Twilio REST client to get started. For example, thefollowing code makes a call using the Twilio REST API.
2.1.1 Make a Call
This sample calls the to phone number and plays music. The from number must be a verified number on your Twilioaccount.
// To find these visit https://www.twilio.com/user/accountString account = 'ACXXXXXXXXXXXXXXXXX';String token = 'YYYYYYYYYYYYYYYYYY';
TwilioRestClient client = new TwilioRestClient(account, token);
Map<String,String> params = new Map<String,String> {'To' => '9991231234','From' => '9991231234','Url' => 'http://twimlets.com/holdmusic?Bucket=com.twilio.music.ambient'
};TwilioCall call = client.getAccount().getCalls().create(params);
2.1.2 Send an SMS
This sample texts Hello there! to the to phone number. The from number must be a verified number on your Twilioaccount.
String account = 'ACXXXXXXXXXXXXXXXXX';String token = 'YYYYYYYYYYYYYYYYYY';TwilioRestClient client = new TwilioRestClient(account, token);
Map<String,String> params = new Map<String,String> {'To' => '+12316851234','From' => '+15555555555','Body' => 'Hello there!'
5
twilio-salesforce Documentation, Release 1.0
};TwilioSMS sms = client.getAccount().getSMSMessages().create(params);
2.1.3 Generate TwiML
To control phone calls, your application needs to output TwiML. Use TwilioTwiML.Response to easily create aTwiML document.
TwilioTwiML.Response r = new TwilioTwiML.Response();TwilioTwiML.Play p = new TwilioTwiML.Play('https://api.twilio.com/cowbell.mp3');p.setLoop(5);r.append(p);System.debug(r.toXML());
<Response><Play loop="5">https://api.twilio.com/cowbell.mp3</Play><Response>
2.1.4 Next Steps
The full power of the Twilio API is at your fingertips. The User Guide explains all the awesome features available touse.
This guide assumes you understand the core concepts of Twilio. If you’ve never used Twilio before, don’t fret! Justread about how Twilio works and then jump in.
6 Chapter 2. Getting Started
CHAPTER 3
User Guide
Functionality is split over three different sub-packages within twilio-salesforce. Below are in-depth guides to specificportions of the library.
3.1 REST API
Query the Twilio REST API to create phone calls, send SMS messages and so much more
3.1.1 Accessing REST Resources
The Twilio REST API allows you to query information about your account, phone numbers, calls, text messages,and recordings. You can also do some fancy things like initiate outbound calls and send text messages. For moreinformation, see the Twilio REST Web Service Interface documentation.
To access Twilio REST resources, you’ll first need to instantiate a TwilioRestClient.
Authentication
TwilioRestClient needs your Twilio credentials to access the Twilio API. While these can be passed in directlyto the constructor, we suggest storing your credentials inside the TwilioConfig custom setting. Why? You’ll never haveto worry about committing your credentials and accidentally posting them somewhere public.
The TwilioAPI helper class looks up your Twilio AccountSid and AuthToken from your current organization, inthe TwilioConfig custom setting. You can configure TwilioConfig by going to Setup | Develop | Custom Settings, andyour AccountSid and AuthToken can be found on the Twilio account dashboard.
Once you’ve set up TwilioConfig, you can easily get a TwilioRestClient from TwilioAPI.
TwilioRestClient client = TwilioAPI.getDefaultClient();
Alternatively, if you’d rather not use TwilioConfig or you want to use a different set of credentials, pass your accountcredentials directly to the the constructor.
String ACCOUNT_SID = 'AXXXXXXXXXXXXXXXXX';String AUTH_TOKEN = 'YYYYYYYYYYYYYYYYYY';TwilioRestClient client = new TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN);
7
twilio-salesforce Documentation, Release 1.0
Get an Individual Resource
Most resources in the Twilio API can be accessed from TwilioAccount, available fromTwilioRestClient.getAccount(). You can get an individual instance resource by passing its uniqueidentifier, or sid, to the appropriate method.
String ACCOUNT_SID = 'AXXXXXXXXXXXXXXXXX';String AUTH_TOKEN = 'YYYYYYYYYYYYYYYYYY';TwilioRestClient client = new TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN);TwilioCall call = client.getAccount().getCall('CA123');System.debug(call.getSid());
Get List Resources
The Twilio API gives you access to various list resources. A list resource object represents a query for instancesresource of a given type. For example, TwilioCallsList provides access to individual TwilioCall resources.You can get the list resource from its parent class, typically TwilioAccount.
String ACCOUNT_SID = 'AXXXXXXXXXXXXXXXXX';String AUTH_TOKEN = 'YYYYYYYYYYYYYYYYYY';TwilioRestClient client = new TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN);TwilioCallList callsResource = client.getAccount().getCalls();
Paging Through List Results
For long lists, the Twilio API breaks the responses into pages of records and returns one at a time. Each list resourcehas a getPageData() method that, by default, returns the most recent 50 instance resources.
String ACCOUNT_SID = 'AXXXXXXXXXXXXXXXXX';String AUTH_TOKEN = 'YYYYYYYYYYYYYYYYYY';TwilioRestClient client = new TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN);TwilioCallList callsResource = client.getAccount().getCalls();List<TwilioCall> calls = callsResource.getPageData()
You can provide arguments to control the page size and current page. The following will return page 3 using a pagesize of 25.
String ACCOUNT_SID = 'AXXXXXXXXXXXXXXXXX';String AUTH_TOKEN = 'YYYYYYYYYYYYYYYYYY';TwilioRestClient client = new TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN);Map<String,String> params = new Map<String,String> {
'page' => 3,'page_size' => 25
};List<TwilioCall> calls = client.getAccount().getCalls(params).getPageData();
Listing All Resources with iterator()
Sometimes you’d like to retrieve all records from a list resource. Instead of manually paging over the resource, each listresource class has an iterator() method that returns a generator. After exhausting the current page, the generatorwill request the next page of results.
Warning: Accessing all your records can be slow. We suggest only doing so when you absolutely need all therecords
8 Chapter 3. User Guide
twilio-salesforce Documentation, Release 1.0
String ACCOUNT_SID = 'AXXXXXXXXXXXXXXXXX';String AUTH_TOKEN = 'YYYYYYYYYYYYYYYYYY';TwilioRestClient client = new TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN);Iterator<TwilioCall> callsIterator = client.getAccount().getCalls().iterator();
3.1.2 Phone Calls
The class TwilioCall resource manages all interaction with Twilio phone calls, including the creation and termi-nation of phone calls.
Making a Phone Call
The TwilioCallList resource allows you to make outgoing calls. Before a call can be successfully started, you’llneed a url which outputs valid TwiML.
String ACCOUNT_SID = 'AXXXXXXXXXXXXXXXXX';String AUTH_TOKEN = 'YYYYYYYYYYYYYYYYYY';TwilioRestClient client = new TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN);
Map<String,String> params = new Map<String,String>() {'To' => '9991231234','From' => '9991231234','Url' => 'http://foo.com/call.xml'
};
TwilioCall call = client.getAccount().getCalls().create(params);System.debug(call.getDuration());System.debug(call.getSid());
Retrieve a Call Record
If you already have a TwilioCall sid, you can use the client to retrieve that record:
String ACCOUNT_SID = 'AXXXXXXXXXXXXXXXXX';String AUTH_TOKEN = 'YYYYYYYYYYYYYYYYYY';TwilioRestClient client = new TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN);
String sid = 'CA12341234';TwilioCall call = client.getAccount().getCall(sid);
Accessing Specific Call Resources
Each TwilioCall resource also has access to its notifications, recordings, and transcriptions. These attributes arelist resources, just like the TwilioCallList resource itself.
String ACCOUNT_SID = 'AXXXXXXXXXXXXXXXXX';String AUTH_TOKEN = 'YYYYYYYYYYYYYYYYYY';TwilioRestClient client = new TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN);
String sid = 'CA12341234';TwilioCall call = client.getAccount().getCall(sid);
System.debug(call.getNotifications().getPageData());
3.1. REST API 9
twilio-salesforce Documentation, Release 1.0
System.debug(call.getRecordings().getPageData());System.debug(call.getTranscriptions().getPageData());
Modifying Live Calls
The TwilioCall resource makes it easy to find current live calls and redirect them as necessary:
String ACCOUNT_SID = 'AXXXXXXXXXXXXXXXXX';String AUTH_TOKEN = 'YYYYYYYYYYYYYYYYYY';TwilioRestClient client = new TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN);
Map<String,String> filters = new Map<String,String>{'Status'=>'in-progress'};Iterator<TwilioCall> calls = client.getAccount().getCalls(filters).iterator();while (calls.hasNext()) {
TwilioCall call = calls.next();call.redirect('http://twimlets.com/holdmusic?Bucket=com.twilio.music.ambient',
'POST');}
Ending all live calls is also possible:
String ACCOUNT_SID = 'AXXXXXXXXXXXXXXXXX';String AUTH_TOKEN = 'YYYYYYYYYYYYYYYYYY';TwilioRestClient client = new TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN);
Map<String,String> filters = new Map<String,String>{'Status'=>'in-progress'};Iterator<TwilioCall> calls = client.getAccount().getCalls(filters).iterator();while (calls.hasNext()) {
TwilioCall call = calls.next();call.hangup();
}
Note that hangup() will also cancel calls currently queued.
In addition to the convenience methods hangup(), redirect(), and cancel() you can also useupdateResource() to update the record directly.
String ACCOUNT_SID = 'AXXXXXXXXXXXXXXXXX';String AUTH_TOKEN = 'YYYYYYYYYYYYYYYYYY';TwilioRestClient client = new TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN);
String sid = "CA12341234"TwilioCall call = client.getAccount().getCall(sid);Map<String,String> properties = new Map<String,String>{
'Url'=> 'http://twimlets.com/holdmusic?Bucket=com.twilio.music.ambient','Method' => 'POST'
};call.updateResource(properties);
3.1.3 Phone Numbers
With Twilio you can search and buy real phone numbers, just using the API.
For more information, see the IncomingPhoneNumbers REST Resource documentation.
10 Chapter 3. User Guide
twilio-salesforce Documentation, Release 1.0
Searching and Buying a Number
Finding numbers to buy couldn’t be easier. We first search for a number in area code 530. Once we find one, we’llpurchase it for our account.
String ACCOUNT_SID = 'AXXXXXXXXXXXXXXXXX';String AUTH_TOKEN = 'YYYYYYYYYYYYYYYYYY';TwilioRestClient client = new TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN);
List<TwilioAvailablePhoneNumbers> numbers;Map<String,String> filters = new Map<String,String> {
'AreaCode' => '530'};
numbers = client.getAccount().getAvailablePhoneNumbers(filters).getPageData();
if (numbers.isEmpty()) {System.debug('No numbers in 530 available');
} else {numbers[0].purchase();
}
Toll Free Numbers
By default, the phone number search looks for local phone numbers. Set Type to tollfree to search toll-freenumbers instead.
TwilioAvailablePhoneNumberList numbers;Map<String,String> filters = new Map<String,String> {'Type' => 'tollfree'};numbers = client.getAccount().getAvailablePhoneNumbers(filters);
Numbers Containing Words
Phone number search also supports looking for words inside phone numbers. The following example will find anyphone number with “FOO” in it.
TwilioAvailablePhoneNumberList numbers;Map<String,String> filters = new Map<String,String> {'Contains' => 'FOO'};numbers = client.getAccount().getAvailablePhoneNumbers(filters);
You can use the ‘’*” wildcard to match any character. The following example finds any phone number that matchesthe pattern ‘’D*D’‘.
TwilioAvailablePhoneNumberList numbers;Map<String,String> filters = new Map<String,String> {'Type' => 'D*D'};numbers = client.getAccount().getAvailablePhoneNumbers(filters);
The Twilio API has plenty of other options to augment your phone number search. The AvailablePhoneNumbersREST Resource documentation describes all the search options at your disposal.
Buying a Number
If you’ve found a phone number you want, you can purchase the number.
3.1. REST API 11
twilio-salesforce Documentation, Release 1.0
String ACCOUNT_SID = 'AXXXXXXXXXXXXXXXXX';String AUTH_TOKEN = 'YYYYYYYYYYYYYYYYYY';TwilioRestClient client = new TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN);
TwilioIncomingPhoneNumber incoming;Map<String,String> properties =
new Map<String,String>{'PhoneNumber' => '+15305431234'};incoming = client.getAccount().getIncomingPhoneNumbers().create(properties);
However, it’s easier to purchase numbers after finding them using search (as shown in the first example).
Changing Applications
An Application encapsulates all necessary URLs for use with phone numbers. Update an application on a phonenumber using updateResource().
String ACCOUNT_SID = 'AXXXXXXXXXXXXXXXXX';String AUTH_TOKEN = 'YYYYYYYYYYYYYYYYYY';TwilioRestClient client = new TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN);
String phone_sid = 'PN123';TwilioIncomingPhoneNumber incoming =
client.getAccount().getIncomingPhoneNumber(phone_sid);
Map<String,String> properties =new Map<String,String>{'SmsApplicationSid' => 'AP456'};
incoming.updateResource(properties);
See Applications for instructions on updating and maintaining Applications.
Validate Caller Id
Adding a new phone number to your validated numbers is quick and easy:
String ACCOUNT_SID = 'AXXXXXXXXXXXXXXXXX';String AUTH_TOKEN = 'YYYYYYYYYYYYYYYYYY';TwilioRestClient client = new TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN);
TwilioCallerIdValidation val =client.getAccount().getAvailableCallerIds().validate('+9876543212');
System.debug(val.getValidationCode());
Display the validation code to your user. Twilio will call the provided number and wait for the validation code to beentered.
3.1.4 SMS Messages
For more information, see the SMS Message REST Resource documentation.
Sending a Text Message
Send a text message in only a few lines of code.
12 Chapter 3. User Guide
twilio-salesforce Documentation, Release 1.0
String ACCOUNT_SID = 'AXXXXXXXXXXXXXXXXX';String AUTH_TOKEN = 'YYYYYYYYYYYYYYYYYY';TwilioRestClient client = new TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN);
Map<String,String> properties = new Map<String,String> {'To' => '+13216851234','From' => '+15555555555','Body' => 'Hello!'
};TwilioMessage message = client.getAccount().getMessages().create(properties);
Note: The message body must be less than 160 characters in length
Sending a MMS
Send a MMS in only a few lines of code.
String ACCOUNT_SID = 'AXXXXXXXXXXXXXXXXX';String AUTH_TOKEN = 'YYYYYYYYYYYYYYYYYY';TwilioRestClient client = new TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN);
List<TwilioNameValuePair> properties = new List<TwilioNameValuePair>();properties.add(new TwilioNameValuePair('To','+13216851234'));
properties.add(new TwilioNameValuePair('From','+15555555555'));properties.add(new TwilioNameValuePair('MediaUrl','https://www.twilio.com/packages/company/img/logos_downloadable_round.png'));
TwilioMessage message = client.getAccount().getMessages().create(properties);
Note: The message body must be less than 160 characters in length
If you want to send a message from a short code on Twilio, just set From to your short code’s number.
Retrieving Sent Messages
String ACCOUNT_SID = 'AXXXXXXXXXXXXXXXXX';String AUTH_TOKEN = 'YYYYYYYYYYYYYYYYYY';TwilioRestClient client = new TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN);
for (TwilioSms message : client.getAccount().getSmsMessages().getPageData()) {System.debug(message.getBody());
}
Filtering Your Messages
The list resource supports filtering on To, From, and DateSent. The following will only show messages to“+5466758723” on January 1st, 2012.
String ACCOUNT_SID = 'AXXXXXXXXXXXXXXXXX';String AUTH_TOKEN = 'YYYYYYYYYYYYYYYYYY';TwilioRestClient client = new TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN);
3.1. REST API 13
twilio-salesforce Documentation, Release 1.0
Map<String,String> filters = new Map<String,String> {'To' => '+5466758723','DateSent' => TwilioParser.formatFilterDatetime(2012,1,1)
};for (TwilioSms message : client.getAccount().getSmsMessages(filters).getPageData()) {
System.debug(message.getBody());}
Short Codes
If you host a Short Code with Twilio, it works just like regular phone numbers with SMS resources.
3.1.5 Accounts
Managing Twilio accounts is straightforward. Update your own account information or create and manage multiplesubaccounts.
For more information, see the Account REST Resource documentation.
Updating Account Information
Use TwilioAccount.updateResource() to modify one of your accounts. Right now the only valid attributeis FriendlyName.
String ACCOUNT_SID = 'AXXXXXXXXXXXXXXXXX';String AUTH_TOKEN = 'YYYYYYYYYYYYYYYYYY';TwilioRestClient client = new TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN);
TwilioAccount twaccount = client.getAccount();Map<String,String> properties = new Map<String,String> {
'FriendlyName' => 'My Awesome SubAccount'};
twaccount.updateResource(properties);
Creating Subaccounts
Subaccounts are easy to make.
String ACCOUNT_SID = 'AXXXXXXXXXXXXXXXXX';String AUTH_TOKEN = 'YYYYYYYYYYYYYYYYYY';TwilioRestClient client = new TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN);
Map<String,String> properties = new Map<String,String> {'FriendlyName' => 'My Awesome SubAccount'
};TwilioAccount subaccount = client.getAccounts().create(properties);
Managing Subaccounts
Say you have a subaccount for Client X with an account sid AC123
14 Chapter 3. User Guide
twilio-salesforce Documentation, Release 1.0
String ACCOUNT_SID = 'AXXXXXXXXXXXXXXXXX';String AUTH_TOKEN = 'YYYYYYYYYYYYYYYYYY';TwilioRestClient client = new TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN);
# Client X's subaccountTwilioAccount subaccount = client.getAccount('AC123');
Client X hasn’t paid you recently, so let’s suspend their account.
subaccount.suspend()
If it was just a misunderstanding, reenable their account.
subaccount.activate()
Otherwise, close their account permanently.
Warning: This action can’t be undone.
subaccount.close()
3.1.6 Conferences and Participants
For more information, see the Conference REST Resource and Participant REST Resource documentation.
Listing Conferences
String ACCOUNT_SID = 'AXXXXXXXXXXXXXXXXX';String AUTH_TOKEN = 'YYYYYYYYYYYYYYYYYY';TwilioRestClient client = new TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN);
TwilioConferenceList confs = client.getAccount().getConferences();for (TwilioConference conference : confs.getPageData()) {
System.debug(conference.getSid());}
Filtering Conferences
The Twilio API supports filtering Conferences on Status, DateUpdated, DateCreated and FriendlyName.The following code will return a list of all active conferences and print their friendly name.
String ACCOUNT_SID = 'AXXXXXXXXXXXXXXXXX';String AUTH_TOKEN = 'YYYYYYYYYYYYYYYYYY';TwilioRestClient client = new TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN);
Map<String,String> filters = new Map<String,String> {'Status' => 'active'
};TwilioConferenceList confs = client.getAccount().getConferences(filters);for (TwilioConference conference : confs.getPageData()) {
System.debug(conference.getFriendlyName());}
3.1. REST API 15
twilio-salesforce Documentation, Release 1.0
Listing Participants
Each TwilioConference has a getParticipants() method which represents all current users in the confer-ence
String ACCOUNT_SID = 'AXXXXXXXXXXXXXXXXX';String AUTH_TOKEN = 'YYYYYYYYYYYYYYYYYY';TwilioRestClient client = new TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN);
TwilioConference conference = client.getAccount().getConference("CF123");for (TwilioParticipant p : conference.getParticipants().getPageData()) {
System.debug(p.getSid());}
Managing Participants
Each TwilioConference has a participants function that returns a TwilioParticipantList resource.This behavior differs from other list resources because TwilioParticipant needs a participant sid AND a con-ference sid to access the participants resource.
Participants can be either muted or kicked out of the conference. The following code kicks out the first participant andmutes the others.
String ACCOUNT_SID = 'AXXXXXXXXXXXXXXXXX';String AUTH_TOKEN = 'YYYYYYYYYYYYYYYYYY';TwilioRestClient client = new TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN);
String conferenceSid = 'CF123';Iterator<TwilioParticipants> participants =
client.getAccount().getParticipants(conferenceSid).iterator();
if (!participants.hasNext())return;
# Kick the first person outparticipants.next().kick();
# And mute the restwhile (participants.hasNext()) {
participants.next().mute();}
3.1.7 Applications
A TwiML application inside of Twilio is just a set of URLs and other configuration data that tells Twilio how to behavewhen one of your Twilio numbers receives a call or SMS message.
For more information, see the Application REST Resource documentation.
Listing Your Applications
The following code will print out the FriendlyName for each TwilioApplication.
16 Chapter 3. User Guide
twilio-salesforce Documentation, Release 1.0
String ACCOUNT_SID = 'AXXXXXXXXXXXXXXXXX';String AUTH_TOKEN = 'YYYYYYYYYYYYYYYYYY';TwilioRestClient client = new TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN);
for (TwilioApplication app : client.getAccount().getApplications().getPageData()) {System.debug(app.getFriendlyName());
}
Filtering Applications
You can filter applications by Friendly Name
String ACCOUNT_SID = 'AXXXXXXXXXXXXXXXXX';String AUTH_TOKEN = 'YYYYYYYYYYYYYYYYYY';TwilioRestClient client = new TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN);
Map<String,String> filters = new Map<String,String> {'FriendlyName' => 'FOO'
};TwilioApplicationList apps = client.getAccount().getApplications(filters);
for (TwilioApplication app : apps.getPageData()) {System.debug(app.getSid());
}
Creating an Application
When creating an application, no fields are required. We create an application with only a Friendly Name.TwilioApplicationList.create() accepts many other arguments for url configuration.
String ACCOUNT_SID = 'AXXXXXXXXXXXXXXXXX';String AUTH_TOKEN = 'YYYYYYYYYYYYYYYYYY';TwilioRestClient client = new TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN);
Map<String,String> properties = new Map<String,String> {'FriendlyName' => 'My New App'
};TwilioApplication app = client.getAccount().getApplications().create(properties);
Updating an Application
String ACCOUNT_SID = 'AXXXXXXXXXXXXXXXXX';String AUTH_TOKEN = 'YYYYYYYYYYYYYYYYYY';TwilioRestClient client = new TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN);
String app_sid = 'AP123';TwilioApplication app = client.getAccount().getApplication(app_sid);Map<String,String> properties = new Map<String,String> {
'VoiceUrl' =>'http://twimlets.com/holdmusic?Bucket=com.twilio.music.ambient'
};app.updateResource(properties);
3.1. REST API 17
twilio-salesforce Documentation, Release 1.0
Deleting an Application
You can delete an application from the list resource or the instance resource:
String ACCOUNT_SID = 'AXXXXXXXXXXXXXXXXX';String AUTH_TOKEN = 'YYYYYYYYYYYYYYYYYY';TwilioRestClient client = new TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN);
String app_sid = 'AP123';// delete from the list resourceclient.getAccount().getApplications().deleteApplication(app_sid);// or do the same thing from the instance resourceclient.getAccount().getApplication(app_sid).deleteApplication();
3.1.8 Notifications
For more information, see the Notifications REST Resource documentation.
Listing Your Notifications
The following code will print out additional information about each of your current TwilioNotification re-sources.
String ACCOUNT_SID = 'AXXXXXXXXXXXXXXXXX';String AUTH_TOKEN = 'YYYYYYYYYYYYYYYYYY';TwilioRestClient client = new TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN);
for (TwilioNotification n : client.getAccount().getNotifications().getPageData()) {System.debug(n.getMoreInfo());
}
You can filter transcriptions by Log and MessageDate. The Log value is 0 for ERROR and 1 for WARNING.
String ACCOUNT_SID = 'AXXXXXXXXXXXXXXXXX';String AUTH_TOKEN = 'YYYYYYYYYYYYYYYYYY';TwilioRestClient client = new TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN);
String ERROR = '0';
Map<String,String> filters = new Map<String,String> {'Log' => ERROR;
}
for (TwilioNotification n : client.getAcount().getNotifications().getPageData()) {System.debug(n.getErrorCode());
}
Note: Due to the potentially voluminous amount of data in a notification, the full HTTP request and response data isonly returned in the Notification instance resource representation.
Deleting Notifications
Your account can sometimes generate an inordinate amount of Notification resources. TheTwilioNotificationList resource allows you to delete unnecessary notifications.
18 Chapter 3. User Guide
twilio-salesforce Documentation, Release 1.0
String ACCOUNT_SID = 'AXXXXXXXXXXXXXXXXX';String AUTH_TOKEN = 'YYYYYYYYYYYYYYYYYY';TwilioRestClient client = new TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN);
client.getAccount().getNotifications().deleteResource("NO123")
3.1.9 Recordings
For more information, see the Recordings REST Resource documentation.
Listing Your Recordings
The following code will print out the duration for each TwilioRecording.
String ACCOUNT_SID = 'AXXXXXXXXXXXXXXXXX';String AUTH_TOKEN = 'YYYYYYYYYYYYYYYYYY';TwilioRestClient client = new TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN);
for (TwilioRecording rec : client.getAccount().getRecordings().getPageData()) {System.debug(rec.getDuration());
}
You can filter recordings by the Call by passing the sid as CallSid, or you can filter by DateCreated.
The following will only show recordings made on January 1, 2012.
String ACCOUNT_SID = 'AXXXXXXXXXXXXXXXXX';String AUTH_TOKEN = 'YYYYYYYYYYYYYYYYYY';TwilioRestClient client = new TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN);
Map<String,String> filters = new Map<String,String> {'DateCreated' => TwilioParser.formatFilterDatetime(2012,1,1)
};for (TwilioRecording rec : client.getAccount().getRecordings(filters).getPageData()) {
System.debug(rec.getDuration());}
Deleting Recordings
The TwilioRecordingList resource allows you to delete unnecessary recordings.
String ACCOUNT_SID = 'AXXXXXXXXXXXXXXXXX';String AUTH_TOKEN = 'YYYYYYYYYYYYYYYYYY';TwilioRestClient client = new TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN);
client.getAccount().getRecordings().deleteResource("RC123");
Audio Formats
Each TwilioRecording can return the the URI to the recorded audio in WAV or MP3 format.
String ACCOUNT_SID = 'AXXXXXXXXXXXXXXXXX';String AUTH_TOKEN = 'YYYYYYYYYYYYYYYYYY';TwilioRestClient client = new TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN);
3.1. REST API 19
twilio-salesforce Documentation, Release 1.0
TwilioRecording rec = client.getRecording("RC123");System.debug(rec.getWavUri());System.debug(rec.getMp3Uri());
Accessing Related Transcriptions
The TwilioRecording resource provides access to transcriptions generated from the recording (if any). Thefollowing code prints out the text for each of the transcriptions associated with this recording.
String ACCOUNT_SID = 'AXXXXXXXXXXXXXXXXX';String AUTH_TOKEN = 'YYYYYYYYYYYYYYYYYY';TwilioRestClient client = new TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN);
recording = client.getRecording("RC123");for (TwilioTranscription t : recording.getTranscriptions().getPageData()) {
System.debug(t.getTranscriptionText());}
3.1.10 Transcriptions
Transcriptions are generated from recordings via the TwiML <Record> verb. Using the API, you can only read yourtranscription records.
For more information, see the Transcriptions REST Resource documentation.
Listing Your Transcriptions
The following code will print out recording length for each TwilioTranscription.
String ACCOUNT_SID = 'AXXXXXXXXXXXXXXXXX';String AUTH_TOKEN = 'YYYYYYYYYYYYYYYYYY';TwilioRestClient client = new TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN);
for (TwilioTranscription t : client.getAccount().getTransactions().getPageData()) {System.debug(t.getDuration());
}
3.2 TwiML
Generates Twilio Markup Language (TwiML) instructions for controlling and manipulating live phone calls and re-sponding to text messages.
3.2.1 Working with TwiML
TwiML controls live phone calls and respond to text messages in real time through Twilio’s API.
When an SMS or incoming call is received, Twilio asks your web application for instructions by making an HTTPrequest. Your application decides how the call should proceed by returning a Twilio Markup XML (TwiML) documenttelling Twilio to say text to the caller, send an SMS message, play audio files, get input from the keypad, record audio,connect the call to another phone and more.
20 Chapter 3. User Guide
twilio-salesforce Documentation, Release 1.0
You can create TwiML documents in Apex using the verb classes defined inside the TwilioTwiML class.
Generating TwiML in Apex
TwiML creation begins with the TwilioTwiML.Response class. Each successive TwiML command is created byadding additional verb classes such as Say or Play to the response using append(). When your instruction set iscomplete, call Response.toXML() to produce a TwiML document.
TwilioTwiML.Response r = new TwilioTwiML.Response();r.append(new TwilioTwiML.Say('Hello'));System.debug(r.toXML());
<Response><Say>Hello</Say>
<Response>
Sometimes you’ll want to set properties beyond what’s covered in the constructor. In these cases, assign the verb classto its own variable and set its properties before appending it to the response.
TwilioTwiML.Response r = new TwilioTwiML.Response();TwilioTwiML.Play p = new TwilioTwimL.Play('https://api.twilio.com/cowbell.mp3');p.setLoop(5);r.append(p);System.debug(r.toXML());
<Response><Play loop="3">https://api.twilio.com/cowbell.mp3</Play>
<Response>
You can provide multiple actions in sequence simply by appending more verbs to the response. Some verbs can benested inside other verbs, like Say inside of Gather.
TwilioTwiML.Response r = new TwilioTwiML.Response();r.append(new TwilioTwiML.Say('Hello'));TwilioTwiML.Gather g = new TwilioTwiML.Gather();g.setFinishOnKey('4');g.append(new TwilioTwiML.Say('World');r.append(g);System.debug(r.toXML());
<Response><Say>Hello</Say><Gather finishOnKey="4"><Say>World</Say></Gather>
</Response>
Serving TwiML Requests from a Force.com Site
1. Create the following Apex page controller MyTwiMLController:
public class MyTwiMLController {
public MyTwiMLController() {}
public String getTwiml() {TwilioTwiML.Response res = new TwilioTwiML.Response();res.append(new TwilioTwiML.Say('Hello, Monkey!'));res.append(
3.2. TwiML 21
twilio-salesforce Documentation, Release 1.0
new TwilioTwiML.Play('http://demo.twilio.com/hellomonkey/monkey.mp3'));res.append(new TwilioTwiML.Hangup());return res.toXML();
}}
2. Create the following Visualforce page TwiMLPage:
<apex:page controller="TwiMLPage"showheader="false"contentType="text/xml">{! '<?xml version=\"1.0\" encoding=\"UTF-8\"?>' }
{!twiml}</apex:page>
3. In Salesforce, go to Setup | App Setup | Develop | Sites and create a new site. Set the home page to TwiMLPageto the list of Site Visualforce Pages. Ensure you activate the site.
4. Log into your Twilio account. Go to Numbers, buy a phone number, and set the Voice RequestURL to the URL of your Visualforce page on your Site – for example, https://twiliotest-developer-edition.na14.force.com/TwiMLPage
5. Test your app by calling the phone number.
Now you have the sample page working, you have a starting point for a TwiML app running on Force.com. ExamineTwilioSamplePage and TwilioSampleController to see how the sample app is put together.
More Information
The complete list of TwiML verbs and attributes is available in the Twilio Markup Language documentation.
3.3 Client
Small functions useful for validating requests are coming from Twilio
3.3.1 Twilio Client
Twilio Client extends the power of Twilio beyond the traditional telephone network. In the past, the only way totransport audio into and out of Twilio was via the PSTN using telephones. With Twilio Client you are no longerrestricted to building Twilio applications that rely on interacting with traditional telephones. And best of all, yourexisting applications will already work with Twilio Client.
The twilio.js Library Take your existing Twilio applications and bring them to the browser using the twilio.js Li-brary.
Twilio Client Mobile SDKs Add voice to your mobile applications with the Twilio Client Mobile SDKs for iOS andAndroid.
How It Works
Twilio Client calls span three environments, just like a regular Twilio call. In both cases, the call comes in to Twilio,which then makes a request to your application for TwiML instructions to control the call. Unlike regular phone calls,however, Twilio Client calls use a client-side web or mobile app in place of a phone.
22 Chapter 3. User Guide
twilio-salesforce Documentation, Release 1.0
On the Client
From your client-side code running in your user’s browser or mobile device, you setup your Twilio Client deviceand establish a connection to Twilio. Audio from your device’s microphone is sent to Twilio, and Twilio plays audiothrough your device’s speakers, like on a normal phone call.
The Twilio Application
When you initiate a connection using Twilio Client, you’re not connecting to another phone directly. Rather, you’reconnecting to Twilio and instructing Twilio to fetch TwiML from your server to handle the connection. This isanalogous to the way Twilio handles incoming calls from a real phone. All the same TwiML verbs and nouns that areavailable for handling Twilio Voice calls are also available for handling Twilio Client connections. We’ve also addeda <Client> noun for dialing to a Client.
Because Twilio Client connections aren’t made to a specific phone number, Twilio relies on a Twilio Applicationwithin your account to determine how to interact with your server. A Twilio Application is just a convenient way tostore a set of URLs, like the VoiceUrl and SmsUrl on a phone number, but without locking them to a specific phonenumber. This makes Twilio Applications perfect for handling connections from Twilio Client (which is actually whywe created them in the first place).
Capability Tokens
When your device initiates a Twilio Client connection to Twilio, it identifies itself using a Capability Token. This tokenauthorizes the client-side application to connect to Twilio using your Twilio account, and specifies which Applicationwithin your account to use. Twilio then makes a request to the VoiceUrl property of the Application, and uses theTwiML response from the request direct what happens with the Client connection.
Because the purpose of the Capability Token is to authorize the direct connection between the client-side code andTwilio, you will use server-side code to generate the tokens. If your client-side app is a web page, you typically willgenerate the token when you generate the page itself. If your client-side app is a mobile device, you may need to createa service for your the mobile app to request a token from your server.
Once your client-side app has a valid token, it can make outbound and/or receive inbound calls through Twilio directly,until the token expires.
Adding Twilio Client to Salesforce
Using the TwilioCapability class
Capability tokens are used by Twilio Client to provide connection security and authorization. The Capability Tokendocumentation explains in depth the purpose and features of these tokens.
TwilioCapability is responsible for the creation of these capability tokens. You’ll need your Twilio AccountSidand AuthToken.
String accountSid = 'ACXXXXXXXXXXXXXXXXX';String authToken = 'YYYYYYYYYYYYYYYYYY';TwilioCapability capability = new TwilioCapability(accountSid, authToken);
3.3. Client 23
twilio-salesforce Documentation, Release 1.0
Allow Incoming Connections
Before a device running Twilio Client can recieve incoming connections, the instance must first register a name (suchas “Alice” or “Bob”). The allowClientIncoming() method adds the client name to the capability token.
capability.allowClientIncoming('Alice');
Allow Outgoing Connections
To make an outgoing connection from a Twilio Client device, you’ll need to choose a Twilio Application to handleTwiML URLs. A Twilio Application is a collection of URLs responsible for outputing valid TwiML to control phonecalls and SMS.
// Twilio Application SidString applicationSid = 'APabe7650f654fc34655fc81ae71caa3ff';capability.allowClientOutgoing(applicationSid);
Generate a Token
String token = capability.generateToken();
By default, this token will expire in one hour. If you’d like to change the token expiration, generateToken() takesan optional expires argument.
String token = capability.generateToken(600);
This token will now expire in 10 minutes. If you haven’t guessed already, expires is expressed in seconds.
Visualforce Example
The controller is responsible for generating the token so it can be embedded in the Visualforce page.
public class TwilioClientController {private TwilioCapability capability;
public TwilioClientController() {capability = TwilioAPI.createCapability();capability.allowClientOutgoing(
TwilioAPI.getTwilioConfig().ApplicationSid__c,null);
}
public String getToken() { return capability.generateToken(); }}
The Visualforce page includes the twilio.min.js Javascript library and calls Twilio.Device.setup(token) to autho-rize the client-side device. Buttons on the page allow the user to invoke Twilio.Device.connect() andTwilio.Device.disconnectAll().
<apex:page controller="TwilioClientController" showHeader="false"><apex:includeScriptvalue="//static.twilio.com/libs/twiliojs/1.0/twilio.min.js"/>
<apex:includeScriptvalue="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"/>
24 Chapter 3. User Guide
twilio-salesforce Documentation, Release 1.0
<apex:stylesheetvalue="http://static0.twilio.com/packages/quickstart/client.css"/>
<script type="text/javascript">// pass the Capability Token to the DeviceTwilio.Device.setup("{! token }");
Twilio.Device.connect(function (conn) {$("#log").text("Successfully established call");
});
Twilio.Device.disconnect(function (conn) {$("#log").text("Call ended");
});
function call() {Twilio.Device.connect();
}
function hangup() {Twilio.Device.disconnectAll();
}</script><div height="100%" width="100%" class="bg">
<button class="call" onclick="call();">Call
</button>
<button class="hangup" onclick="hangup();">Hangup
</button>
<div id="log"/><br/>
</div></apex:page>
3.3. Client 25
twilio-salesforce Documentation, Release 1.0
26 Chapter 3. User Guide
CHAPTER 4
Support and Development
All project development occurs on GitHub. To checkout the source, use:
$ git clone [email protected]:twilio/twilio-salesforce.git
Report bugs using the Github issue tracker.
If you have questions that aren’t answered by this documentation, ask the #twilio IRC channel
27
twilio-salesforce Documentation, Release 1.0
28 Chapter 4. Support and Development
Index
TThe twilio.js Library, 22Twilio Client Mobile SDKs, 22
29