Whispir API Callbacks

Whispir API Callbacks

API Callbacks enable developers to reduce the heavy lifting required by their apps by utilising the simplicity of a callback server.  Keep reading to find out more. We recommend reading the Messaging section prior to taking on API Callbacks.

  1. What are API Callbacks?
  2. Structure of an API Callback
  3. Building your Callback Server
  4. Configuring Whispir to use your Callback Server
  5. Using the Callback ID in your API message
  6. Adding Authentication to your Callback Server
  7. Get notified of Callback failures

What are API Callbacks?

Firstly it might be easier to describe the flow of a message from the Whispir API.

  1. The user requests the API to send out a message to a group of recipients
  2. Whispir receives this message request, and adds it to a queue to be processed 
  3. Whispir then responds to the user with an HTTP 202 Accepted (e.g. I've got the message, I'll be sure to process that in just a bit)

    In this response, Whispir also provides the user with a Message ID reference that can be used to look up this message and query some more information.

    Next, what happens is Whispir sends out the message to the intended recipients.  This happens nearly instantly, but it is important to know that it is a queued and asynchronous process.
  1. After the message has been sent out, the recipients of the message will begin sending in replies.

These replies are automatically stored in Whispir, and notifications are sent out to the User who initiated the message.

But what if we want these replies to come back to an application that we have developed?  This is where callbacks are useful.

Whispir Callback Flow

Whispir can forward the content of each reply, and some associated metadata to a URL that the user has registered to receive this information.  Each reply to a message will cause this URL to be invoked and the information sent.  This allows users applications to automatically be notified about messages that they are sending, without the need to poll!

The sections that follow describe how to set up a callback URL in Whispir, then use it within your messaging API calls.

Structure of an API Callback

Each API callback can be returned to your application as JSON or XML.

XML Example

HTTP 1.1 POST http://yourserver/callback.php
Content-Type: application/xml

<ns2:deliveryresponse xmlns:ns2="http://schemas.api.whispir.com">
    <messageid>ABC4857BCCF484575FCA</messageid>
    <location>https://api.whispir.com/workspaces/FDD8348CBBED939FCAC/messages/ABC4857BCCF484575FCA</location>   
    <from>
        <name>Fred Waters</name> 
        <mri>Fred_Waters.528798.Sandbox@Contact.whispir.com</mri> 
        <mobile>0430984567</mobile> 
        <email>imacros@test.com</email> 
        <voice>0761881564</voice> 
    </from> 
    <responsemessage> 
        <channel>SMS</channel> 
        <acknowledged>09/01/13 13:22</acknowledged> 
        <content>Yes, I accept. Will I need to bring steel cap boots?</content> 
    </responsemessage> 
</ns2:deliveryresponse>

JSON Example

HTTP 1.1 POST http://yourserver/callback.php
Content-Type: application/json
{
    "messageId":"ABC4857BCCF484575FCA",
    "location" : "https://api.whispir.com/workspaces/FDD8348CBBED939FCAC/messages/ABC4857BCCF484575FCA",
    "from":{
          "name":"Fred Waters",
          "mri":"Fred_Waters.528798.Sandbox@Contact.whispir.com",
          "mobile":"0430984567",
          "email":"imacros@test.com",
          "voice":"0761881564"
         },
    "responseMessage":{
           "channel":"SMS",
           "acknowledged":"09/01/13 13:22",
           "content":"Yes, I accept. Will I need to bring steel cap boots?"
    }
}

Your application will receive a payload as demonstrated for each response returned to the message you've sent.

Now that you can see the content of a callback, you can move to build the server to receive these.

Building your callback server

There are lots of different ways, and lots of different languages that you can use for your callback server.  These are most likely to be server side scripts (such as PHP, Python or Perl), but advanced languages such as Java or .Net can also just as easily be used.

In the examples that follow, We'll be using PHP 5.3 to demonstrate how to create a callback server.

The simplest example will just take the received content payload, and write this to a text file. E.g.

 

<?php

   /*
    * Author: Jordan Walsh
    * Description: Callback Server that supports JSON POSTs and writes the 
    *              content to a file called responses.txt in the same directory.
    *
    */        
  
   header("HTTP/1.0 200 OK");

   $text = "";
   $obj = "";

   //Get the body of the POST Message (the reply)
   $json = file_get_contents('php://input');
   
   if( $json != false ) {  
   
      //Decode the JSON object
      $obj = json_decode($json);
      
      //Get the ResponseMessage from the JSON object
      $responseMessage = $obj->{'responseMessage'};
      
      //Get the content of the response
      $text = $responseMessage->{'content'};
      
      //Write the content to a file
      writeFile($text);
   } else {
      writeFile('Request received.  JSON object is empty.');
   }

   function writeFile($text) {
      file_put_contents("responses.txt", $text, FILE_APPEND);
   }

