Location: PHPKode > projects > Ebay Developer API > ebay-developer-api/Ebay_API.php
<?php
/*
 *  The Ebay_API class provides an easy interface for making calls to the eBay
 *  developer API.  
 *
 *  The class requires:
 *   - cUrl to be compiled into PHP     Download from http://curl.planetmirror.com/
 *   - the PEAR XML_Serializer package  Download from http://pear.php.net/
 *
 *  @author     Matt McInnes <hide@address.com>
 *  @copyright  2004 Kudos Online
 *  @version    0.1.0
 */
define('EBAY_API_MODE_LIVE', 1);
define('EBAY_API_MODE_TEST', 2);

class Ebay_API {
    var $_mode = EBAY_API_LIVE;

    var $_apiURL = array(
        'live' => ' https://api.ebay.com/ws/api.dll',
        'sandbox' => 'https://api.sandbox.ebay.com/ws/api.dll',
        );

    var $_appHeaders = array(
        'X-EBAY-API-COMPATIBILITY-LEVEL' => array(
            'required' => true,
            'default' => '311',
            ),
        'X-EBAY-API-SESSION-CERTIFICATE' => array(
            'required' => true,
            'xmlName' => 'SessionCertificate',
            ),
        'X-EBAY-API-DEV-NAME' => array(
            'required' => true,
            'xmlName' => 'DevName',
            ),
        'X-EBAY-API-APP-NAME' => array(
            'required' => true,
            'xmlName' => 'AppName',
            ),
        'X-EBAY-API-CERT-NAME' => array(
            'required' => true,
            'xmlName' => 'CertName',
            ),
        'X-EBAY-API-CALL-NAME' => array(
            'required' => true,
            'xmlName' => 'Verb',
            ),
        'X-EBAY-API-SITEID' => array(
            'required' => true,  
            'xmlName' => 'SiteId',
            'default' => 0,
            ),
        'X-EBAY-API-DETAIL-LEVEL' => array(
            'required' => true,
            'xmlName' => 'DetailLevel',
            'default' => 0,
            ),
        'Content-Type' => array(
            'required' => true,
            'default' => 'text/xml',
            ),
        'Content-Length' => array(
            'required' => false,
            'xmlName' => 'ContentLength',
            ),
        );

    function Ebay_API() {
    }

    function setAppCredentials($userId, $password) {
        $this->_requestUserId = $userId;
        $this->_requestPassword = $password;
    }

    /** 
     *  Assign a set of header values at one time
     *
     *  @access     public
     *  @param      array       headers     An array of header keys/values to assign for the request
     *  @return     void
     */
    function setAppHeaders($headers) {
        foreach ( $headers as $key => $value ) {
            if ( isset($this->_appHeaders[$key]) || isset($this->_appHeaders[$this->_getHeaderKey($key)]) ) {
                $this->setAppHeader($key, $value);
            }
        }
    }

    /**
     *  Set a header to send to the eBay application server
     *
     *  @access     public
     *  @param      string      headerName      The header field name (complete or short)
     *  @param      mixed       value           The value to assign to the field
     *  @return     void
     */
    function setAppHeader($headerName, $value) {
        if ( isset($this->_appHeaders[$headerName]) ) {
            $this->_appHeaders[$headerName]['value'] = $value;
        } else {
            if ( $fullHeaderName = $this->_getHeaderKey($headerName) ) {
                $this->_appHeaders[$fullHeaderName]['value'] = $value;
            }
        }
    }

    /**
     *  Fetch the current value of a header assignment
     *
     *  @access     public
     *  @param      string      headerName      The header field name (complete or short)
     *  @return     mixed                       The value assigned for the header, or false
     */
    function getAppHeader($headerName) {
        if ( isset($this->_appHeaders[$headerName]) ) {
            return $this->_appHeaders[$headerName]['value'];
        } else {
            if ( $fullHeaderName = $this->_getHeaderKey($headerName) ) {
                return $this->_appHeaders[$fullHeaderName]['value'];
            }
        }
        return false;
    }

    /**
     *  Get the full header key using the short reference name for the header
     *
     *  @access     private
     *  @param      string      shortName       The short reference for the header
     *  @return     mixed                       The full key when successful, false on failure
     */
    function _getHeaderKey($shortName) {
        foreach ( $this->_appHeaders as $key => $detail ) {
            if ( preg_match('/^'.$shortName.'$/i', $detail['xmlName']) ) {
                return $key;
            }
        }
        return false;
    }

    /**
     *  Set the mode for requests to be executed.  Test mode will execute commands against the eBay sandbox.
     *
     *  @access     public
     *  @param      string      status      Mode to run requests in [live|test]
     *  @return     void
     */
    function setMode($status = 'live') {
        $this->_mode = constant('EBAY_API_MODE_'.strtoupper($status));
    }

    /**
     *  Get the URL that should be referenced according to the mode the application is running in.
     *  All test mode calls will be made to the eBay Sandbox environment.
     *
     *  @access     private
     *  @param      void
     *  @return     string                  The full URL of the eBay application server to make calls to
     */
    function _getApiURL() {
        return ($this->_mode == EBAY_API_MODE_LIVE) ? $this->_apiURL['live'] : $this->_apiURL['sandbox'];
    }

