PHP


 

In this article we discuss some examples for API interaction. It should be noted that these are indeed examples and not production-grade code.


Uploading Purchases 1

Language: PHP
This example assumes a set of classes has been generated according to the WSDL and are stored in the folder phpClasses_1.0. A tool like Wsdl2phpgenerator can be used to this end.

In the example, a purchase is generated every minute for a 1000 minutes and sent to CB via the uploadPurchases method. Some very rudimentary checks are in place to handle expired sessions, incorrect credentials, and other errors.

<?php

    function __autoload($class_name) {
        include 'phpClasses_1.0/'.$class_name . '.php';
    }

    function guid(){
        if (function_exists('com_create_guid')){//windows only
            return com_create_guid();
        }else{
            mt_srand((double)microtime()*10000);//optional for php 4.2.0 and up.
            $charid = strtoupper(md5(uniqid(rand(), true)));
            $hyphen = chr(45);// "-"
            $uuid = substr($charid, 0, 8).$hyphen
                    .substr($charid, 8, 4).$hyphen
                    .substr($charid,12, 4).$hyphen
                    .substr($charid,16, 4).$hyphen
                    .substr($charid,20,12);
            return $uuid;
        }
    }

    function login($userName, $password){

        $url     = "https://api.billing.inter8.co/V1_0.svc?wsdl"; 
        $options = array();
        $client  = new SoapClient($url, $options);

        $params = array(
            "emailAddress" => $userName,
            "password" => $password
        );

        $response = $client->Login($params);
        $result = $response->LoginResult->Result;

        if($result==NULL){
            echo "ERROR during Login\n";
            echo $response->LoginResult->ResultMessage."\n";
        }

        return $result;
    }

    $user = "admin@example.com";
    $pass = "examplePassword";

    $tok = login($user, $pass);
    if($tok!=NULL){
        //OK
    } else {
        exit();
    }

    $url     = "https://api.billing.inter8.co/V1_0.svc?wsdl"; 
    $options = array();
    $client  = new SoapClient($url, $options);

    $num = 1000; //send 1000 purchases
    $i = 0;
    while($i < $num){

        $purch = new Purchase(false, mt_rand(1,5), UOM::None);
        $purch->CustomerCode="C001";
        $purch->ProductLabel="Bicycle";
        $purch->PurchaseReference=guid();
        $purch->PurchaseDate="2015-01-02T12:34:56";

        $params = array(
            "purchases" => array($purch)
        );

        $failCount = 0; //keep track of subsequent failures
        $uploaded = false; //keep trakc of success
        while(!$uploaded && $failCount < 3){//as long as it's not uploaded, keep trying
            try {
                $response = $client->__soapCall("UploadPurchases", array($params), NULL, new SoapHeader("System","String",$tok));
            } catch (SoapFault $e) {
                if(strpos($e->faultstring,"You are not authorized to access this service, or your session might have expired")!==false){//session expired
                    if($failCount==0){//first failure, just log in again
                        $tok = login($user, $pass);
                    } else { //second failure -- sleep 20 secs then retry.
                        echo $response->UploadPurchasesResult->ResultMessage;
                        echo "\n Second error in upload due to credentials, sleeping for 20 seconds and trying again\n";
                        sleep(20);
                        $tok = login($user, $pass);
                    }
                    $failCount++;
                }
            }
            if($response->UploadPurchasesResult->ResultCode == "Success"){//uploaded succesfully
                $failCount = 0;
                $uploaded=true;
                echo "Sent 1 purchase to CB: " . $purch->PurchaseReference."\n";
            } else if (strpos($response->UploadPurchasesResult->ResultMessage, "authorized") !== false) {

            } else {//failed due to some other reason...
                echo $response->UploadPurchasesResult->ResultMessage;
                echo "\nError in upload, sleeping for 20 seconds and trying again\n";
                sleep(20);
                $failCount++;
            }
        }
        if($failCount==3){//never uploaded, broke out of the loop due to 3 failures in a row.
            echo "Persistent error during upload, exiting\n";
            exit();
        }
        sleep(60);//sleep for 1 minute before sending next
        $i++;
    }
?>

Uploading Customers

Language: PHP
This example relies on the same dependencies as Example 1. It's final purpose is to add a single Customer. To this end, it starts by adding a CustomerCluster for the customer and then finally adds the customer, assigning it to the newly created cluster.

