fusi0n
29Jul/11

Big Commerce API PHP Wrapper

Short URL for this post: http://plp.me/nBqWqa

Big Commerce is a hosted e-commerce platform. You are given FTP credentials to access the few static files you are allowed to manipulate... and you have an API. For various reasons, I had to interact with the Big Commerce API and since there was a serious lack of code (and decent documentation), I figured I'd put together my own little wrapper. Should be pretty self-explanatory if you're here. Needless to say, this code comes as-is with no support from me whatsoever.

define('BIG_COMMERCE_DEBUG', false);
define('BIG_COMMERCE_SUCCESS', 'SUCCESS');
define('BIG_COMMERCE_FAILURE', 'FAILED');
define('BIG_COMMERCE_USERNAME', 'YOUR_USERNAME');
define('BIG_COMMERCE_TOKEN', 'YOUR_TOKEN');
define('BIG_COMMERCE_URL', 'https://YOUR_STORE_URL/xml.php');
function bc($type, $criteria) {
  $xml = new SimpleXMLElement('');
  $xml->addChild('username', BIG_COMMERCE_USERNAME);
  $xml->addChild('usertoken', BIG_COMMERCE_TOKEN);
  switch (strtolower($type)) {
    case 'product':
    case 'products':
      $xml->addChild('requesttype', 'products');
      $xml->addChild('requestmethod', 'Get'.ucfirst($type));
      $fields =  is_array($criteria)? $criteria : array('productId' => (int)$criteria);
      break;
    case 'customer':
    case 'customers':
      $xml->addChild('requesttype', 'customers');
      $xml->addChild('requestmethod', 'Get'.ucfirst($type));
      $fields =  is_array($criteria)? $criteria : array('customerId' => (int)$criteria);
      break;
    case 'order':
    case 'orders':
      $xml->addChild('requesttype', 'orders');
      $xml->addChild('requestmethod', 'Get'.ucfirst($type));
      $fields = is_array($criteria)? $criteria : array('orderId' => (int)$criteria);
      break;
  }
  $details = $xml->addChild('details');
  foreach ($fields as $k=>$v) $details->addChild($k, $v);
  $stream = stream_context_create(array('http' => array('method' => 'POST','header' => 'Content-Type: text/xml', 'content' => $xml->saveXML())));
  $response = new SimpleXMLElement(file_get_contents(BIG_COMMERCE_URL, false, $stream));
  switch ($response->status) {
    case BIG_COMMERCE_SUCCESS:
      return $response->data;
      break;
    case BIG_COMMERCE_FAILURE:
    default:
      return BIG_COMMERCE_DEBUG? $response->errormessage : false;
      break;
  }
}
Tagged as: , ,