Vous êtes sur la page 1sur 23

TringMe Flash & Rest API

Version 1.7

Last Update: May 28, 2009

Notice: Use of TringMe API is subjected to API Terms of Service available from TringMes website. TringMe reserves the right to update and change the Terms of Service from time to time without notice.

TringMe Flash & REST API

Page 1

Table 1 Revision History


Date Dec 29th, 2008 Jan 5th, 2009 Jan 21st 2009 Version 1.3 1.4 1.5 Feb 24th 2009 1.6 May 28th 2009 1.7 Brief Description Updated REST API Added Caller ID support for Flash calling Added support for managing private users. Added call status notification in Flash Updated SIP URL domain address Added Calltag support in Flash Add Duration and Calltag support in Click2Call New Click2Call Parameters added

TringMe Flash & REST API

Page 2

Table of Contents
1 2 Overview ............................................................................................................................................... 4 REST API ................................................................................................................................................. 6 2.1 2.2 SSL Support.................................................................................................................................... 6 API Parameters .............................................................................................................................. 6 Mandatory Parameters ......................................................................................................... 6 Operation Table..................................................................................................................... 6 Results .................................................................................................................................14

2.2.1 2.2.2 2.2.3 2.3

Calling API ....................................................................................................................................14 Generating Signature ..........................................................................................................15 Generating API URL .............................................................................................................15

2.3.1 2.3.2 2.4 2.5

Debugging....................................................................................................................................16 Call Status Notifications in REST API...........................................................................................16 Notification Parameters ......................................................................................................16 Notification Security ............................................................................................................17

2.5.1 2.5.2 3 4

PHP Helper Functions ..........................................................................................................................17 Using Existing TringMe Flash Widgets.................................................................................................18 4.1 4.2 Embedding TringPhone widget ...................................................................................................18 Embedding Push-n-talk widget ...................................................................................................18

Developing your own Flash Telephony Widgets .................................................................................19 5.1 5.2 5.3 5.4 Making Call ..................................................................................................................................19 NetConnection targetURI Specification ......................................................................................20 Ending Call ...................................................................................................................................21 Call Status Notifications in Flash ................................................................................................22

TringMe Flash & REST API

Page 3

1 Overview
TringMe opens up its platform APIs for developers to empower them to create rich web-based, standalone or mobile voice applications and recreate a all of TringMes functionality. For example, Social networking, dating sites can easily integrate voice as a means of communication in innovative ways VoIP providers can quickly deploy and offer their services using TringMes easy to use AdobeFlash based web-phone or mobile devices enabled via cheap to use Mobile-VoIP Game developers, virtual world creators can enable making phone calls from virtual world to real world and vice-versa.

The platform is written from scratch to cater to the emerging needs of the internet, mobile devices and their diverse usage in real world or virtual. TringMe has abstracted the inner details of call signaling and call processing by exposing easy to use, standards based APIs for developers to essentially innovate at the application level Web based apps Apps for mobile devices Desktop based apps.

TringMes unified communication architecture enabled APIs to be used by any kind of application and not just tie it to Adobe Flash, Flex, AIR, PHP, AJAX or any one technology or platform. TringMe offers an interface which is cross-platform and scalable on any language. Whether its just voice enabling a website, a social networking site (facebook, orkut, myspace etc.), integrating voice into CRM, Sales Management tool or a full-featured desktop AIR application, TringMes APIs will be used to your requirements. TringMe APIs are built to integrate telephony into applications which require a reliable and efficient service. Using the simple to use REST based APIs, developers can add telephony capabilities to their apps in a matter of couple of hours. TringMes APIs will allow developers to configure and utilize any number of call origination and call termination options as supported by TringSwitch (PSTN, Mobile Phones, VoIP apps, SIP URIs, IM Gtalk, SMS-initiated calls, Web applications, Browser, Desktop widgets etc). Developers can quickly create their own Adobe Flash, Flex or AIR application based on TringMes standards based APIs. Given the powerful functionality of Adobe Flash and the ease of use of TringMes APIs, developers will be able to produce compelling voice enabled apps using Adobes Flash, Flex or

