04 November 2012

Using Twilio to send an SMS and get status feedback using PHP

I've been playing with Twilio for a while now. Twilio is an API that allows you to send and receive SMS messages and telephone calls.

Now that I've reserected the project, I have re-coded all the Twilio code, using the lastest php library. They have brought out many helper libraries to use with your favorite code. http://www.twilio.com/docs/libraries

I'm using the Official PHP Twilio REST API and TwiML library php code to send an SMS. It was super easy to send an SMS but to get the status of the SMS was always a mystery to me, so I started to experiment a bit with the code. In the end I have code that sends out a single SMS (Multiple user SMS code is available on the Twilio website at http://www.twilio.com/docs/quickstart/php/sms/sending-via-rest

There are two parts to the code. The page to send the SMS, sms_send.php, and a separate page to read the SMS status feedback, sms_callback.php.

sms_send.php



$sms_message = "Test SMS with feedback status";

// Install the library via PEAR or download the .zip file to your project folder.
// This line loads the library
require('twilio/Twilio.php');

$sid = "AC25xxxxxxxxxxxxxxxxxxxx";  // Enter your own AccountSid here
$token = "xxxxxxxxxxxxxxxxxxxxxxx";  // Enter your own AuthToken here

$client = new Services_Twilio($sid, $token);
$message = $client->account->sms_messages->create( '+1xxxxxxxxxx', // From a valid Twilio number '+278xxxxxxxx', // Text this number $sms_message, array('StatusCallback' => 'http:///sms_callback.php')); $sms_id = $message->sid;print $sms_id . "
";



?>

You need to add the standard html headers and coding etc


Here is the complete callback file. You can add code to update the database or to send you an SMS when the status of a sent SMS is updated.



session_start();

error_reporting(0);


$SmsSid      = sanitiseString($_POST['SmsSid']);
$SmsStatus   = sanitiseString($_POST['SmsStatus']);

// Add your code here to process the information received here...

?>


No comments:

Post a Comment