Overview
In part of 1 of this 2-part series, we covered all of the basics of what exactly is involved with making calls to eBay’s API using PHP. We reviewed each step in the process, but we haven’t actually seen any of this in action yet. For part 2, we’ll be building some actual API calls from start to finish. After reviewing the samples in this article I think you’ll feel much more comfortable with these methods and will be making your own calls to eBay without any trouble.
I’m going to start with a very simple call, GeteBayOfficalTime, which as the name suggests will return the current time that eBay is running on. Then we’ll look at GetItem, which is a little bit more involved and allows us to retrieve information about eBay items programmatically. So, let’s get started!
Configuration File
The first thing we need to do in order to make calls is make our API credentials available to our application. As I mentioned in part 1, I generally do this with a configuration file and that’s exactly what we’ll do here.
I’ve created a file, config.php, and have stored it within my project files. Here is what it currently looks like.
$sandbox = true; $compat_level = 753; $api_endpoint = $sandbox ? 'https://api.sandbox.ebay.com/ws/api.dll' : 'https://api.ebay.com/ws/api.dll'; $dev_id = $sandbox ? "K8CU7387FJ375WF5N1D1QXDR37K1K8" : ""; $app_id = $sandbox ? "AngellEY-94d6-4611-994c-1bdcb33b093d" : ""; $cert_id = $sandbox ? "0138ffba-9069-4b2e-bb5e-4511125133a4" : ""; $auth_token = $sandbox ? "12341234ASDFASDF234234" : "";
As you can see, this file simply sets values for the following variables:
- sandbox – This is a Boolean flag that adjusts whether or not the application should run on the eBay sandbox (test server) or not.
- compat_level – This variable stores the compatibility level, or the API version, that you’re using within this call. This can be found at the very top of the documentation page for any given API call. For example, take a look at the documentation for GeteBayOfficalTime and you’ll see at the very top it shows the current version as of the time of this writing is 753.
- api_endpoint – This value is adjusted based on the value of $sandbox and sets the URL for API calls accordingly.
- dev_id/app_id/cert_id/auth_token – Each of these values are considered part of your API credentials and were discussed in part 1. You should have access to these values within your own eBay developer account.
You can store anything else you might want to within your config file, but this is all we need in order to make calls successfully. We’ll include this config.php file into each of our project files where making calls to eBay.
GeteBayOfficialTime
We can now begin constructing a PHP file to make a call to eBay and handle the response accordingly. I’ll go through this step by step and then we’ll take a look at the entire script as a whole.
First, we need to include our configuration file and also set values for a couple of other necessary variables. As such, I’ll create a new file called GeteBayOfficalTime.php and start with the following lines of code.
// Load configuration file require_once("includes/config.php"); $site_id = 0; $call_name = 'GeteBayOfficialTime';
Our config file will now be available to this script, and we’ve also set values for a couple of other variables:
- site_id – This is the value of the eBay site ID which describes to eBay which country/site you’d like to interact with. In this case we’re using the site ID 0 because that is for the US eBay site. Take a look at eBay’s documentation for the IDs for other countries as necessary.
- call_name – This variable simply holds the name of the API call we’re making so that it can be easily accessible through-out our application. In this case it’s set to GeteBayOfficialTime since that’s the call we’re working with.
Next, we need to create our headers as discussed in part 1 of this series. I’ll simply paste in the same code discussed previously:
$headers = array ( 'X-EBAY-API-COMPATIBILITY-LEVEL: ' . $compat_level, 'X-EBAY-API-DEV-NAME: ' . $dev_id, 'X-EBAY-API-APP-NAME: ' . $app_id, 'X-EBAY-API-CERT-NAME: ' . $cert_id, 'X-EBAY-API-CALL-NAME: ' . $call_name, 'X-EBAY-API-SITEID: ' . $site_id, );
As you can see, this is where the majority of our configuration variables are utilized. Our array simply creates each header name and uses the variable for the value in each instance. We are left with a single array, $headers, that holds our information to pass into the CURL request in just a little bit.
Now we can move on to generating our actual XML request. The first thing we need to do is see what the request looks like, so we’ll pull up the eBay API reference for GeteBayOfficalTime.
On this page, eBay shows us the format of this particular call including each element that can be included with it.
<?xml version=”1.0″ encoding=”utf-8″?> <GeteBayOfficialTimeRequest xmlns=”urn:ebay:apis:eBLBaseComponents”> <!– Standard Input Fields –> <ErrorLanguage>string</ErrorLanguage> <MessageID>string</MessageID> <Version>string</Version> <WarningLevel>WarningLevelCodeType</WarningLevel> </GeteBayOfficialTimeRequest>
As you can see, it follows the same format that we discussed in part 1 of this article, but it has replaced <CallName> with <GeteBayOfficalTimeRequest>. If you click on any of the element names inside this, you will be taken directly to a detailed description of that element so you can see exactly what type of information should be passed in that spot. This can help a lot when working with larger API calls that require more information. You might also notice the Standard Input Fields section. This is described more in the documentation, but that is basically just a placeholder for the <RequesterCredentials> node you’ll see here in just a moment and is required with every call you make to eBay.
In this case, each of the elements shown is optional and I’m happy to accept the defaults. As such, I’ll leave them out entirely. Interestingly enough, that means we don’t need any extra elements included with this request. All we need is the following:
<?xml version="1.0″ encoding="utf-8″?> <GeteBayOfficialTimeRequest xmlns="urn:ebay:apis:eBLBaseComponents"> <RequesterCredentials> <eBayAuthToken>token_value</eBayAuthToken> </RequesterCredentials> </GeteBayOfficialTimeRequest>
This can be generated within our script using the following PHP snippet:
// Generate XML request $xml_request = “<?xml version=\"1.0\" encoding=\"utf-8\"?> <“.$call_name."Request xmlns=\"urn:ebay:apis:eBLBaseComponents\"> <RequesterCredentials> <eBayAuthToken>" . $auth_token . “</eBayAuthToken> </RequesterCredentials> </".$call_name."Request>";
Here you can see that we’ve included our $call_name and $auth_token variables accordingly, and we now have a variable called $xml_request that contains our entire XML string.
At this point we have our headers and our XML string ready to go. We can now send the actual request to eBay using CURL with the following code that we reviewed in part 1:
// Send request to eBay and load response in $response $connection = curl_init(); curl_setopt($connection, CURLOPT_URL, $api_endpoint); curl_setopt($connection, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($connection, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($connection, CURLOPT_HTTPHEADER, $headers); curl_setopt($connection, CURLOPT_POST, 1); curl_setopt($connection, CURLOPT_POSTFIELDS, $xml_request); curl_setopt($connection, CURLOPT_RETURNTRANSFER, 1); $response = curl_exec($connection); curl_close($connection);
This snippet fires our request off to eBay and stores the response in our PHP variable, $response. We are now ready to parse out our information using DOM as discussed in part 1. Let’s take a look at what exactly we get from eBay first.
<?xml version="1.0" encoding="UTF-8"?> <GeteBayOfficialTimeResponse xmlns="urn:ebay:apis:eBLBaseComponents"> <Timestamp>2012-01-18T18:38:38.789Z</Timestamp> <Ack>Success</Ack> <Version>756</Version> <Build>E756_CORE_BUNDLED_14289277_R1</Build> </GeteBayOfficialTimeResponse>
Here we can see that <Ack> is Success, which means our API request was successful. We also see a <Timestamp> which is the value we’re after in this particular case. It is a standard practice to check the value of <Ack> and then start pulling out the necessary information based on the call status.
Now we can go ahead and setup our DOM object, load this response, and pull out the necessary data.
/ Create DOM object and load eBay response $dom = new DOMDocument(); $dom->loadXML($response); // Parse data accordingly. $ack = $dom->getElementsByTagName('Ack')->length > 0 ? $dom->getElementsByTagName('Ack')->item(0)->nodeValue : ''; $eBay_official_time = $dom->getElementsByTagName('Timestamp')->length > 0 ? $dom->getElementsByTagName('Timestamp')->item(0)->nodeValue : '';
Again, as explained in part 1, we’re setting up a new DOM object and loading our $response into this object accordingly. This gives us access to a wide range of functions that will make it easy for us to search through the document and pull out what we need. The function we’ll be using the majority of the time is getElementsByTagName().
This function allows you to pass in the name of a tag you’re looking for and will return every instance of that tag name in an array, even if only a single element was found. I’m using a PHP shorthand if/then statement to first check that the element was found, and if so, pull out the value and store it in the variable. If it’s not found, the variable is still created but is left with an empty value. Without this if/then check we would end up with PHP errors if the element is not found in the XML string. This same format can be used to pull any value(s) you want from the eBay response.
I used this method to pull out the value for Ack and Timestamp, so now we’re able to process that data however we want within our application. In this case, I’ll simply display the timestamp on screen so we can see that it works as expected.
echo $eBay_official_time;
That line will display the actual Timestamp value, 2012-01-18T18:38:38.789Z, on screen for us.
Now let’s take a look at this script in its entirety.
<?php // Load configuration file require_once('includes/config.php'); $site_id = 0; $call_name = 'GeteBayOfficialTime'; // Create headers to send with CURL request. $headers = array ( 'X-EBAY-API-COMPATIBILITY-LEVEL: ' . $compat_level, 'X-EBAY-API-DEV-NAME: ' . $dev_id, 'X-EBAY-API-APP-NAME: ' . $app_id, 'X-EBAY-API-CERT-NAME: ' . $cert_id, 'X-EBAY-API-CALL-NAME: ' . $call_name, 'X-EBAY-API-SITEID: ' . $site_id, ); // Generate XML request $xml_request = '<?xml version="1.0\" encoding="utf-8" ?> <'.$call_name.'Request xmlns="urn:ebay:apis:eBLBaseComponents"> <RequesterCredentials> <eBayAuthToken>'.$auth_token.'</eBayAuthToken> </RequesterCredentials> </'.$call_name.'Request>'; // Send request to eBay and load response in $response $connection = curl_init(); curl_setopt($connection, CURLOPT_URL, $api_endpoint); curl_setopt($connection, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($connection, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($connection, CURLOPT_HTTPHEADER, $headers); curl_setopt($connection, CURLOPT_POST, 1); curl_setopt($connection, CURLOPT_POSTFIELDS, $xml_request); curl_setopt($connection, CURLOPT_RETURNTRANSFER, 1); $response = curl_exec($connection); curl_close($connection); // Create DOM object and load eBay response $dom = new DOMDocument(); $dom->loadXML($response); // Parse data accordingly. $ack = $dom->getElementsByTagName('Ack')->length > 0 ? $dom->getElementsByTagName('Ack')->item(0)->nodeValue : ''; $eBay_official_time = $dom->getElementsByTagName('Timestamp')->length > 0 ? $dom->getElementsByTagName('Timestamp')->item(0)->nodeValue : ''; echo $eBay_official_time;
That’s it. Less than 50 lines of code and we’re receiving information back from the eBay API. Now that we have this script put together we can use it as a template to make any API call we want with eBay. Let’s look at another example now that’s a little bit more involved.
GetItem
One of the API’s I find myself using quite a bit is GetItem. This call allows us to pull information about an eBay item so that we can display it within our application. Let’s walk through building a new script for GetItem.
First, since we’ll be following almost the same pattern we did with our first example, I’m going to open my GeteBayOfficalTime.php file and simply save-as GetItem.php. Then we just need to update the value for $call_name so it reads GetItem, update our XML request string to match our new API call, and parse out any additional information we need from the eBay response.
So do you remember what we’ll do to generate our new XML request? Open up our handy API reference for GetItem and see what our options are.
This time, we see that we can provide a lot more optional information with our request. Again, if you need information about any of the elements shown here you can click on the element name and it will provide detailed information about it.
Of course, we’ll need an eBay item that we’d like to pull information about, so if you’re working in the sandbox you’ll need a test item posted, or if you’re working with the production eBay servers you can use a live auction, of course. Then we can build our request according to the options we’d like to use from the API reference. This is what I decided to go with:
<?xml version="1.0" encoding="utf-8" ?> <GetItemRequest xmlns="urn:ebay:apis:eBLBaseComponents"> <RequesterCredentials> <eBayAuthToken>AgAAAA**AQAAAACOliJ39OSmbSS7Tjl</eBayAuthToken> </RequesterCredentials> <DetailLevel>ReturnAll</DetailLevel> <IncludeItemSpecifics>true</IncludeItemSpecifics> <IncludeWatchCount>true</IncludeWatchCount> <ItemID>270841694581</ItemID> </GetItemRequest>
This can be generated within our PHP script like this:
// Generate XML request
$xml_request = '<?xml version="1.0" encoding="utf-8” ?> <'.$call_name.'Request xmlns="urn:ebay:apis:eBLBaseComponents"> <RequesterCredentials> <eBayAuthToken>' . $auth_token . '</eBayAuthToken> </RequesterCredentials> <DetailLevel>ReturnAll</DetailLevel> <IncludeItemSpecifics>true</IncludeItemSpecifics> <IncludeWatchCount>true</IncludeWatchCount> <ItemID>270841694581</ItemID> </'.$call_name.'Request>';
With this request we are telling eBay the following things.
- We’d like to retrieve information about eBay item number 270841694581.
- We’d like to return all details, including item specifics and the current watch count for the item.
With our $xml_request string now updated for our new call we can go ahead and run our script. When we do so, we get back the following response from eBay.
As you can see, there is an awful lot of information available in this response pertaining to the item in question. For the purposes of this demonstration, let’s assume we’d simply like to pull the item price and description so we can display them within our application.
Now we’re ready to update our DOM section of our code to pull out the data we’re after. One thing worth mentioning here is that we already have a value for $eBay_official_time setup and this can actually stay in place without causing any issues. Every eBay request you make will return this by default. That’s another reason I chose to use this simple call as a template for all other calls.
So, let’s go ahead and pull out the price and the description using DOM.
$current_price = $dom->getElementsByTagName('ConvertedCurrentPrice')->length > 0 ? $dom->getElementsByTagName('ConvertedCurrentPrice')->item(0)->nodeValue : ''; $description = $dom->getElementsByTagName('Description')->length > 0 ? $dom->getElementsByTagName('Description')->item(0)->nodeValue : '';
I was able to find these element names by taking a quick look at the eBay response to see what I wanted. Any other information needed could be pulled by copying the line above and simply changing the variable and tag names accordingly.
Once you’ve pulled out all of the information you were after you’re free to update your local database, display the information on screen, send out notification emails about item status, or anything you might feel useful at this point.
Conclusion
We’ve come a long way since we began this journey in part 1. I’d like to reiterate that this style is not considered standard practice with PHP as it does not use class libraries or follow any sort of framework. That said, the code snippets used here could easily be added to a class and used with all your calls if you choose to do so. Everything here was meant to be a simple example of accomplishing these tasks without too much effort.
You may download the project files that were constructed during this article if you’d like to study them directly. I hope you got what you expected out this information, and I wish you happy coding on the eBay platform!
Excellent article. Well explained and to the point which is uncommon from a programmer who works with these APIs regularly. The biggest challenge of working with a new API can be just getting a simple example set up to execute so you can build from it. This was a great job at showing someone familiar with programming how to begin using the eBay API. I figured you’d have something good on this topic after coming across (from Google) your well-organized PayPal class.
Thanks Andrew, you saved my time and fingernails 🙂
Ha, thanks! I appreciate the kind words. I’m glad you found my library and this article helpful!
Excellent article. You managed a good practical explanation three large segments in one swoop. XML formatting, Curl connections, and SimpleXML are pretty useful contacting quite a few API’s. And I found the eBay specific information useful. Thanks
Glad you found it useful!
Hi Andrew,
I’m just getting into eBay integration and found the official documentation a little overwhelming!
In two pages, you’ve succinctly explained everything I needed to know and I’ve now been able to build my own requests using the API guides on eBay.
Thanks!
Glad to hear it helped! 🙂
Fantastic, been scared of eBay api for so long with your help i have taken the plunge and feel as i have a grip now!
Happy to hear it helped you out! 🙂
Thank you for this, the official eBay documentation is scary!
You have helped so much within 2 pages.
Glad it helped!
After hours of wading through the eBay API docs and samples, I still had no working example, just a head full of confusion. It was overwhelming to say the least. I, like many, just need a simple working example to build upon. You delivered that here. In minutes, not hours or days, I got a working example and now can build into what I want to actually do, download complete orders from eBay and place in my database.
Happy to hear it helped! 🙂
you brought my patience back! like a savior!
Happy to help!
This Article Serie is Definitely for any PHP rookie like you said in part 1 (y) (y) (y) thank you Andrew
SO what if We use oauth token instead of ebay token. I try to make “GetUser” request but I got 400 bad request error
It’s been a while since I have worked with eBay’s API, and the auth tokens weren’t available then. You should be able to use it, but may need to adjust headers or something. I’d have to get into those details to figure it out. Have you checked into that at all?
hi Andrew Angell , thank you for your tutorial.
but now. in december 2019, this work ?
the ebay php sdk work ?
is possible upload products with php ?
Yes, it still works. Did you try it? Are you having a particular problem I can try to help with?
As with everyone else, thanks for this!!
I thought I was the only one who found the official documentation a little overwhelming and all over the place.
Sometimes all we need is a simple example which we can build on from there – which is what you have done.
Glad you liked this tutorial. Happy to help!
This all works beautifully even today. Excellent job. I do find the shorthand PHP at the end a bit confusing though. That would be great in standard form if possible? Struggling to modify it to iterate through all returned records (orders). I’ve changed item(0) to item(1) etc to pull them out manually currently. Also should the Ack check stay in there all the time? Thanks!
Thanks for the feedback, I’ll try to improve that at some point. Glad you got it working, though. Yes, any time you make a request to the API I would check the ACK so you know the result before processing response data.
you have provided an amazing guide and well laid out. as a developer just stepping into APis, you have a skill at training / explaining / simplifying the process. many thanks
thank u for this post !!!
Happy it helped!
Forgive me I’m not very practical, I generated my token on production, but I saw that your script uses the sandbox version.
Am I getting confused?
The sandbox is just used for testing. Everything works the same in production.
Hello Drew,
I am very thankful for your wonderful tutorial on how to integrate eBay APIs with PHP.
How can we move away from auth_token that expires very quickly and then have to regenerate another? Isn’t there a way to Fetch a new Token with the FetchToken call? I don’t want to have to regenerate a new auth_token every 4 hrs or so. Your help would be very appreciated.
These API’s are actually now outdated, and I would suggest you move to the new REST API that they offer. Unfortunately, I don’t have a library built for that, but I think they provide a better one of their own now.
do you have a script to send messages to the user who purchased the product?
I don’t have anything readily available, and these scripts are rather old now. I would suggest you look into eBay’s new REST API’s, and look at their “platform notifications” or “webhooks”. You could automate messages based on different events.
Thank you so much for this tutorial! As a person familiar with PHP but not at all with APIs, this has been a very valuable help and starting point.