TringMe Flash & REST API

Page 4

AIR technologies. For example, developers can create a fully-functional desktop phone on top of TringMe APIs using Adobe AIR technology. While TringMes REST API can meet most application requirements, more advanced application can be developed using VoicePHP (http://voicephp.com), TringMes advanced platform. This document is divided into two parts. First part describes the REST API which will allow users to configure and access the TringSwitch. The second part focuses on creating your own Flash widget using Adobe Flash, Flex or AIR.

TringMe Flash & REST API

Page 5

2 REST API
The TringMe API uses a REST-based interface. TringMe API calls are made over the internet by sending HTTP GET or POST requests to our server. For example, to get the TringMe user id, following URL should be constructed. http://login.tringme.com/api.php?apikey=12sdas8dadadsadajs3&sig=4b61af9cd869706edc6a4569fc4e7 b33&op=getuid&email=api@anexample.com You will require API keys in order to use TringMe API. To obtain API keys, send your request to a special email address support@tringme.com along with your TringMe user ID. API keys are available in a pair, public and private keys. To access the TringMe API, you should pass your public API key, operation code and signature of the request to the TringMes API server. Depending on requested operation, you will also need to pass one or more required parameters. All API request must include checksum signature using private key to avoid any tempering of the request. Note that, you MUST NOT include your private key for any transaction.

2.1 SSL Support


TringMe supports strong encryption. TringMe API is also accessible over https connection using the same URL (https://login.tringme.com/api.php).

2.2 API Parameters


Following sections describe various API parameters. 2.2.1 Mandatory Parameters Parameter Description Signature sig Public API Key apikey Operation (see operation table) op

2.2.2 Operation Table Operation createuser

Description Create User

Input Parameters email name pw private

Description Email address Name (Optional) Password (Optional) Create Private user (Optional) If this parameter is specified, user will be created in API users private space.

TringMe Flash & REST API

Page 6

autoactivation

activateuser

Activate the user Applicable only if user was created using cuser and optional password parameter. Re-send the activation e-mail to user. Applicable only if user was created using cuser and optional password parameter. Login a user

email activationcode

Default 0 (off) Create user without any activation code or email verification. This flag is applicable only for creating private users. Email address Activation Code which was sent to user to users email address

reactivateuser

email

Email address

login

email pw private

gettempcookie

Get Temporary Cookie

cookie

Email address Password Private User Login (Optional). This parameter should only be set if the user was created (createuser) with the private parameter set. Cookie (obtained using login) (optional) If cookie is omitted, the subsequent call will be placed from API holders account. If cookie is passed , the call will be placed from the users account whose credentials were passed to obtain cookie (Using login )

dest

Destination (Optional) If specified, the

TringMe Flash & REST API

Page 7

validity

temporary cookie can be used to call specified destination only Validity in minutes (Options) Default 3 minutes Maximum number of call attempts (Optional) 0 For unlimited. Default 1 Cookie (obtained using login). Cookie (obtained using login) Name (Optional) Users Gtalk ID (Optional) Users phone number with country code (Optional) Users SIP destination (Optional) DTMF string 19*# w Delay 500ms Where user will be connected when pushn-talk widget is pressed (Optional) 0 = Phone 1 = Gtalk 2 = Offline 3 = SIP URI 4 = SIP/VoIP acct (see sipproxy) 5 = MobileVoIP SIP Proxy Server (optional) NULL to delete SIP profile. Below SIP parameters

maxusage

logout setuser

Logout the user Set User Profile

cookie cookie

All parameters are name optional except gtalk cookie. Do not pass parameters which you phone do not intend to change. sipid dtmf

connectto

sipproxy

TringMe Flash & REST API

Page 8

sipuser sipauth sippass getuid Get Users UID email

are only applicable along with sipproxy SIP Username (optional) SIP Auth Name (optional) SIP Password (optional) Get user UID from email

click2call

Click 2 Call c2c will create a callback between two parties. It will call callsrc and then call destination and then bridge both the calls (similar to any other click2call If cookie is omitted, the call will be placed from API holders account. If cookie is present, the call will be placed from a users account whose credentials were passed to obtain cookie (Using login )

cookie

Cookie (obtained using login) (optional) If cookie is omitted, the call will be placed from API holders account. If cookie is present, the call will be placed from a users account whose credentials were passed to obtain cookie (Using login )

callsrc

calldest

First party phone number (optional). Call will be first placed to this number. If the call is not answered, the API will terminate. Second party phone number. (optional) Destination, can be any phone number, TringMes registered email address, any valid SIP/IMS URI. Destination is optional if greeting is specified so as to enable call and play a message functionality User supplied parameter to associate Page 9

calltag

TringMe Flash & REST API

a call in the Call Data Records. (optional) calltag should be alphanumeric only (a-z, A-Z, 0-9), and all other characters will be replaced by 'X' You must specifiy calltag when notifyurl is specified. If not, notifyurl will not be invoked. Specifies the duration after which the call should automatically disconnect. (optional) The duration is the timeframe from the moment callsrc is answered till the time when the call disconnects URL of the wave file which will be played immediately after callsrc answers. (optional) wav file should be [8KHz sampled, 16 bit linear, mono, uncompressed] URL of the wave file which will be played before disconnecting the call. (optional) wav file should be [8KHz sampled, 16 bit linear, mono, uncompressed] Maximum number of DTMF digits expected to enter by user after playing greeting. Page 10

duration

greeting'

postcallgreeting

dtmfmaxdigits

TringMe Flash & REST API

(optional) Default 0 Number of times DTMF entry will be retried. (optional) Default 1 Valid only if dtmfmaxdigits > 0 and greeting specified. DTMF timeout in seconds. (optional) Default 10 seconds. Valid only if dtmfmaxdigits > 0 and greeting specified. Call status notification URL. (optional) For details, refer to section titled Call Status Notifications in REST API This specifies a flag that controls the type of notifications to receive on notifyurl. (optional) Default value is 1 0 Do not Invoke the notifyurl except for DTMF input. 1 Termination Status Codes (e.g. COMPLETED ) 2 Call Progress Status Codes (e.g. SRCANSWRED) 3 Combination of 1 and 2 above.

dtmfretries

dtmftimeout

notifyurl

flag

TringMe Flash & REST API

Page 11

For details, refer to section titled Call Status Notifications in REST API token Security token (optional ) For details, refer to section titled Notification Security getcdr Get Call Data Records (CDR) cookie Cookie (obtained using login) Obtain CDR having identifier > id (Optional) Obtain CDR for date > startdate (Optional) Obtain CDR for date < enddate (Optional) Obtain CDR having tag = calltag (Optional) Cookie (obtained using login)

id

Returns XML with CDR information

startdate enddate calltag

getvoicemail

Get Voicemail Returns XML with voicemail information

cookie

deletevoicemail

Delete Voicemail

cookie

Cookie (obtained using login) VM ID specified in XML obtained using getvm Cookie (obtained using login) Cookie (obtained using login) USD Amount to be transferred.

vmid deleteallvoicemails Delete All Voicemails cookie

setphonecredits

Transfer phone cookie credits (USD) from API account to users account. amount If successful, returns transaction reference number in response. Reverse Transaction

reversetransaction

ref

Transaction reference number obtained in Page 12

TringMe Flash & REST API

If successful, returns amount reversed in response. Note that depending on usage, full amount may or may not be refunded. *THIS OPERATION IS CURRENTLY UNDER REVISON TEMPORARILY NOT AVAILABLE Get Current Phone Credit Balance If cookie is omitted, it will return the phone credits balance (USD) of the API account else balance of the users account Get rate for voice call or SMS

operation setphonecredits

getphonecredits

cookie

Cookie (obtained using login) (Optional)

getrate

dest type

sendsms

Send a SMS to worldwide destinations

cookie

Destination Phone Number 0 = Phone (Default) 1 = SMS Cookie (obtained using login) (optional) If cookie is omitted, the SMS will be sent from API holders account. If cookie is present, the SMS will be sent from a users account whose credentials were passed to obtain cookie (Using login )

dest msg fromtype

Destination Phone Number Message (HTTP URL Encoded) Selects the senders Phone number in SMS 0 = Use users

TringMe Flash & REST API

Page 13

authorized phone number. If Empty, use API Providers authorized phone number (default) 1 = Use API Providers authorized phone number cuser, suser, gcookie, getvm, dvm, dvmall, c2c operations have been deprecated. They are still supported, but we recommend using the new equivalent operations mentioned above. 2.2.3 Results API response is indicated by OK or Fail condition. Success will be indicated by following output: OK [<value>] value will be operation specific and optional. Failure will be indicated by one of the values tabulated below: Result FAIL NOKEY NOSIG NOOP BADSIG INVALIDKEY INSUFFICIENTCREDITS INVALIDDEST MISSINGPARA USEREXIST AUTHFAIL NOTLOGGEDIN TOOMANYCOOKIES Description Operation Failed (however API key, signature etc were okay) Missing Key Missing Signature Missing Operation Bad Signature Invalid API Key Insufficient Credits Invalid Destination Missing parameters User already exists Authorization Fail or Session Expired/Invalid cookie (get new cookie) Login Required User obtained too many temporary cookies

You should ignore any line in response starting with #

2.3 Calling API


If you are using PHP, TringMe API source includes all the code necessary to call and execute desired API function. All you have to do is to create an array with parameters and call API function. // complete php code to create your own click to call service // http://blog.tringme.com/roll-out-your-own-click-to-call-service/ TringMe Flash & REST API Page 14

<?php include_once (tringmeapi.php); $publickey = yourpublicapikey; $privatekey = yourprivateapikey; $parameters=array(); $parameters[op]=click2call; $parameters[apikey]=$publickey; $parameters[callsrc]=18585551111; $parameters[calldest]=18585552222; $response = TringMeAPI($parameters, $privatekey); ?>

If you are not using PHP and like to use TringMe API, you need to generate signature and API URL and use appropriate library (e.g. libcurl) to invoke the API using URL. In above code, all mentioned functionalities are handled by function TringMeAPI. Below is description of how you can generate signature and API URL manually. 2.3.1 Generating Signature Signature is generated by concentrating all the parameters in HTTP REQUEST ($_GET or $_POST field in php) , private key and taking md5 of it. Example php code: // sample php code to compute the signature $parameters = array(); $parameters ['op'] = 'login'; $parameters ['apikey'] = $publickey; $parameters ['email'] = 'api@anexample.com'; $parameters ['pw'] = 'somepw'; $sig = GetSignature($parameters , $privatekey); function GetSignature($params_array, $private) { $str = ''; ksort($params_array); foreach ($params_array as $key=>$val) { $str .= "$key=$val"; } $str .= $private; return md5($str); } 2.3.2 Generating API URL Example php code: TringMe Flash & REST API Page 15

// sample php code to generate URL $parameters = array(); $parameters ['op'] = 'login'; $parameters ['apikey'] = $publickey; $parameters ['email'] = 'api@anexample.com'; $parameters ['pw'] = 'somepw'; $sig = GetSignature($parameters , $privatekey); $url = CreateAPIURL($parameters, $sig); function CreateAPIURL($params_array, $signature) { $uri='http://tringme.com/api.php?'; foreach ($params_array as $key=>$val) { $uri .= "$key=$val&"; } $uri .= "sig=$signature"; return $uri; }

2.4 Debugging
An additional parameter debug with value 1 can be passed in all the operations to get dump of the parameters received by TringMe API server. You can access the dump at the following location http://login.tringme.com/apidebug/<publickey>.txt To delete the debug logs, pass parameter debug with value 2.

2.5 Call Status Notifications in REST API


Live call status notification can be received by specifying the notification URL in notifyurl parameter and call tag in calltag parameter. The notification URL will be invoked with following parameters.

2.5.1 Notification Parameters Parameter Value tm f

Description This is a identification field and will be populated with the value tm. Status could be: SRCFAILED Source call leg failed SRCNOTANSWERING Source call leg not answering SRCANSWERED - Source call leg answered SRCCANCELED - Source disconnected the call

Status

TringMe Flash & REST API

Page 16

calltag sig r d p

Calltag Signature Random Number Duration Parameters

(before destination was connected) DESTNOTANSWERED - Destination not answering DESTCONGESTED - Destination could not be connected due to congestion. DESTNETWORKERROR DESTCONGESTED Destination could not be connected due to destination network error. USERDTMFINPUT DTMF value COMPLETED Call completed successfully Call tag passed during API invocation. Hash Signature Random Number Call Duration in Seconds. 0 if call was unsuccessful. Parameters specific to the type of Status. For USERDTMPINPUT it contains the DTMF input digits. No other Status has any parameters.

2.5.2 Notification Security TringMe invoked the notification URL with MD5 signature and a random number. You can calculate the signature locally to verify the authenticity of invoker. MD5 signature is calculated by concatenating random number, call tag and a secret token. Token can be passed during invocation of API. If not passed, private key will be used as the token. An empty token can be passed to disable the signature. 2.5.2.1 Reverse DNS Lookup Alternatively, you can do a reverse DNS lookup for the IP address to verify that it is from TringMe.

3 PHP Helper Functions


For convenience of PHP developers, we have released helper PHP functions for most of the commonly used operations. Helper functions are bundled together in the sample source code available at http://tringme.com/samples.html. If helper function are used, the above Click 2 Call sample code reduces to: // TringMe Click 2 Call using helper function <?php include_once (tringmehelper.php); $publickey = yourpublicapikey; $privatekey = yourprivateapikey;

TringMe Flash & REST API

Page 17

$response = TringMeClick2Call($privatekey, $publickey, $callsrc ,$calldest); ?>

4 Using Existing TringMe Flash Widgets


4.1 Embedding TringPhone widget
TringPhone is a Flash widget and can be embedded into your website like any other flash file (.swf) file. TringPhone takes cookie as a parameter to identify the user making outgoing calls. Use gcookie API to obtain the cookie. Following are the details of flash object: URL: http://tringme.com/tringphone.swf?uid=<cookie> Width: 280 Height: 400 majorversion: "6" wmode: "transparent"

4.2 Embedding Push-n-talk widget


TringMe Push-n-talk is a Flash widget and can be embedded into your website like any other flash file (.swf) file. There are two types of push-n-talk widgets: 1.> A widget to make a call. 2.> A widget to leave a voicemail. Push-n-talk takes following parameters:

Parameter uid username wtype

tmlink ctxt

Description UID of the User Name to be displayed on Widget Widget Type 0 Voicemail (default) 1 - Phone Type of TringMe Link to be displayed below the widget (0 or 1) Call Text - Replaces default call text on the widget. Default Click to Call or Click to leave Voicemail For Localization & customization. Hangup Text - Replaces default hangup text on the widget. Call Termination Text Replaces default call Page 18

htxt ttxt TringMe Flash & REST API

termination text on the widget

Widget URL: http://tringme.com/tringme2.swf?uid=<uid>&username=<name>&wtype=<0> Width: 215 Height: 138 majorversion: "6" wmode: "transparent" TringMe provides an alternate way of accessing the same using more browser friendly code: 4.2.1.1 Push-n-talk voicemail code <div id="tringmevm"> <script type="text/javascript" src="widget.php?uid=123234412202&username=somename&wtype=0"> </script> </div>

4.2.1.2 Push-n-talk phone <div id="tringmeph"> <script type="text/javascript" src="widget.php?uid=123234412202&username=somename&wtype=1"> </script> </div>

Accessing Voicemails
Voicemails are accessible through a XML file which can be obtained using getvm operation. The file format of XML is self explanatory.

5 Developing your own Flash Telephony Widgets


TringMe uses standard NetStream and NetConnection interfaces which have been available since Flash 7. This allows even an inexperienced flash developer to develop new widgets by writing few lines of code. Since NetConnection and NetStream are widely used and tons of documentation and help already are available on the web, readers are requested to refer those resources and we will not cover it here. Instead, the following gives the steps and specifications for making a call using TringMe. For exact usage, refer to TringMe widget source code.

5.1 Making Call


Making a Call is as simple as:

TringMe Flash & REST API

Page 19

1) Create Flash NetConnection object 2) Two NetStream Objects (A & B) attached them to NetConnection 3) Create Microphone Object and attach it to a NetStream A 4) Publish NetStream A 5) Play NetStream B Complete working source code of a minimal phone widget is below. //Create NetConnection and connect nc = new NetConnection(); // handle async notification and failures nc.onStatus = ConnectStatus; nc.connect(TringSwitchURI); //Create NetStream A and attach it with Microphone nsA = new NetStream(nc); mic = Microphone.get(); mic.setRate(8); mic.setSilenceLevel(0); nsA.attachAudio(mic); nsA.publish(randomstreamname, "record"); // Create NetStream B and play nsB = new NetStream(nc); nsB.play("tring", -1);