?>

 

If you host this file on a server that supports php and run it, you can expect the output to be:

"Request received. JSON object is empty".

However, if you were to use your REST Client (see Quick Start Guide) and POST some content to this, the output in the text file would be the posted content.

Now we've got our callback server, we can configure Whispir to use it and send out our message.

Configuring Whispir to use your Callback Server

Before you can send any messages and have the responses routed, you need to tell Whispir where to route the information.

Open your browser and browse to http://www.whispir.com.  Click the Sign-In button at the top of the screen, and log into Whispir using your credentials.

Browse to 'Admin -> Company Settings -> API -> Register a Callback URL'.

Callback URL Setup

 

In this form you need to provide the following information:

  1. A unique name for your callback.  This name will be referenced in your API message requests.
  2. The Destination URL to your server e.g. http://myserver.mycompany.com/whispir/callback.php (this must be publicly accessible)
  3. If you have authorization required you can add this here (we will add this to our server shortly)
  4. The type of authorization you have set up (Query String, or HTTP Header)
  5. The Content Type to be POSTed to your application (XML or JSON).
  6. An email address for where any callback failure notifications should be sent to.

Click Test URL to ensure your URL is valid, then click Add to store this in Whispir.

Callback Register Success

Using the Callback ID in your API message

When sending messages using the Whispir API, you can now add the ID of the callback server in your message content.  Any replies to this message will automatically be forwarded back to the associated server for processing.

The following examples show how you can use your server above to receive responses in JSON.

XML Example

HTTP 1.1 POST http://api.whispir.com/messages?apikey=<yourkey>
Authorization: Basic am9obi5zbWl0aDpteXBhc3N3b3Jk
Content-Type: application/vnd.whispir.message-v1+xml

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns2:message xmlns:ns2="http://schemas.api.whispir.com">
    <to>61400000000</to>
    <subject>Test SMS Message</subject>    
    <body>This is the body of my test SMS message</body>
    <callbackId>JSON Callback</callbackId>
</ns2:message> 

 

JSON Example

HTTP 1.1 POST http://api.whispir.com/messages?apikey=<yourkey>
Authorization: Basic am9obi5zbWl0aDpteXBhc3N3b3Jk
Content-Type: application/vnd.whispir.message-v1+json

{
   "to" : "61400000000",
   "subject" : "Test SMS Message",
   "body" : "This is the body of my test SMS message",
   "callbackId" : "JSON Callback"
}

Sending this request will send out this message.  Any responses to this message will be forwarded back to the Callback Server script and written to the text file.

Easy as that! Now you no longer need to poll Whispir to retrieve responses to your messages, Whispir will automatically forward them directly to your application for processing.

Adding Authentication to your Callback Server

Whispir Callbacks have been designed to be simple, yet secure.  In order to make your Callback Server safer, it is suggested that you generate a token that Whispir should send to you with each request.  This way you can confirm that the request has come from the Whispir Platform based on the presence of the token.

First, you'll need to edit your Callback URL configuration within the Whispir Platform to begin sending this new parameter.

Browse to 'Admin -> Company Settings -> API -> Register a Callback URL'.  

In this screen you can enter your desired Authentication Key/Token in the Auth Parameter field provided.

Callback Setup with Auth

Users have two choices with the Authorization Type:

Query Parameter

The Authorization will be passed to the callback server on the query string using an 'Auth' parameter as follows:

HTTP 1.1 POST http://yourserver/callback.php?auth=234023490349034
Content-Type: application/xml

<ns2:deliveryresponse xmlns:ns2="http://schemas.api.whispir.com">
    <messageid>ABC4857BCCF484575FCA</messageid>
    <location>https://api.whispir.com/workspaces/FDD8348CBBED939FCAC/messages/ABC4857BCCF484575FCA</location>   
    <from>
        <name>Fred Waters</name> 
        <mri>Fred_Waters.528798.Sandbox@Contact.whispir.com</mri> 
        <mobile>0430984567</mobile> 
        <email>imacros@test.com</email> 
        <voice>0761881564</voice> 
    </from> 
    <responsemessage> 
        <channel>SMS</channel> 
        <acknowledged>09/01/13 13:22</acknowledged> 
        <content>Yes, I accept. Will I need to bring steel cap boots?</content> 
    </responsemessage> 
</ns2:deliveryresponse>

It is the responsibility of the receiving script to parse this query string parameter and check against the internal application. 

