Accessing Web Services From CCXML

This is the first in a series of posts that will highlight how to accomplish specific things using the Voxeo Prophecy platform. All of the examples that will be discussed draw directly from the GreenPhone project discussed in a previous post.

The first issue that will be discussed – accessing web services from CCXML using PHP.

One of the very cool things about Prophecy is that it comes bundled with the PHP scripting language. In fact, I have on occasion referred to PHP as Prophecy’s “embedded scripting language.” PHP 5 comes with an abundance of features that will be of interest to IVR developers – chief among them, the ability to create SOAP clients to interact with web services, and the ability to easily work with data in XML format using the SimpleXML extension.

If you’ve read my previous post on the GreenPhone Project, you will know that I am using a collection of web services from StrikeIron that includes a web service to provide information on U.S. area codes. If we pass this web service an area code, it will return the U.S. state that area code is in. Ultimately, what the GreenPhone application will do is look up E85 and bio-diesel stations by state. So when a person calls the application, we want to use their area code to look up what state they are in – thereby saving them the trouble of entering this information manually.

In CCXML, we can access the caller’s ANI via the Connection Object:

<transition state="initial" event="connection.alerting">
 <log expr="'*** Call is coming in. Lookup area code information. ***'"/>
 <assign name="ani" expr="event$.connection.remote"/>
 <assign name="areacode" expr="ani.substring(0,3)"/>
 <send target="'php/areaCodeLookup.php'" name="'lookupEvent'" targettype="'basichttp'" namelist="areacode"/>
</transition>

This block of code show how to set up a transition to access the ANI on an incoming call. When an incoming call is detected by Prophecy, the “connection.alerting” event is delivered and we have access to the Connection Object’s “remote” property – this property exposes the telephone URL for the device that is calling into the platform. Note – in my previous post, I explained the process of setting up the Prophecy SIP phone to deliver a specific ANI. This is how we access the value that is set in the Prophcy SIP phone.

We assign the ANI value to a variable we have previously declared and (very cleverly) called “ani”, and then we grab the first 3 characters of this string (using the ECMAScript substring method) and assign them to another variable called “areacode”. We then pass the area code value to a PHP script that will interact with the StrikeIron area code web service.

Using the CCXML <send/> element in this fashion is identical to an HTTP GET with the areacode variable appended to the URL of the PHP script, like this:

http://myserver/php/areaCodeLookup.php?areacode=123

There several possible outcomes of this HTTP request:

  1. Our PHP script was able to successfully interact with the StrikeIron web service and lookup the U.S. state information for the submitted area code;
  2. Our PHP script was able to successfully interact with the StrikeIron web service but was not able to lookup the state information for the submitted area code (bad area code);
  3. Something went wrong (an exception occurred) while trying to interact with the web service; or,
  4. Something really went wrong and our HTTP request resulted in a bad response from the server.

We need to set up handlers for each possible outcome – we won’t discuss them in detail until after we look more closely at the PHP components that are interacting with the StrikeIron web service, but to summarize what we’ll need, here they are:

<transition state="lookup" event="areaCodeLookupSuccess">
</transition>

<transition state="lookup" event="areaCodeLookupFailure">
</transition>

<transition state="lookup" event="error.send.failed">
</transition>

The first two handlers react to custom events that we will toss into the CCXML event stream (more on that shortly), and the last will take care of instances where we get an invalid response back from the server (e.g., a 404 response). Now lets look at the PHP components that interact with the StrikeIron web services.

When the HTTP request from Prophecy that holds our area code information is received in PHP, we can access the submitted value by using the PHP $_REQUEST superglobal:

$areacode = (int) $_REQUEST['areacode'];

You’ll notice that we also typecast the value as a way of cleansing the input – as with any other kind of web application, never trust user input. Even though we’re not using the submitted information in a SQL query, this is a really good habit to get into. There are certainly other ways to achieve this, but type casting is simple and effective for our purposes.

The PHP version that comes bundled with Prophecy has support for PHP’s SOAP extension right out of the box. Since we’re going to be accessing several different web services over the course of one telephone call, I decided to set up a very simple class to handle all of the interactions with the StrikeIron web services.

class greenSoapClient {

  private $client;
  private $headers;

  function __construct($type) {
    global $WSDL, $USER, $PSWD;
    $this->client = new SoapClient($WSDL[$type], array('trace' => 1,
                                          'exceptions' => 0));
    $headerArray = array("RegisteredUser" => array("UserID" => $USER,
                                          "Password" => $PSWD));
    $this->headers = new SoapHeader("http://ws.strikeiron.com",
                                          "LicenseInfo", $headerArray);
  }