    /**
     *  Set the session certificate header for the upcoming requests.  This is simply contructed 
     *  from the existing developer keys specified in the object.
     *
     *  @access     private
     *  @param      void
     *  @return     void
     */
    function _setSessionCertificate() {
        $certificate = $this->getAppHeader('DevName').';'.$this->getAppHeader('AppName').';'.$this->getAppHeader('CertName');
        $this->setAppHeader('SessionCertificate', $certificate);
    }

    /**
     *  Clean the key/value pairs in the application headers so that all required variables are set
     *  either to the values specified or their default values, then construct an array of HTTP headers
     *  to use in the cUrl transaction with the eBay application server.
     *
     *  @access     private
     *  @param      void
     *  @return     array                   An array of HTTP headers
     */
    function _cleanAppHeaders() {
        $finalHeaders = array();
        foreach ( $this->_appHeaders as $key => $detail ) {
            $finalHeaders[$key] = $key.': '.(isset($detail['value']) ? $detail['value'] : $detail['default']);
        }
        return $finalHeaders;
    }

    /**
     *  Structure and send an XML request to Ebay
     *
     *  @access     private
     *  @param      string      command     The command to pass to eBay
     *  @param      array       params      An array of paramaters to include with the request
     *  @param      array       siteId      The siteId to include with the request
     *  @return     array                   The eBay XML result transformed into an array
     */
    function sendRequest($command, $params = null, $siteId = 0) {
        $this->_setSessionCertificate();
        $this->setAppHeader('Verb', $command);
        $this->setAppHeader('SiteId', $siteId);
        $this->setAppHeaders($params);

        $xmlRequest = $this->_buildRequest($params);
        $this->setAppHeader('ContentLength', strlen($xmlRequest));

        $eBayApp = curl_init();
        curl_setopt($eBayApp, CURLOPT_POST, 1);
        curl_setopt($eBayApp, CURLOPT_POSTFIELDS, $xmlRequest);
        curl_setopt($eBayApp, CURLOPT_HTTPHEADER,  $this->_cleanAppHeaders());
        curl_setopt($eBayApp, CURLOPT_URL, $this->_getApiURL());
        curl_setopt($eBayApp, CURLOPT_SSL_VERIFYHOST,  2);
        curl_setopt($eBayApp, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($eBayApp, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($eBayApp, CURLOPT_VERBOSE, 1);

        $eBayResponse = curl_exec ($eBayApp);

        if ( Ebay_API::isError($arrResponse = $this->_parseXMLToArray($eBayResponse)) ) {
            Ebay_API::showError($arrResponse, curl_getinfo($eBayApp));
        }
        curl_close ($eBayApp);
        return $arrResponse;
    }

    /**
     *  Build the full XML request that needs to be sent to eBay 
     *
     *  @access     private
     *  @param      array       params      An array of key value pairs that will make up additional request data
     *  @return     string                  The complete XML request to send to eBay
     */
    function _buildRequest($params) {
        $request = array(
            'RequestUserId' => $this->_requestUserId,
            'RequestPassword' => $this->_requestPassword,
            'DetailLevel' => $this->getAppHeader('DetailLevel'),
            'ErrorLevel' => 1,
            'SiteId' => $this->getAppHeader('SiteId'),
            'Verb' => $this->getAppHeader('Verb'),
            ) + $params;
        $XMLrequest = $this->_parseArrayToXML($request);

        return $XMLrequest;
    }

    /**
     *  Construct an XML document according to the data passed to the function
     *  
     *  @access     private
     *  @param      array       requestData     The data to be converted to XML format
     *  @return     string                      An XML document
     */
    function _parseArrayToXML($requestData) {
        require_once 'XML/Serializer.php';
        $xmlOptions = array(
            'addDecl' => true,
            'encoding' => 'ISO-8859-1',
            'indent' => '  ',
            'rootName' => 'request',
            );
        $xmlParser = &new XML_Serializer($xmlOptions);
        if ( $xmlParser->serialize($requestData) ) {
            return $xmlParser->getSerializedData();
        }
    }

    /**
     *  Convert an XML document to an 'n' dimensional array
     *
     *  @access     private
     *  @param      string      xmlString       The XML document to convert back to an array
     *  @return     array                       An 'n' dimenstional array of data
     */
    function _parseXMLToArray($xmlString) {
        require_once 'XML/Unserializer.php';
        $xmlParser = &new XML_Unserializer();
        if ( $xmlParser->unserialize($xmlString) ) {
            $eBayArray = $xmlParser->getUnserializedData();
            return $eBayArray;
        }
        return;
    }

    /**
     *  Read a value from an eBay response array using the notation name.name2.value
     *
     *  @access     public
     *  @param      string      reference       The string to reference into the array/XML response from eBay
     *  @return     mixed                       The value of the reference requested, or false
     *  @note                                   This function can be called statically
     */
    function getFromResponse($eBayResponse, $reference) {
        $refCode = preg_replace('/\./', '\'][\'', $reference);
        eval('$value = $eBayResponse[\''.$refCode.'\'];');
        return ($value ? $value : false);
    }

    /**
     *  Determine whether an eBay response is actually an error or not
     *
     *  access      public
     *  param       array       eBayResponse    An eBay response to check
     *  @return     int                         Returns the errorCode if one exists, or false
     */
    function isError($eBayResponse) {
        if ( $errorCode = Ebay_API::getFromResponse($eBayResponse, 'Errors.Code') ) {
            return $errorCode;
        }
        return false;
    }
}
?>
Return current item: Ebay Developer API