This method should only be used over HTTPS with other means of Auth including IP whitelisting as it is susceptable to packet sniffing and man-in-the-middle attacks.

 

HTTP Header

Using an HTTP Header for authorisation is the preferred approach.  Instead of using a query string parameter, this will use a custom HTTP Header X-Whispir-Callback-Key:

HTTP 1.1 POST http://yourserver/callback.php
Content-Type: application/xml
X-Whispir-Callback-Key: 234023490349034 

<ns2:deliveryresponse xmlns:ns2="http://schemas.api.whispir.com">
    <messageid>ABC4857BCCF484575FCA</messageid>
    <location>https://api.whispir.com/workspaces/FDD8348CBBED939FCAC/messages/ABC4857BCCF484575FCA</location>   
    <from>
        <name>Fred Waters</name> 
        <mri>Fred_Waters.528798.Sandbox@Contact.whispir.com</mri> 
        <mobile>0430984567</mobile> 
        <email>imacros@test.com</email> 
        <voice>0761881564</voice> 
    </from> 
    <responsemessage> 
        <channel>SMS</channel> 
        <acknowledged>09/01/13 13:22</acknowledged> 
        <content>Yes, I accept. Will I need to bring steel cap boots?</content> 
    </responsemessage> 
</ns2:deliveryresponse>


Once you have saved this information, you can update your callback server to look for this value. 

See the updated callback server code here.

<?php

   /*
    * Author: Jordan Walsh
    * Description: Callback Server that supports JSON POSTs and writes the 
    *              content to a file called responses.txt in the same directory.
    * Updates: 
    * 2013-02-19 - Added support for Authentication.
    */        
  
   header("HTTP/1.1 200 OK");

   $text = "";
   $obj = "";
   $query = "";
   $auth = "";
   
   $query = $_SERVER['QUERY_STRING'];
   
   if( "$query" != "" ) {
   
      //GET the auth variable off the query string
      $auth = $_GET["auth"];
      
      if ( "$auth" != "234023490349034" ) {
         writeFile("Authentication failed. Auth = $auth");
      } else {
         //Auth is correct so continue processing
         
         //Get the body of the POST Message (the reply)
         $json = file_get_contents('php://input');
         
         if( $json != false ) {  
            //Decode the JSON object
            $obj = json_decode($json);
           
            //Get the ResponseMessage from the JSON object
            $responseMessage = $obj->{'responseMessage'};
           
            //Get the content of the response
            $text = $responseMessage->{'content'};
           
            //Write the content to a file
            writeFile($text);
         } else {
           writeFile('Request received.  JSON object is empty.');
         }
      }
   } else {
      writeFile('Callback Received.  Querystring not defined.');
   }

   function writeFile($text) {
      file_put_contents("responses.txt", $text, FILE_APPEND);
   }

?>

 

This code now checks for the presence of our 'auth' parameter on the URL.  Once this is present and correct, the script will run as before.  If the auth parameter is not there, or it is incorrect, we simply write the information to the file and move on.

For more information on how to use authentication in your callbacks, please send an email to apisupport@whispir.com and we'll be glad to give you a hand.

Get notified of callback failures

Users can now be automatically notified via Email in the event an API Callback has not processed as expected.

Whispir will automatically send an email in the following circumstances:

  1. If the Callback Server returns anything other than an HTTP 200 OK.
  2. If the authorization to the Callback Server fails (e.g. returns an HTTP 400 level error) 
  3. If the Callback Server does not connect within 5 seconds.
  4. If the Callback Server does not return a response within 60 seconds.

In any of these events, Whispir will send an email that resembles the following:

 Dear Customer,  

 Your callback <callback_id> failed on <date> with response: <response>.  

 The callback that failed is as follows:  

 URL: http://yourserver/callback.php?auth=12345 
 Location: https://api.whispir.com/messages/ABC4857BCCF484575FCA 
 Name: Fred Waters 
 Mobile: 0430984567 
 Email: imacros@test.com 
 Channel: SMS 
 Content: Yes, I accept. Will I need to bring steel cap boots? 
 
 Please take the necessary steps to ensure your callback is configured correctly.  

 If this callback URL continues to fail, Whispir may remove this until the service is resolved. 

 Regards, 

 Whispir Support

 

In order to set up this email for your callbacks, you must log into the Whispir Platform, and browse to the 'Register a Callback URL' section.  

You can edit your existing callback, and set the 'Notify of errors' section with the appropriate email.

 

Callback Setup with Auth

 

For more information on these notifications, please send an email to apisupport@whispir.com and we'll be glad to give you a hand.