OpenX API: Example XML-RPC Code to Get Campaign Month to Date Impressions

Here is an example of using the (unsupported) OpenX XML-RPC API to get the number of impressions served, month-to-date', for campaign number '123'.

<?php

if (!@include('/website/openx287/lib/pear/XML/RPC.php')) {
      die('Error: cannot load the PEAR XML_RPC class');
}
$xmlRpcHost = 'your.openx.server.com';
$webXmlRpcDir = '/www/api/v1/xmlrpc';
$logonXmlRpcWebServiceUrl = $webXmlRpcDir . '/LogonXmlRpcService.php';
$campaignXmlRpcWebServiceUrl = $webXmlRpcDir . '/CampaignXmlRpcService.php';
$username = 'your_openx_admin_user_name';
$password = 'your_openx_password';

function returnXmlRpcResponseData($oResponse)
{
     if (!$oResponse->faultCode()) {
          $oVal = $oResponse->value();
          $data = XML_RPC_decode($oVal);
          return $data;
     } else {
     die('Fault Code: ' . $oResponse->faultCode() . "\n" .
         'Fault Reason: ' . $oResponse->faultString() . "\n");
     }
}

// login to openx api and print session id

$aParams = array(
                    new XML_RPC_Value($username, 'string'),
                    new XML_RPC_Value($password, 'string')
             );
$oMessage  = new XML_RPC_Message('logon', $aParams);
$oClient   = new XML_RPC_Client($logonXmlRpcWebServiceUrl, $xmlRpcHost);
$oResponse = $oClient->send($oMessage);
if (!$oResponse) {
     die('Communication error: ' . $oClient->errstr);
}
$sessionId = returnXmlRpcResponseData($oResponse);
echo 'User logged on with session Id : ' . $sessionId . '<br>';

// get  month-to-date served impressions for campaign 123

$campaignId = 123;
$oStartDate = date("Ym").'01T00:00:00';
$oEndDate =  date("c");
$aParams    = array(
                new XML_RPC_Value($sessionId, 'string'),
                new XML_RPC_Value($campaignId, 'int'),    
                new XML_RPC_Value($oStartDate, 'dateTime.iso8601'), 
                new XML_RPC_Value($oEndDate, 'dateTime.iso8601'),  
                );

    $oMessage   = new XML_RPC_Message('campaignPublisherStatistics', $aParams);    
    $oClient    = new XML_RPC_Client($campaignXmlRpcWebServiceUrl, $xmlRpcHost);
    $oResponse  = $oClient->send($oMessage);
    $CampaignStats   = returnXmlRpcResponseData($oResponse);
    echo 'Campaign '. $campaignID . 'Month-to-Date Impressions: ' . $CampaignStats['0']['impressions'] . '<br>';

//logout

$aParams   = array(new XML_RPC_Value($sessionId, 'string'));
$oMessage  = new XML_RPC_Message('logoff', $aParams);
$oClient   = new XML_RPC_Client($logonXmlRpcWebServiceUrl, $xmlRpcHost);
$oResponse = $oClient->send($oMessage);
echo 'User with session Id : ' . $sessionId . ' logged off<br>';


?> 

Note: I posted this because the OpenX API code is not supported anymore; but many people still use OpenX and there are not many examples on how to use the API on the net.

See also: OpenX API: Example XML-RPC Code to Get Campaign Impressions