Connecting to the eBay Trading API in PHP
We have recently been commissioned to create a Magento e-Commerce module which will integrate PHP with eBay. While starting to research this, we had real trouble finding an easy way to talk to the eBay trading API. There is a very advanced SOAP class, but at Camiloo we like to do things in the most straightforward way possible.
So, using PHP’s built in CURL support, we devised the following one-stop-shop function.
function talk_to_ebay($devid, $appid, $certid, $callname, $xml, $mode="sandbox", $siteid="3", $version="621"){
if($mode == "sandbox"){
$ch = curl_init("https://api.sandbox.ebay.com/ws/api.dll?siteid=$siteid");
}else{
$ch = curl_init("https://api.ebay.com/ws/api.dll?siteid=$siteid");
}
$headers = array('X-EBAY-API-COMPATIBILITY-LEVEL: '.$version,
'X-EBAY-API-DEV-NAME: '.$devid,
'X-EBAY-API-APP-NAME: '.$appid,
'X-EBAY-API-CERT-NAME: '.$certid,
'X-EBAY-API-CALL-NAME: '.$callname,
'X-EBAY-API-SITEID: '.$siteid);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
$output = curl_exec($ch);
curl_close($ch);
return simplexml_load_string($output);
}
So, what do we have here? Well, for inputting the required variables:
$devid – eBay Developer ID
$appid – eBay Application ID
$certid – eBay Certificate
$callname – The name of the call you are sending to eBay in your XML – e.g. GetSellerList
$xml – The XML Document you want to send to eBay [as defined here]
And the following optional variables:
$mode – Do you want to connect to “live” or “sandbox” API. Default is “sandbox”.
$siteid – Which eBay site are you calling the API about? See here. Default is 3 [UK].
$version – Which version of the API is this call for? See here. Default is 621.
You will get the response of your call as a convenient PHP simplexml [php manual link] document. When debugging you have two options to view the contents of this- you can either print_r() [php manual link] on the returned value or you can echo the returned value like this (assuming the returned value is named $retxml).
header("Content-Type: text/xml");
echo $retxml->asXml();
This will output the XML document as it was received from eBay. To get this to display correctly in firefox as an XML document, i’ve also added a header(“Content-Type: text/xml”); line above. [php manual link]
Hope you have found this tutorial useful – if you have any PHP topics you want me to cover in future on the blog just leave a comment below – I’m going to try to post a lunchtime blog at least every two days.
Mark.
You can follow any responses to this entry through the RSS 2.0 feed.
Facebook comments: