twilio-salesforce Documentation



Similar documents
Phone Manager Application Support JANUARY 2015 DOCUMENT RELEASE 4.2 APPLICATION SUPPORT

Cloud Elements ecommerce Hub Provisioning Guide API Version 2.0 BETA

Development Lifecycle Guide

Fairsail REST API: Guide for Developers

TABLE OF CONTENTS. avaya.com

Cloud Elements! Marketing Hub Provisioning and Usage Guide!

The full setup includes the server itself, the server control panel, Firebird Database Server, and three sample applications with source code.

Getting Started. Getting Started with Time Warner Cable Business Class. Voice Manager. A Guide for Administrators and Users

Salesforce Mobile Push Notifications Implementation Guide

Login with Amazon. Getting Started Guide for Websites. Version 1.0

Salesforce Classic Guide for iphone

Single-User VoIP Service User Manual. Version Revised

Using FreePBX with Twilio Elastic SIP Trunking

Chatter Answers Implementation Guide

Configuration Guide - OneDesk to SalesForce Connector

Installation and Administration Guide

Chatter Answers Implementation Guide

Hosted Contact Centre Configuration Manager Guide Version Revision 1.0

Dictamus Manual. Dictamus is a professional dictation app for iphone, ipod touch and ipad. This manual describes setup and use of Dictamus version 10.

QAS Small Business for Salesforce CRM

Frequently Asked Questions: Cisco Jabber 9.x for Android

Identity Implementation Guide

SpringCM Troubleshooting Guide for Salesforce

Salesforce Integration

Salesforce.com Integration Guide

one Managing your PBX Administrator ACCESSING YOUR PBX ACCOUNT CHECKING ACCOUNT ACTIVITY

Working with Indicee Elements

TOTAL DEFENSE MOBILE SECURITY USER S GUIDE

Fusion Voic Plus User Guide For Android Devices

Hubcase for Salesforce Installation and Configuration Guide

DroboAccess User Manual

How To Set Up A Scopdial On A Pc Or Macbook Or Ipod (For A Pc) With A Cell Phone (For Macbook) With An Ipod Or Ipo (For An Ipo) With Your Cell Phone Or

Hosted VoIP Phone System. Meet Me Audio Conferencing. User Guide

Advanced Tornado TWENTYONE Advanced Tornado Accessing MySQL from Python LAB

Getting Started with Loyola s New Voic System

License Management and Support Guide

Single Sign-On Implementation Guide

Introduction to Building Windows Store Apps with Windows Azure Mobile Services

Single Sign-On Implementation Guide

Avaya one-x Mobile User Guide for iphone

Phone Manager Application Support OCTOBER 2014 DOCUMENT RELEASE 4.1 SAGE CRM

Virtual Contact Center

PHP Integration Kit. Version User Guide

Portals and Hosted Files

Installation & Configuration Guide Professional Edition

Your Phone. Your Business. Your World. SM SM

Bizconferencing Service

LiveText Agent for Salesforce Installation Guide

For details about using automatic user provisioning with Salesforce, see Configuring user provisioning for Salesforce.

ISVforce Guide. Version 35.0, Winter

Guide for Setting Up Your Multi-Factor Authentication Account and Using Multi-Factor Authentication. Mobile App Activation

LiveText for Salesforce Quick Start Guide

Building Secure Applications. James Tedrick

Salesforce Files Connect Implementation Guide

Presto User s Manual. Collobos Software Version Collobos Software, Inc

Force.com Migration Tool Guide

Samsung Xchange for Mac User Guide. Winter 2013 v2.3

Customize Mobile Apps with MicroStrategy SDK: Custom Security, Plugins, and Extensions

Digital Voice Services User Guide

Set Up and Maintain Customer Support Tools

User Guide FOR TOSHIBA STORAGE PLACE

RingCentral Office. Basic Start Guide FOR USERS

Secure Coding SSL, SOAP and REST. Astha Singhal Product Security Engineer salesforce.com

Configuring Salesforce

IBM Unica emessage Version 8 Release 6 February 13, User's Guide

AT&T Voice DNA User Guide

A This panel lists all the IVR queues you have built so far. This is where you start the creation of a IVR

SpringCM Integration Guide. for Salesforce

License Management App 2.1 Administration and User Guide

SpringCM Integration Guide. for Salesforce

Practice Fusion API Client Installation Guide for Windows

Integrating Skype for SIP with UC500

Fax User Guide 07/31/2014 USER GUIDE

DocuSign for Salesforce Administrator Guide v6.1.1 Rev A Published: July 16, 2015

dotmailer for Salesforce Installation Guide Winter 2015 Version