5.2 NetConnection targetURI Specification


TringSwitch supports calling a user by their UID or by dialing a destination (phone number, email, SIP URI etc). Hence the following rtmp URIs are supported. To call a user by their UID (e.g. in case of push-n-talk type of applications), use the following URI string: rtmp://sip.tringme.com/call/<uid> or rtmp://sip.tringme.com/call/<uid>[/<dtmf>][/<calltag>]

TringMe Flash & REST API

Page 20

To reach a users voicemail by their UID (e.g. in case of leave a voicemail type of applications), use the following URI string: rtmp://sip.tringme.com/voicemail/<uid> To make a worldwide phone call, or call to SIP URI or TringMes registered email address, the URI string should be formatted as below: rtmp://sip.tringme.com/sip/<cookie>/<destination> or rtmp://sip.tringme.com/sip/<cookie>/<destination>[/<calltag>][/<callerid>] uid and cookie are as obtained from login, gettempcookie or getuid API. calltag [Optional] - User supplied parameter to associate a call in the Call Data Records (obtained by getcdr). calltag is alphanumeric only (a-z, A-Z, 0-9), and all other characters will be replaced by 'X'. callerid [Optional] Caller ID [Requires special activation due to the privacy & security issues contact bizdev@tringme.com ]

5.3 Ending Call