<?php

    function __autoload($class_name) {
        include 'phpClasses_1.0/'.$class_name . '.php';
    }

    function login($userName, $password){
        $url     = "https://api.billing.inter8.co/V1_0.svc?wsdl"; 
        $options = array();
        $client  = new SoapClient($url, $options);
        $params = array(
            "emailAddress" => $userName,
            "password" => $password
        );
        $response = $client->Login($params);
        $result = $response->LoginResult->Result;
        if($result==NULL){
            echo "ERROR during Login\n";
            echo $response->LoginResult->ResultMessage."\n";
        }
        return $result;
    }

    $user = "admin@example.com";
    $pass = "ExamplePassword";

    $tok = login($user, $pass);
    if($tok!=NULL){
        //OK
    } else {
        exit();
    }

    $url     = "https://api.billing.inter8.co/V1_0.svc?wsdl"; 
    $options = array();
    $client  = new SoapClient($url, $options);

    $response = $client->__soapCall("AddCustomerCluster", array(array("tagName" => "Customer 0001", "parentTagName"=>"All Customers")), NULL, new SoapHeader("System","String",$tok));
    if($response->AddCustomerClusterResult->ResultCode == "Success"){

    } else {
        echo "ERROR\n";
        echo $response->AddCustomerClusterResult->ResultMessage."\n";
    }

    $addr = new Address();
    $addr->AddressLine1="Laapersveld 61";
    $addr->PostalCode="1213 VB";
    $addr->City="HILVERSUM";
    $addr->Country="NETHERLANDS";
    $addr->Name="Invoice Address";

    $cust = new Customer(true, 1, UOM::Month, true, false, false, false, false, false, 1033);
    $cust->Addresses=array($addr);
    $cust->BillFromDate="2015-01-01T00:00:00";

    $cust->CustomerCode="C0001";
    $cust->CustomerName="Customer 0001";
    $cust->ImportTagName="Customer 0001";
    $cust->TimezoneId="W. Europe Standard Time";

    $params = array(
        "customers" => array($cust)
    );

    $response = $client->__soapCall("UploadCustomers", array($params), NULL, new SoapHeader("System","String",$tok));
    if($response->UploadCustomersResult->ResultCode == "Success"){

    } else {
        echo "ERROR: API call threw an error:\n";
        echo $response->UploadCustomersResult->ResultMessage."\n";
    }
?>

Retrieving general invoice information

Language: PHP
The following example retrieves all invoice headers covering a specified date and prints out some information regarding each one.

<?php

    function __autoload($class_name) {
        include 'phpClasses_1.0/'.$class_name . '.php';
    }

    function login($userName, $password){
        $url     = "https://api.billing.inter8.co/V1_0.svc?wsdl"; 
        $options = array();
        $client  = new SoapClient($url, $options);
        $params = array(
            "emailAddress" => $userName,
            "password" => $password
        );
        $response = $client->Login($params);
        $result = $response->LoginResult->Result;
        if($result==NULL){
            echo "ERROR during Login\n";
            echo $response->LoginResult->ResultMessage."\n";
        }
        return $result;
    }

    $user = "admin@example.com";
    $pass = "ExamplePassword";

    $tok = login($user, $pass);
    if($tok!=NULL){
        //OK
    } else {
        exit();
    }

    $url     = "https://api.billing.inter8.co/V1_0.svc?wsdl"; 
    $options = array();
    $client  = new SoapClient($url, $options);

    $response = $client->__soapCall("GetInvoiceHeaders", array(array("billingPeriodDate"=>"2014-04-15T00:00:00")), NULL, new SoapHeader("System","String",$tok));
    if($response->GetInvoiceHeadersResult->ResultCode == "Success"){
        foreach($response->GetInvoiceHeadersResult->Result->InvoiceHeader as $invoice){
            echo $invoice->CustomerCode." ".$invoice->BillingPeriodStart." - ".$invoice->BillingPeriodEnd.": ".$invoice->LastCalculatedTotal." (".$invoice->Id.")\n";
        }
    } else {
        echo "ERROR\n";
        echo $response->GetInvoiceHeadersResult->ResultMessage."\n";
    }

?>

Retrieving invoice details

Language: PHP
In this example we decide we need full details on one of the invoices we retrieved in Example 4. We retrieve the invoice details and print out some general information on them.

<?php

    function __autoload($class_name) {
        include 'phpClasses_1.0/'.$class_name . '.php';
    }

    function login($userName, $password){
        $url     = "https://api.billing.inter8.co/V1_0.svc?wsdl"; 
        $options = array();
        $client  = new SoapClient($url, $options);
        $params = array(
            "emailAddress" => $userName,
            "password" => $password
        );
        $response = $client->Login($params);
        $result = $response->LoginResult->Result;
        if($result==NULL){
            echo "ERROR during Login\n";
            echo $response->LoginResult->ResultMessage."\n";
        }
        return $result;
    }

    $user = "admin@example.com";
    $pass = "ExamplePassword";

    $tok = login($user, $pass);
    if($tok!=NULL){
        //OK
    } else {
        exit();
    }

    $url     = "https://api.billing.inter8.co/V1_0.svc?wsdl"; 
    $options = array();
    $client  = new SoapClient($url, $options);

    $response = $client->__soapCall("GetInvoiceDetails", array(array("invoiceId"=>"TheIdWeGotFromExample4")), NULL, new SoapHeader("System","String",$tok));
    if($response->GetInvoiceDetailsResult->ResultCode == "Success"){
        foreach($response->GetInvoiceDetailsResult->Result->InvoiceItems->InvoiceDetailItem as $iit){
            echo $iit->Quantity." ".$iit->ProductTagName." ".$iit->OperatorUsed." @ ".$iit->OperatorValueUsed.": ".$iit->Value."\n";
        }
    } else {
        echo "ERROR\n";
        echo $response->GetInvoiceDetailsResult->ResultMessage."\n";
    }