New World Construction FTP service User Guide

Force.com Canvas Developer's Guide

HTTP Reverse Proxy Scenarios

Business mail 1 MS OUTLOOK CONFIGURATION... 2

Integrating LivePerson with Salesforce

Integrated Billing Solutions with HP CSA 4.00

Quick Start Configuration Guide Salesforce.com Integration

Desktop Reference Guide

Coveo Platform 7.0. Salesforce Connector Guide

MASTERPASS MERCHANT ONBOARDING & INTEGRATION GUIDE

Contents. Cbeyond Communicator for Mobile (ios) extends TotalCloud Phone System (TCPS) calling capabilities to an iphone.

LEVEL 3 SM XPRESSMEET SOLUTIONS

DocuSign Connect for Salesforce Guide

Contents 1. Setting up your Phone Phone Setup Phone Usage 2. User Portal 3. Softphone for your computer 4. Faxing

RingCentral for Outlook. Installation & User Guide

PLANET is a registered trademark of PLANET Technology Corp. All other trademarks belong to their respective owners.

My Account Quick Start

Programming Autodesk PLM 360 Using REST. Doug Redmond Software Engineer, Autodesk

Salesforce Mobile Push Notifications Implementation Guide

Administering Jive Mobile Apps

Content Filtering Client Policy & Reporting Administrator s Guide

Sophos Mobile Control User guide for Android. Product version: 4

Architecture and Data Flow Overview. BlackBerry Enterprise Service Version: Quick Reference

Contents Release Notes System Requirements Administering Jive for Office

Using the Push Notifications Extension Part 1: Certificates and Setup

Transcription:

twilio-salesforce Documentation Release 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

Get ready to unleash the power of the Twilio cloud communications platform in Salesforce and Force.com! Soon you 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

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 the included Ant script. 1. Checkout or download the twilio-salesforce library from GitHub. $ git clone git@github.com: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 be using 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

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, the following 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 Twilio account. // To find these visit https://www.twilio.com/user/account String 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 Twilio account. 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

; 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 a TwiML 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 to use. This guide assumes you understand the core concepts of Twilio. If you ve never used Twilio before, don t fret! Just read 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 specific portions 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 more information, 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 directly to the constructor, we suggest storing your credentials inside the TwilioConfig custom setting. Why? You ll never have to 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, in the TwilioConfig custom setting. You can configure TwilioConfig by going to Setup Develop Custom Settings, and your 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 account credentials directly to the the constructor. 7