To end the call, close NetStream by calling close method. // close stream A, it optional to close stream B as it will be automatically closed by TringSwitch nsA.close();

If the call is terminated by called party, TringSwitch will close the connection. Notification will be posted to onStatus handler of class NetConnection function ConnectStatus( pInfo:Object ) { if ( pInfo.code == "NetConnection.Connect.Success" ) { // do something to indicate successful connection with TringSwitch } else if ( pInfo.code == "NetConnection.Connect.Closed" || pInfo.code == "NetConnection.Connect.Rejected" ) { // close streams and clean up

TringMe Flash & REST API

Page 21

} }

For any questions or comments, send a mail to support@tringme.com

5.4 Call Status Notifications in Flash


To receive call status notification, register a status handler as shown below. Currently only following status notifications are supported: TringMe.Status.00200 Call Connected Status //Create NetConnection and connect nc = new NetConnection(); // handle async notification and failures nc.onStatus = ConnectStatus; nc.connect(TringSwitchURI); //Create NetStream A and attach it with Microphone nsA = new NetStream(nc); mic = Microphone.get(); mic.setRate(8); mic.setSilenceLevel(0); nsA.attachAudio(mic); nsA.publish(randomstreamname, "record"); // Create NetStream B and play nsB = new NetStream(nc); nsB.onStatus = NSOnStatusHandler; nsB.play("tring", -1); // Declare the OnStatus handler for receiving status updates. // It should be registered as shown below NSOnStatusHandler = function (info:Object) { trace(info.code);

TringMe Flash & REST API

Page 22

if(info.code == "TringMe.Status.00200") { // Call is connected } }

TringMe Flash & REST API

Page 23

Vous aimerez peut-être aussi