?>

Retrieving invoice transformation results

Language: PHP
In this example we retrieve and display all invoices for a specific customer. This mechanism can be used, e.g., in a self-service portal environment. Where we retrieve the invoices transformation results for the customer that is logged in. The example is actually meant to be served by an apache webserver (although it can be easily modified for other servers) and will generate a page with a list of invoices for the customer that is hard-coded in the PHP code. It requires the existence of a "files" folder that the apache user has sufficient permissions for. This folder is used to store files locally before serving. In an actual implementation, we would suggest to add some intelligence here, in terms of caching and versioning. The example is purely HTML based, but should be straightforward to modify to allow serving of PDFs as well.

<html>
  <head>
    <style>
        .itr {
           padding-left:10px;
           padding-top:5px;
           padding-bottom:5px;
           border: 0px solid black;
           background-color: #fff;
           width:320px;
           margin-top: 2px;
           height:14px;
        }

        .itr:hover {
          background-color:#aed4e8;
          color: #fff;
         }
        
        .period {
           padding-right:10px;
           width:100px;
           float:left;
         }
        
        .cc {
           float:left;
           width:50px;
           padding-right: 10px;
         }
        
        .type {
           float:right;
           width:150px;
        
         }
        
        .header {
           padding-left:10px;
           padding-top:5px;
           padding-bottom:5px;
           border: 0px solid black;
           width:320px;
           margin-top: 2px;
           height:14px;
           background-color: #333;
           color: #fff;
         }
    </style>
  </head>
  <body>
  <div class="header">
    <span class="period">Period</span>
   <span class="type">Type</span>
  </div>
<?php

date_default_timezone_set("Europe/Amsterdam");

$APIu   = "admin@example.com";
$APIp   = "ExamplePassword";

$url         = "https://api.billing.inter8.co/V1_1.svc?wsdl";
$client      = new SoapClient($url, $options);
$custCode    = "1";
$transName   = "HTML Invoice";

$params = array(
                "emailAddress" => $APIu,
                "password" => $APIp
                );

$response = $client->Login($params);

$tok = $response->LoginResult->Result;
if($tok!=NULL){

} else {
  echo "ERROR\n";
  echo $response->LoginResult->ResultMessage."\n";
}

parse_str($_SERVER['QUERY_STRING'], $args);
if($args['dl']){
  $fileResponse = $client->__soapCall("GetInvoiceTransformationResultFile", array(array("invoiceTransformationResultId" => $args['dl'])), NULL, new SoapHeader("System","String",$tok));
  $filename = "files/".$args['fn'];
  $output = fopen($filename , "w");
  fwrite($output, $fileResponse->GetInvoiceTransformationResultFileResult->Result->FileBytes);
  fclose($output);
  $modules = apache_get_modules();

  if($args['html']){
    header("Location: http://<YOUR HOST>/PathToFiles/".$filename);
    die();
  } else if (in_array('mod_xsendfile', $modules)) {
    header ('X-Sendfile: ' . $filename);
    header ('Content-Type: application/pdf' );
    header ('Content-Disposition: attachment; filename="' . basename($filename) . '"');
    exit();
  } else {
    header ('Content-Type: application/pdf');
    header ('Content-Disposition: attachment; filename="' . basename($filename) . '"');
    @ob_end_clean();
    @ob_end_flush();
    readfile($filename);
    exit();
  }
} else {
}

function cmp($a, $b){
  if(new DateTime($a->InvoicePeriodStart) < new DateTime($b->InvoicePeriodStart)){
    return 1;
  } else if(new DateTime($a->InvoicePeriodStart) > new DateTime($b->InvoicePeriodStart)){
    return -1;
  } else {
    return 0;
  }
}

$response = $client->__soapCall("GetInvoiceTransformationResultsForCustomers", array(array("customerCodes" => array( $custCode ), "invoiceTransformationName" => $transName)), NULL, new SoapHeader("System","St\
ring",$tok));
if($response->GetInvoiceTransformationResultsForCustomersResult->ResultCode == "Success"){
  $res = $response->GetInvoiceTransformationResultsForCustomersResult->Result->InvoiceTransformationResult;
  $res = is_array($res)?$res:array($res);
  uasort($res, 'cmp');
  foreach($res as $itr){
    if($itr != NULL && $itr->Status == "COMPLETE"){
        $d = new DateTime($itr->InvoicePeriodStart);
        echo "    <div class=\"itr\" data=\"".$itr->Id."\" fn=\"".$itr->CustomerCode."_".$d->format("M-Y")."\"><span class=\"period\">" . $d->format("F Y") . "</span><span class=\"type\">".$itr->InvoiceTransformationName."</span></div>\n";
    }
  }
  }
?>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.js"></script>
    <script type="text/javascript">
  $(".itr").click(function(event){
      var id = event.currentTarget.getAttribute("data");
      var fn = event.currentTarget.getAttribute("fn");
      window.location.href ="index.php?dl=" + id +"&fn="+fn+"&html=1";
    })
    </script>
  </body>
</html>