Get an Individual Resource Most resources in the Twilio API can be accessed from TwilioAccount, available from TwilioRestClient.getAccount(). You can get an individual instance resource by passing its unique identifier, or sid, to the appropriate method. 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 instances resource 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. 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 resource has a getpagedata() method that, by default, returns the most recent 50 instance resources. 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 page size of 25. 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 list resource class has an iterator() method that returns a generator. After exhausting the current page, the generator will request the next page of results. Warning: records Accessing all your records can be slow. We suggest only doing so when you absolutely need all the 8 Chapter 3. User Guide

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 termination of phone calls. Making a Phone Call The TwilioCallList resource allows you to make outgoing calls. Before a call can be successfully started, you ll need a url which outputs valid TwiML. 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 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 are list resources, just like the TwilioCallList resource itself. String sid = 'CA12341234'; TwilioCall call = client.getaccount().getcall(sid); System.debug(call.getNotifications().getPageData()); 3.1. REST API 9

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: 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: 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 use updateresource() to update the record directly. 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

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 ll purchase it for our account. 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-free numbers 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 any phone 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 matches the 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 AvailablePhoneNumbers REST 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

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 phone number using updateresource(). 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: 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 be entered. 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

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. 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/lo 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 for (TwilioSms message : client.getaccount().getsmsmessages().getpagedata()) { System.debug(message.getBody()); Filtering Your Messages The list resource supports filtering on To, From, and DateSent. +5466758723 on January 1st, 2012. The following will only show messages to 3.1. REST API 13

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 multiple subaccounts. 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 attribute is FriendlyName. 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. 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

# Client X's subaccount TwilioAccount 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 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. 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

Listing Participants Each TwilioConference has a getparticipants() method which represents all current users in the conference 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 conference 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 and mutes the others. String conferencesid = 'CF123'; Iterator<TwilioParticipants> participants = client.getaccount().getparticipants(conferencesid).iterator(); if (!participants.hasnext()) return; # Kick the first person out participants.next().kick(); # And mute the rest while (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 behave when 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

for (TwilioApplication app : client.getaccount().getapplications().getpagedata()) { System.debug(app.getFriendlyName()); Filtering Applications You can filter applications by Friendly Name 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. Map<String,String> properties = new Map<String,String> { 'FriendlyName' => 'My New App' ; TwilioApplication app = client.getaccount().getapplications().create(properties); Updating an Application 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

Deleting an Application You can delete an application from the list resource or the instance resource: String app_sid = 'AP123'; // delete from the list resource client.getaccount().getapplications().deleteapplication(app_sid); // or do the same thing from the instance resource client.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 resources. 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 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 is only returned in the Notification instance resource representation. Deleting Notifications Your account can sometimes generate an inordinate amount of Notification resources. The TwilioNotificationList resource allows you to delete unnecessary notifications. 18 Chapter 3. User Guide

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. 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. 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. client.getaccount().getrecordings().deleteresource("rc123"); Audio Formats Each TwilioRecording can return the the URI to the recorded audio in WAV or MP3 format. 3.1. REST API 19

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). The following code prints out the text for each of the transcriptions associated with this recording. 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 your transcription records. For more information, see the Transcriptions REST Resource documentation. Listing Your Transcriptions The following code will print out recording length for each TwilioTranscription. 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 responding 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 HTTP request. Your application decides how the call should proceed by returning a Twilio Markup XML (TwiML) document telling 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

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 by adding additional verb classes such as Say or Play to the response using append(). When your instruction set is complete, 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 class to 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 be nested 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

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 TwiMLPage to 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 Request URL to the URL of your Visualforce page on your Site for example, https://twiliotest-developeredition.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. Examine TwilioSamplePage 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 to transport audio into and out of Twilio was via the PSTN using telephones. With Twilio Client you are no longer restricted to building Twilio applications that rely on interacting with traditional telephones. And best of all, your existing applications will already work with Twilio Client. Take your existing Twilio applications and bring them to the browser using the twilio.js Li- The twilio.js Library brary. Twilio Client Mobile SDKs Add voice to your mobile applications with the Twilio Client Mobile SDKs for ios and Android. 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

On the Client From your client-side code running in your user s browser or mobile device, you setup your Twilio Client device and establish a connection to Twilio. Audio from your device s microphone is sent to Twilio, and Twilio plays audio through 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 re connecting to Twilio and instructing Twilio to fetch TwiML from your server to handle the connection. This is analogous to the way Twilio handles incoming calls from a real phone. All the same TwiML verbs and nouns that are available for handling Twilio Voice calls are also available for handling Twilio Client connections. We ve also added a <Client> noun for dialing to a Client. Because Twilio Client connections aren t made to a specific phone number, Twilio relies on a Twilio Application within your account to determine how to interact with your server. A Twilio Application is just a convenient way to store a set of URLs, like the VoiceUrl and SmsUrl on a phone number, but without locking them to a specific phone number. This makes Twilio Applications perfect for handling connections from Twilio Client (which is actually why we 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 token authorizes the client-side application to connect to Twilio using your Twilio account, and specifies which Application within your account to use. Twilio then makes a request to the VoiceUrl property of the Application, and uses the TwiML 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 and Twilio, you will use server-side code to generate the tokens. If your client-side app is a web page, you typically will generate the token when you generate the page itself. If your client-side app is a mobile device, you may need to create a 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 Token documentation 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 AccountSid and AuthToken. String accountsid = 'ACXXXXXXXXXXXXXXXXX'; String authtoken = 'YYYYYYYYYYYYYYYYYY'; TwilioCapability capability = new TwilioCapability(accountSid, authtoken); 3.3. Client 23

Allow Incoming Connections Before a device running Twilio Client can recieve incoming connections, the instance must first register a name (such as 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 handle TwiML URLs. A Twilio Application is a collection of URLs responsible for outputing valid TwiML to control phone calls and SMS. // Twilio Application Sid String 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() takes an 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 authorize the client-side device. Buttons on the page allow the user to invoke Twilio.Device.connect() and Twilio.Device.disconnectAll(). <apex:page controller="twilioclientcontroller" showheader="false"> <apex:includescript value="//static.twilio.com/libs/twiliojs/1.0/twilio.min.js"/> <apex:includescript value="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"/> 24 Chapter 3. User Guide

<apex:stylesheet value="http://static0.twilio.com/packages/quickstart/client.css"/> <script type="text/javascript"> // pass the Capability Token to the Device Twilio.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> </apex:page> <div id="log"/> <br/> 3.3. Client 25

26 Chapter 3. User Guide

CHAPTER 4 Support and Development All project development occurs on GitHub. To checkout the source, use: $ git clone git@github.com: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

28 Chapter 4. Support and Development

Index T The twilio.js Library, 22 Twilio Client Mobile SDKs, 22 29