  function makeSoapCall($name, $params) {
    $result = $this->client->__call($name, array($params), NULL, $this->headers);
    return $this->client->__getLastResponse();
  }

  function __destruct() {
    unset($this->client);
  }

}

This class has only three functions – a constructor, a destructor and a function to make the call to the SOAP method we want information from.

When we instantiate the greenSoapClient class, we pass in a reference to a WSDL file for the service we want to invoke. In this case, we will pass in a reference to the WSDL file for the U.S. Area Code Information Web Service. (Actually, the string “areaCode” is used to access the WSDL reference from a pre-established associative array holding the URL references for all of the WSDL files used by the greenPhone application.)

$mySoapClient = new greenSoapClient("areacode");

Now that we have our area code information, and a shiny new greenSoapClient object to work with, we can make our SOAP call:

$param = array('AreaCode' => $areacode);
$response = $mySoapClient->makeSoapCall('GetAreaCode', $param);

The variable $response now holds the XML response that was returned from the web service. We’ll need to process this response in order to properly format the information we want to return to CCXML.

One of the very cool things about the Voxeo implementation of CCXML is that developers can toss custom events into the CCXML event stream using simple HTTP responses. Prophecy lets us send back a custom event, as well as any data that we want to access in CCXML as properties of that event. We do this by formatting our response as follows:

First line of body of HTTP response = custom event name.
Data to be returned to CCXML = name value pair appearing on successive lines of the HTTP body, one pair per line.

The U.S. Area Code Information Web Service returns two pieces of information that we want to access in CCXML – a count of the number of locations identified for each area code (typically 1), and the name of the U.S. state that area code belongs to. A snippet of the raw response returned from the web service might look something like this (for the 610 area code):

<ServiceResult>
 <Count>1</Count>
 <AreaCodes>
  <AreaCodeInfo>
   <AreaCode>610</AreaCode>
   <Location>Pennsylvania</Location>
  </AreaCodeInfo>
 </AreaCodes>
</ServiceResult>

We want to format our raw XML response like so:

areaCodeLookupSuccess
count=1
location=Pennsylvania

The easiest way to do this in PHP is to use the SimpleXML extension:

$xml = new SimpleXmlElement($response);
$result = $xml->soapBody->GetAreaCodeResponse->GetAreaCodeResult;
$output = "areaCodeLookupSuccessn";
$output .= "count=".$result->ServiceResult->Count."n";
$output .= "location=".$result->ServiceResult->AreaCodes->AreaCodeInfo->Location."nn";

We take the response from the StrikeIron web service and use it to create a new SimpleXML object. We can then access the values we want and build our HTTP response.

How do we deliver our response once we’re done constructing it, we simply use the PHP “echo” language construct to write it out:

echo $output;

Now that we’ve returned our values to CCXML, how do we access them? For the answer to that,we need to go back to the handlers we set up previously, most importantly the handler for the custom “areaCodeLookupSuccess” event:

<transition state="lookup" event="areaCodeLookupSuccess">
 <assign name="count" expr="event$.count"/>
 <if cond="count == 1">
  <assign name="location" expr="event$.location"/>
  <assign name="stateCode" expr="getStateCode(event$.location)"/>
  <assign name="myState" expr="'accepting'"/>
  <accept connectionid="connection_id"/>
 <else/>
  <log expr="'*** Could not look up area code. ***'"/>
  <reject/>
 </if>
</transition>

When we write out our web service response in PHP, we can cause a custom event to drop into the CCXML event stream – the name of this event is the first line of the HTTP response we just constructed – areaCodeLookupSuccess.

We access the values we just returned to CCXML as properties of the areaCodeLookupSuccess event using the “event$.” vernacular. This allows us to assign these values to ECMAScript variables that we have previously declared. It also lets us decide how we want our application to react, based on certain conditions (e.g., if count = 0).

Similarly, our other event handlers can be used if we get an unexpected response form the web service – we could send back a “areaCodeLookupFailure” event. If something really bad happens – like an invalid response from the web server we will get an “error.send.failed” event, so we’ll want to have a handler ready for that as well.

Now that you have a flavor for how to access web services using CCXML and PHP, we’ll look at two different techniques for returning information from a web service to VoiceXML. We’ll cover these two techniques in the next two posts. Stay tuned…

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s