ONLamp.com    
 Published on ONLamp.com (http://www.onlamp.com/)
 See this if you're having trouble printing code examples


Programming eBay Web Services with PHP 5 and Services_Ebay

by Adam Trachtenberg
01/27/2005

Over the last ten years, eBay has emerged as a platform where people can buy and sell practically anything. With more than 135 million users worldwide, eBay is a thriving online marketplace. Best of all, eBay isn't constrained by HTML. By using eBay's web services APIs, members of the eBay Developers Program can hook into the eBay platform using XML to integrate eBay into their own applications.

Like many web services, the eBay API comes in multiple flavors. There's the original XML-over-HTTPS POST interface, a format that's quite similar to REST. There's also a newer, more fashionable SOAP interface, which uses the Doc/Literal format.

Both have their own benefits and weaknesses. Pure XML is easy to produce and consume on any platform, something that's vital given the shaky state of PHP's SOAP support. However, SOAP has the advantage of eliminating the trouble of manually parsing XML into usable data structures.

PHP programmers have a third alternative, which combines the best parts of both interfaces: Services_Ebay. Written primarily by Stephan Schmidt, Services_Ebay is a PEAR package that wraps around the XML API to provide an object-oriented interface to eBay. Additionally, it takes advantage of several new PHP 5 features to create powerful code that's simple to use. You can't run this code under PHP 4 because PHP 5 plays such a key role.

This article demonstrates how to use Services_Ebay to search eBay and display results, similar to what an eBay affiliate might write. In the process, it gives a small taste of what you can begin to do with the package. Additionally, it shows off a real-world implementation of a PHP 5 program, one that showcases many of the reasons to upgrade from PHP 4 to PHP 5. Throughout the piece, I highlight all the places where a PHP 5 feature has come into play, so you can see where PHP 5 makes a real difference.

Installing

Before you can use Services_Ebay, you need to install it using the PEAR package manager tool. The easiest way to do this is with the upgrade -a command:

$ pear upgrade -a Services_Ebay-alpha

The upgrade -a flag causes PEAR not only to install Services_Ebay but also to automatically upgrade all package dependencies. The -alpha portion at the end lets PEAR know that it's OK to install an alpha version of the package, which is necessary because Services_Ebay is not yet tagged as stable.

Configuring

Now that you've installed Services_Ebay, you need to configure it with your authentication credentials. This is developer-specific information that allows eBay to identify you and your application.

require_once 'Services/Ebay.php';

// load authentication data from config file 
$config = parse_ini_file('ebay.ini');

// pass authentication data to Services_Ebay
$session = Services_Ebay::getSession($config['devId'],
                                     $config['appId'],
                                     $config['certId']);

$session->setToken($config['authToken']);
$session->setUrl(Services_Ebay_Session::URL_PRODUCTION);

After including the Services_Ebay package, the code loads in a configuration file, ebay.ini, using parse_ini_file(). This file contains the credentials you must provide when making an eBay services API call. Specifically, these are your:

The first three authentication credentials are collectively developer keys, and they identify the developer that's contacting eBay.

The fourth, Auth & Auth Token, identifies the user making the request without exposing her username and password. This person is frequently distinct from the application's developer, and the feature allows programmers to write applications for others to use without compromising security.

To acquire your own credentials, sign up for the eBay Developers Program.

Now that you have the data loaded, the next step is to create an eBay web services session. This session is an object that holds your credential data. Create a session by calling Services_Ebay::getSession() and passing your keys as arguments. In this case, the keys are in the $config array created by parse_ini_file().

The next two steps modify the session to set the Auth & Auth Token and the URL of the web service by using the setToken() and setUrl() methods. By default, the session points itself at eBay's testing server (known as the Sandbox). To override this value and direct the server at the live Production site, pass the Services_Ebay_Session::URL_PRODUCTION constant.

Searching

With the session configured, it's time to create the Services_Ebay object used to make eBay web services API calls. Instantiate a new instance, passing $session to the constructor.

// create new proxy object
$ebay = new Services_Ebay($session);

// search eBay
$searchTerms = 'new ipod mini';
$items = $ebay->GetSearchResults($searchTerms);

// print the results
foreach ($items as $item) {
	echo $item;
	echo "<br />";
}

Related Reading

Upgrading to PHP 5
By Adam Trachtenberg

Now you can go ahead and search eBay using the GetSearchResults() method, or GSR for short. The easiest way to use GSR is to pass a single argument: your search terms. Here you're searching for a "new ipod mini".

Calling this method causes Services_Ebay to construct an XML web services request, contact eBay's servers, fetch a response, and then return the returned items in $items. In many ways, this process is similar to what occurs when you use a SOAP client; however, it has the benefits of being able to extend beyond the definitions in the WSDL file.

You can't tell from the code, but the Services_Ebay class doesn't actually define the GSR method. Instead, Services_Ebay uses the magical __call() method to trap the method invocation and automagically load in and execute the appropriate code. In PHP 5, you can define a method named __call(); then, any time you call an unimplemented method, PHP will invoke __call() instead of dying an ugly death.

Normally, once you've retrieved a list of search results, you want to loop through them and print them out. That's why the $items object uses a new PHP 5 feature, iterators, to allow to you cycle through the items inside of a foreach() loop.

Inside the foreach(), you receive an $item, which is an object that represents an eBay item. This class uses yet another PHP 5 feature that allows you to specify an object's "stringification." When you print or echo an object, PHP calls the object's __toString() method and displays what it returns.

Printing out a list of search results is a piece of cake:

// print the results
foreach ($items as $item) {
	echo $item;
	echo "<br />";
}

A list of search results
Figure 1. A list of search results

There's no need to extract the individual items from the object, nor to retrieve their individual properties to create a string description. It's all encapsulated inside the class, and accessible using regular PHP language constructs.

Beautifying

Of course, that's not a very visually appealing display, but you can fix this problem with only a little bit of code:

require_once 'Services/Ebay/Model/Item.php';

class prettyItem extends Services_Ebay_Model_Item {
	public function __toString() {
		$title = $this->Title;
		$img   = $this->ItemProperties['GalleryURL'];
		$price = $this->LocalizedCurrentPrice;
		$link  = $this->Link;
		$time  = $this->EndTime;
		$bids  = $this->BidCount;
	
		// skip items without a gallery picture
		if (empty($img)) { return ''; }
		
		return <<<_HTML_
<div style="clear:left; width: 450px; padding:5px; margin:5px; background:#ddd;">
    <a href="$link"><image src="$img" 
      alt="$title" align="left" height="77" width="77" /></a>
    <b>$title</b><br/>
    Current Price: $price<br/>
    Number of Bids: $bids<br/>
    Ending Time: $time<br />
</div>
_HTML_;
	}
}

Services_Ebay::useModelClass('Item', 'prettyItem');

Services_Ebay uses a series of "model classes" to handle the dirty work of abstracting away the details behind the individual API calls. When GSR returns a list of eBay items, Services_Ebay instantiates Item models for each listing. Even better, it allows you to override the model to add or redefine methods to fix your application needs.

In this case, you're modifying the Item model's __toString() method to update the default display to a more attractive one.

First, you need to load the class, Services_Ebay_Model_Item, located inside the Models directory in Item.php. Once it's loaded, you can subclass it using the standard PHP extends syntax. In this example, the child class is prettyItem.

Inside of prettyItem::__toString(), a set of lines combines Item properties--including the title, price, and link--into a set of HTML elements.

The final step is to tell Services_Ebay to substitute your new model class for the default one. To do this, call the Services_Ebay::useModelClass() method. The first value is the model name; the second is the name of the replacement class.

Now, when you print out items, you'll have an entirely new picture:

	foreach ($items as $item) {
		echo $item;
	}

A new list of search results
Figure 2. A new list of search results

Notice that you didn't need to modify any of the logic for cycling through the items or for printing them out.

Introspecting

Besides creating an iterable list of items, GSR returns additional information about your search. For instance, while GSR returns a maximum of 100 items per call, it does allow you to "paginate" your request. This allows you to make one request for items 1-100, a second for 101-200, and so on.

In order to do this, however, you need to know the total number of potential results. This is available as an object property:

print $items->GrandTotal;
1153

Alternatively, you can use array syntax if you prefer:

print $items['GrandTotal'];
1153

These bits of syntactical sugar again use new PHP 5 features: the accessor method, __get(), and SPL's ArrayAccess interface, respectively.

To access all the properties at once, retrieve them using the toArray() method:

print_r($items->toArray());

Array
(
    [Count] => 100
    [HasMoreItems] => 1
    [GrandTotal] => 1155
    [PageNumber] => 1
)

This method exposes everything: the count of the items returned, whether there are any more items to fetch, the total number of available items, and the "page number" within the search results.

The ability to call methods on $items is one of the advantages of using an iterable object instead of an array. With an array, you're just holding a set of individual items. Now, you can provide collection of items, packaged more tightly as parts of a whole.

On the flip side, it's useful to know what parameters GSR takes. Earlier on, I said that the first argument is the search string, but GSR actually takes up to five parameters. You could read the documentation or flip through the code, but Services_Ebay wants to make things really easy.

Therefore, every API call has a describeCall() method, which lets you retrieve a method's parameters from within the code itself:

$call = Services_Ebay::loadAPICall('GetSearchResults');
$call->describeCall();

API-Call : GetSearchResults

Parameters (max. 5)
 Query(no default value)
 SearchInDescription(no default value)
 Skip(no default value)
 MaxResults(no default value)
 Category(no default value)

API Documentation : http://developer.ebay.com/DevZone/docs/API_Doc/
Functions/GetSearchResults/GetSearchResultsLogic.htm

As you see, describeCall() returns three pieces of information:

This not only lets you figure out how Services_Ebay has modeled a call but also points you directly to the official eBay documentation, so you can read the definitive reference.

Surprisingly, even describeCall() uses a new PHP 5 feature: reflection. PHP 5's reflection classes let you retrieve information about classes and functions in a programmatic fashion. In this example, the documentation URL actually comes from a specially formatted comment above the class that phpDocumentor, an auto-documentation tool for PHP, can read. With PHP 5 you can extract these comments without reading and parsing the class file yourself by instantiating a class and invoking a single method, getDocComment().

Conclusion

You've just seen how easy it is to write a eBay web services search application in PHP with the help of Services_Ebay. Services_Ebay uses much of the power of PHP 5: the whole spectrum of the new object model, the rewritten XML and XSL extensions, iterators and SPL, reflection, and exceptions. These components combine to create a kick-ass tool that PHP 4 can't replicate without lots of work, if at all.

Furthermore, the eBay API is not restricted to read-only calls, such as searching for and viewing listings. You can do almost everything through the API, including listing items, giving and checking feedback, managing eBay Stores, retrieving data from your My eBay page, and setting preferences. Services_Ebay supports most of these calls today and is quickly adding the rest.

As a result, now's a great time for PHP developers to start exploring the power of the eBay API.

Adam Trachtenberg is the manager of technical evangelism for eBay and is the author of two O'Reilly books, "Upgrading to PHP 5" and "PHP Cookbook." In February he will be speaking at Web Services Edge 2005 on "Developing E-Commerce Applications with Web Services" and at the O'Reilly booth at LinuxWorld on "Writing eBay Web Services Applications with PHP 5."


Return to the PHP DevCenter.

Copyright © 2009 O'Reilly Media, Inc.