Refreshing twilio token programmatically
Sibin John
February 25, 2015
Twilio Client uses capability tokens to establish communications between devices to Twilio. Capability tokens allow you to add Twilio capabilities to web and mobile applications.
Allowing incoming and outgoing capability to a twilio client
You create a token on your server and specify what capabilities you’d like your device to have. Here is the code for creating capability token with your twilio credentials (ie. Accountsid and AuthToken). Also download the twilio library from https://github.com/twilio/twilio-php/archive/master.zip and move the twilio-php folder to your project directory and then include the library file, (using php)
require '/path/to/twilio-php/Services/Twilio.php'; require '/path/to/twilio-php/Services/Twilio/Capability.php'; $token = new Services_Twilio_Capability(‘Account sid’, ‘AuthToken’); $token->allowClientOutgoing(‘Appsid’); //enter Appsid of twilio app $token->allowClientIncoming(‘client name’); // enter client name
Generate tokens
A token can be generated, (using js )
Twilio.Device.setup("<?php echo $token->generateToken();?>");
using php,
$token_name = $token->generateToken();
Life time of tokens and need for refreshing
All tokens have a limited lifetime to protect you from abuse. The lifetime is configurable up to 24 hours. By default, this token will expire in one hour. If you’d like to change the token expiration time,generateToken takes an optional argument which specifies time to live in seconds.
in js:
Twilio.Device.setup("<?php echo $token->generateToken(600);?>");//This token will now expire in 10 mins
in php:
$token_name = $token->generateToken(600); //This token will now expire in 10 mins
If you are creating applications that requires the twilio client to be online all the time, then this tokens must be refreshed after they expired.
For example, web twilio is one of my application that refreshes twilio token every 10 hours. I used the following simple technique to refresh the twilio token,
Twilio.Device.setup("<?php echo $token->generateToken();?>"); setTimeout(function() { location.reload();//reload page every 10hrs to refresh twilio token }, 36000000); // 36000000 milliseconds = 10 hours
One disadvantage of this method is that any call in progress, at the time of refreshing page, may be lost. If you want to avoid this problem generate another token in the timeout function.
Leave a Reply