Amazon and Zend_Service_Amazon - Zend

You know what Amazon.com is and what it does: it sells books, clothing, and electronics (among other things), and it has become the leading online retail store. Amazon.com has recently opened its inventory to developers by creating the Amazon.com Associates Web Service (AWS), which allows developers to search and retrieve information regarding specific products.

The Amazon.com AWS allows developers to do the following:

  • Retrieve product descriptions based on keywords or by a specific Amazon Standard Identification Number (ASIN)
  • Retrieve product images
  • Retrieve customer reviews for specific products
  • Retrieve editorial reviews for specific products
  • Retrieve a list of similiar products
  • Retrieve special offers by Amazon.com
  • Retrieve ListMania listings

Having these features available enabled Zend Framework to create the Zend_ Service_ Amazon component by using both the Zend_HTTP_Client and Zend_Rest components of the framework to handle the web service communication shown below.

Zend_Service_Amazon object layers

It also consolidated commonly used features of the Amazon.com API to allow developers to simply pass in specific parameters, such as the ASIN of a product, and return the desired product detail; allowing developers to worry about their application instead of worrying about constructing the proper message for the type of protocol to use and dealing with exceptions that might arise.

Getting Started with the Amazon Service

Before you continue, you need to sign up for an Amazon.com developer account. Like all other developer accounts, it allows you to use the extensive collection of web services that Amazon.com offers.

To sign up, load the URL and click the Sign Up Now button on the page to create an Amazon.com user account. If you already have an Amazon.com account, log in. Once you have successfully signed up or logged in to your account, you will receive an e-mail with a URL. Click the URL to fetch a set of authentication items such as the AWS application ID, secret access key, and certificate file. You’ll need only the AWS access key ID.

With the AWS access key, Amazon.com allows the application to use the web services available from Amazon.com and identifies the application to Amazon.com (this access key is unique and should not be shared).

You’re now set. Open up the editor and try to search for an Amazon.com product using Zend Framework.

The code shown in Listing is a basic skeleton to test the access key as well as a simple example demonstrating how to fetch item information. You create a new test action named amazonTestAction() in the TestWSController.php file. The action will help you understand the different components required to do a simple and complex item search.

Listing amazonTestAction()

public function amazonTestAction()
{
try{
$amazon = new Zend_Service_Amazon('API_KEY', 'US');
$results = $amazon->itemSearch(array('SearchIndex' => 'Music',
'Keywords' => 'Motley Crue'));
foreach($results as $result){
echo $result->Title."<br>";
}
}catch(Zend_Exception $e){ throw $e; }
//Suppress the view $this->_helper->viewRenderer->setNoRender();
}

Zend Framework automatically loads the file that powers the Zend/Service/Amazon.php
service. You then create a new instance of a Zend_Service_Amazon object by passing in two parameters: the access ID created for you by Amazon.com and the country code you are accessing the data from. Once you instantiate the object, query the Amazon.com data set by executing the itemSearch() method on the Zend_Service_Amazon object. The itemSearch() method requires a key-value array with keys representing the different search-and-display criteria and the values for each criterion.

You call the web service and retrieve a Zend_Service_Amazon_ResultSet object. You iterate through the resulting result set using the foreach loop. The result set is a collection of Zend_Service_Amazon_Item objects, so you can access the item’s data using object attribute calls.

Pull up to see the results. If successful, you should see the list of items for sale that match the search, as shown in Figure.

List of Motley Crue music listings

Amazon.com Item Search

Take a look at Listing again. When you instantiated a Zend_Service_Amazon object, you intentio-nally used the second parameter:

Zend_Service_Amazon('API_KEY', 'US');

The first parameter is the access key ID, and the second parameter is your country. Amazon’s AWS allows you to use different country codes. You can request a service from France, Japan, Germany, or other locations by replacing the default country code, US, with any of the country codes listed in Table

Table Country Codes

The beauty of changing the country code is that it enables you to integrate the Amazon.com web services into a localized web application. If the application is targeted to a German audience or a Japanese audience, the web service call accesses products for the given country. After it fetches the data, it returns the result set in the spcific country language. It even changes the currency to the appropriate equivalent based on the country code.

Open the TestWSController.php file once more and create a new action amazonCountry CodeTest Action(). You will fetch items using the country code FR which returns the result set in French

Listing Setting the Country Code to France

public function amazonCountryCodeTestAction(){
try{
$amazon = new Zend_Service_Amazon('API_KEY', 'FR');
$results = $amazon->itemSearch(array('SearchIndex' => 'Music',
'Keywords' => 'Motley Crue'));
foreach($results as $result){
echo $result->Title."<br>";
}
}catch(Zend_Exception $e){ throw $e; }
$this->_helper->viewRenderer->setNoRender();
}

If you load the action in the browser you will see the new result set shown in Figure.

load the action in the browser you will see the new result

Searching for Items using ItemSearch

Using the code in Listing as a road map, let’s continue analyzing the components much more in depth. After you initialize the Zend_Service_Amazon object, you run a query by issuing the call temSearch(), which calls the ItemSearch web service in Amazon.

The itemSearch() method accepts one parameter as a key-value array. It allows you to search for products in the Amazon.com database and opens up additional operations that narrow down the search into specific categories, brands, and manufacturers.

By default, itemSearch() allows you to sort the result and set the maximum and minimum price of the products. Take a look at Table to see all acceptable key values.

Acceptable itemSearch() Table forU_S Country Code

Each of the parameters outlined in Table is supported by the majority of the searches, but other parameters can be used depending on the category in which you are searching. (You’ll take a look at these different combinations in the next section.)

The SearchIndex option allows you to determine in which category you want to conduct the search. In the example shown in Listing, you searched in the category Music, but you could have easily changed it to VideoGames or Toys.

Listing changes the search.

Listing Fetching Used PHP Book with Price Range from $10.00 to $20.00

public function amazonMultikeysTestAction(){
try{
$amazon = new Zend_Service_Amazon('API_KEY', 'US');
$results = $amazon->itemSearch(array('SearchIndex' => 'Books',
'Keywords' => 'PHP',
'Condition' => 'Used',
'MaximumPrice' => '2000',
'MinimumPrice' => '1000'));
foreach($results as $result){
echo $result->Title."<br>";
}
}catch(Zend_Exception $e){ throw $e; }
$this->_helper->viewRenderer->setNoRender();
}

Using five of the possible parameters outlined in Table, you use Keywords; SearchIndex; Condition; and both MaximumPrice and MinimumPrice. You change the category you want to search in from Music to Books, add the Condition key to fetch only the used books, and set the price range you prefer.

Narrowing Down the Search Using Combinations

You don’t get a feel for the power of the Amazon.com AWS Web Services API until you begin to narrow down the searches. Depending on the category you’re searching, you can open additional options to search. For example, if you want to search in the Books category, the additional options to specify the Publisher and Author would be available, as shown in Listing.

Listing Using Additional Combination Parameters

public function amazonSearchByPublisherTestAction(){ try{
$amazon = new Zend_Service_Amazon('API_KEY', 'US');
$results = $amazon->itemSearch(array('SearchIndex' => 'Books',
'Keywords' => 'PHP',
'Condition' => 'All',
'Publisher' => 'Apress'));
foreach($results as $result){
echo $result->Title."<br>";
}
}catch(Zend_Exception $e){ throw $e; }
$this->_helper->viewRenderer->setNoRender();
}

Listing contains a small update, but changes the result set that is returned from Amazon.com. Instead of returning all books with the keyword PHP, you narrow down the search to return the subset published by Apress from the result set containing the keyword PHP. To accomplish this, add the Publisher key with the value of Apress and allow the web service to do the rest.

A list of the commonly used U.S.-based category combinations is shown in Table.

U.S.-based category combinations

Sorting the Result Set

You can successfully and effectively return data from Amazon.com. Now let’s sort the data.Using the sorting criteria used in the itemSearch() array, you can search the result set by a number of values identified in Table. Much like the combination searches, sorting also depends on which category youfre searching and which country code you use.

Using the category, you can sort using the values relevancerank, salesrank, reviewrank, pricerank, and titlerank, among others. Listing uses the titlerank sorting value, which returns the result set alphabetically. Try it out.

Listing Sorting Books Alphabetically

public function amazonSortingBooksTestAction(){ try{$amazon = new Zend_Service_Amazon('API_KEY', 'US'); $results = $amazon->itemSearch(array('SearchIndex' => 'Books',
'Keywords' => 'PHP',
'Condition' => 'Used',
'Publisher' => 'Apress',
'Sort' => 'titlerank'));
foreach($results as $result){
echo $result->Title."<br>";
}
}catch(Zend_Exception $e){ throw $e; }
$this->_helper->viewRenderer->setNoRender();
}

Pull up the URL http://localhost/test/amazon-sorting-books-test to see the result set listed alphabetically.

The Zend_Service_Amazon_ResultSet also has additional operations that allow you to return the number of items retrieved and how many pages each result set contains, thereby giving you additional sorting features.

The totalResults() and totalPages() operations return the number of items the web service call found and how many pages of data were returned, respectively. Listing shows the total number of books published by Apress that Amazon.com is selling.

Listing Sorting the Result Set

public function amazonSortingBooksTestAction(){

try{

$amazon = new Zend_Service_Amazon('API_KEY', 'US');

$results = $amazon->itemSearch(array('SearchIndex' => 'Books',

'Keywords' => 'PHP',
'Condition' => 'Used',
'Publisher' => 'Apress',
'Sort' => 'titlerank',
'ItemPage' => '3'));
foreach($results as $result){
echo $result->Title."<br>";
}
}catch(Zend_Exception $e){ throw $e; }
echo "<br>";
echo "Total Books: ".$results->totalResults();
echo "<br>";
echo "Total Pages: ".$results->totalPages();
$this->_helper->viewRenderer->setNoRender();
}

The example in Listing shows a number of new items. For starters, you print out the total number of items and pages using the Zend_Service_Amazon_ResultSet’s totalPages() and totalResults() methods. By default, each page contains ten items. If you pull up the URL, you can see the number of Apress books (new and used) that Amazon.com is selling that contain the PHP keyword. By default, when you present the data, you pull from the initial page. But because there are multiple pages, use the ItemPage key and set the value. If you passed in a numerical value that is larger than the total number of pages available, you receive a 404 error.

The Zend_Service_Amazon_ResultSet contains additional operations for iterating through the result set.

additional operations for iterating through the result set

Searching for Similar Products

Let’s go into more advanced use of Amazon AWS by returning similar products. Refer to Table to view which key allows you to fetch similar products. Using the ResponseGroup key and specifying the Similarities value, the result set will return an array of Zend_Service_ Amazon_ SimilarProduct objects. Each object contains the attributes outlined in Table.

Searching for Similar Products

The power of the Zend_Service_Amazon library is that you need only two operations to make a call to fetch product information, and the only thing you have to worry about is which parameter fetches the proper data for you and how you can display the data. Listing demonstrates this by calling similar products for you. You use the ResponseGroup key and the Small value, which is the default ResponseGroup value and fetches all the standard data, and Similarities to return the similar titles. With the result set fetched, you now have the Zend_Service_Amazon_ResultSet’s SimilarProducts attribute. The attribute contains a collection of Zend_Service_ Amanzon_ Similar Products objects that can be accessed in a loop.

Listing Fetching Similar Products

public function amazonSimilarProductsTestAction()
{
try{
$amazon = new Zend_Service_Amazon('API_KEY', 'US');
$results = $amazon->itemSearch(array('SearchIndex' => 'Books',
'Keywords' => 'PHP',
'Condition' => 'Used',
'Publisher' => 'Apress',
'Sort' => 'titlerank',
'ItemPage' => '3',
'ResponseGroup' =>
'Small,Similarities'));
//Foreach item return the Similar Products
foreach($results as $result){
echo "<b>".$result->Title."</b><br>";
$similarProduct = $result->SimilarProducts;
if(empty($similarProduct)) {
echo "No recommendations.";
} else {
foreach($similarProduct as $similar){
echo "Recommended Books: ".$similar->Title."<br>";
}
}
echo "<br><br>";
}
}catch(Zend_Exception $e){ throw $e; }
echo "<br>";
echo "Total Books: ".$results->totalResults();
echo "<br>";
echo "Total Pages: ".$results->totalPages();
$this->_helper->viewRenderer->setNoRender();
}

Returning Product Reviews

Each of the products returned contains reviews, and also provides customer reviews of the product and reviews made by editors. The Zend Amazon service allows you to return each review as a Zend_Service_ Amazon_* Review object. If the review is a customer review, the object is a Zend_Service_ Amazon_ CustomerReview. If the review is an editor’s review, the object is a Zend_Service_ Amazon_ Editorial Review. Listing shows how to get the reviews.

Listing Returning Product Reviews from Amazon.com

public function amazonFetchReviewsTestAction()
{
try{
Zend_Loader::loadClass("Zend_Service_Amazon");
$amazon = new Zend_Service_Amazon('API_KEY', 'US');
$results = $amazon->itemSearch(array('SearchIndex' => 'Books',
'Keywords' => 'PHP',
'Condition' => 'Used',
'Publisher' => 'Apress',
'Sort' => 'titlerank',
'ItemPage' => '3',
'ResponseGroup' =>
'Small, Similarities,
Reviews, EditorialReview'));
//Foreach item return the Similar Products
foreach($results as $result){
echo "<b>".$result->Title."</b><br>";
//Fetch the Customer Reviews and display the content.
$customerReviews = $result->CustomerReviews;
if(empty($customerReviews)) {
echo "No customer reviews.<br>";
} else {
foreach($result->CustomerReviews as $customerReview){
echo "Review Summary: ".$customerReview->Summary."...<br>";
}
}
$similarProduct = $result->SimilarProducts;
if(empty($similarProduct)) {
echo "No recommendations.";
} else {
foreach($similarProduct as $similar){
echo "Recommended Books: ".$similar->Title."<br>";
}
}
echo "<br><br>";
}
}catch(Zend_Exception $e){ throw $e; }
echo "<br>";
echo "Total Books: ".$results->totalResults();
echo "<br>";
echo "Total Pages: ".$results->totalPages();
$this->_helper->viewRenderer->setNoRender();
}

Let’s go over the code in Listing. Because you know all the basic building blocks to create a call to the web service, let’s focus on the changes to fetch the customer reviews. First look at the Reviews string appended to the ResponseGroup value. This returns the product reviews, along with all the data you request. With the result set returned, call the Customer Reviews ResultSet attributes. The return value is a collection of Zend_ Service_ Amazon_ Customer Review objects.

To display the customer reviews, loop through each element in the $customerReviews array, and display the date and the summary by calling the Zend_ Service_ Amazon_ Customer Review Summary and Date attributes.

Run the new update to the code by calling the same URL, and you should now see the title of the book, similar products, and all reviews for the product.

Each of the review objects contains different atributes that you can use to display the content of the review. Table shows all the available attributes that the Zend_Service_ Amazon_ CustomerReview class contains.

Table Zend_Service_Amazon_Customer Reviews

Zend_Service_Amazon_EditorialReview

Editorial reviews can be retrieved and displayed like customer reviews. The only difference is that you have to add in EditorialReviews to the ResponseGroup.

The result is a collection of Zend_Service_Amazon_EditorialReview objects that can be accessed by calling the Zend_Service_Amazon_ResultSet attribute Editorial Review. The Editorial Review class has the attributes shown in Table.

Zend_Service_Amazon_EditorialReview

Looking Up Specific Items

So you want to drill down a bit more and just want to return a specific Amazon product? The Zend_Service_Amazon library provides you with such a operation: itemLookup().

itemLookup(String ASIN, array)

The initial parameter is the ASIN, which can be found by doing a search using the item Search() method. It returns the ASIN in the result set for each product or it can be located by navigating through the Amazon.com site and locating the product using the portion

The second parameter, which is optional, allows you to set sorting and return value information. It is identical to the key-value array in the itemSearch() method.

The itemLookup() example shown in Listing changes the way you retrieve data from Amazon.com. This example looks up data for this book with the 1430218258 ASIN number.

Listing itemLookUp() Example

public function amazonLookupTestAction()
{
try{
$amazon = new Zend_Service_Amazon('API_KEY', 'US');
$results = $amazon->itemLookup("1430218258",
array('Condition' => 'Used',
'Publisher' => 'Apress',
'ResponseGroup' =>
'Small,Similarities,Reviews,EditorialReview'));
echo "<b>".$results->Title."</b><br>";
}catch(Zend_Exception $e){ throw $e; }
$this->_helper->viewRenderer->setNoRender();
}

When using itemLookup(), you still separate search criteria with a comma, but there should be no whitespace in the string as there was in other examples.

The result set contains only a single Zend_Service_Amazon_Item object, which has the attributes shown in Table.

Table The Zend_Service_Amazon_Item Object

LoudBite: Adding Amazon Product Information

Now you have more than enough of a foundation to add additional functionality to the application you’ve created throughout this book. You can now add a product module to the site. The product module presents users with a set of products they might find interesting depending on the music they enjoy and the groups they have in their favorites list. The module pulls in CD, music, and apparel information from Amazon.com, and displays a small image and summary of the product, orders the products by “coolness” and displays a link where the user can purchase the product on Amazon.com.

First, you need to create the controller and actions for the pages. You will create a new controller called ProductController.php; you don’t want to give the impression that it’s a store because people will be standoffish if they think you’re selling them something. The Product Controller will contain two actions: a quickProductDisplayAction() and an indexAction(), as shown in Listing.

Listing ProductController: indexAction()

public function indexAction()
{
//Get the artist name from the request.
$artistName = $this->_request->getParam("artistName");
//If there is no artist name in the request send the user to an oops page
if(empty($artistName)){
throw new Exception("Oh man i think you broke something. No not really,
you just got here by mistake.");
}
try{
$amazon = new Zend_Service_Amazon('API_KEY', 'US');
//Get the apparel t-shirts items
$apparelItems = $amazon->itemSearch(
array('SearchIndex' => 'Apparel',
'Keywords' => $artistName.' t-shirt',
'ResponseGroup' => 'Small, Images'));
//Get the music tracks
$cds = $amazon->itemSearch(array('SearchIndex' => 'Music',
'Artist' => $artistName,
'ResponseGroup' => 'Small, Images'));
//Get the posters
$posters = $amazon->itemSearch(array(
'SearchIndex' => 'HomeGarden',
'Keywords' => $artistName.' posters',
'ResponseGroup' => 'Small, Images'));
//Set the view variables
$this->view->products = $apparelItems;
$this->view->cds = $cds;
$this->view->posters = $posters;
}catch(Zend_Exception $e){ throw $e; }
}

The new ProductController contains the indexAction() method, which allows you to fetch three types of items from Amazon.com:

  • CDs for an artist
  • T-shirts for an artist
  • Posters for an artist

Use the itemSearch() operation for all three instances. Before you reach these calls, see whether the artist name was supplied. The artist name is retrieved from inside the request; if it is empty, you redirect the user to a general error page. Once you return the data for each itemSearch() call, you initialize three view variables to use in the view: $cds, $products, and $posters. These steps are shown in Listing.

Listing ProductController: quickProductDisplayAction()

public function quickProductDisplayAction(){
//Get the artist name from the request.
$artistName = $this->_request->getParam("artistName");
//If there is no artist name in the request send the user to an oops page
if(empty($artistName)){
throw new Exception ("Oh man i think you broke something. No not really,
you just got here by mistake.");
}
try{
$amazon = new Zend_Service_Amazon('API_KEY', 'US');
//Get the Music tracks
$cds = $amazon->itemSearch(array('SearchIndex' => 'Music',
'Artist' => $artistName,
'ResponseGroup' => 'Small, Images'));
//Set the view variables
$this->view->products = $cds;
}catch(Zend_Exception $e){ throw $e; }
}

The quickProductDisplayAction() method is not as extensive as indexAction(); you don’t have to do any extensive querying for different items because you simply want to fetch the artist’s CDs and display them. You use the itemSearch() method again and pass in the Artist key, select the category Music, and ask for both the default data as well as the image data in the returned information. On to the display.

The first files you need to create are the quick-product-display.phtml and index.phtml files within the application/views/scripts/product directory. The files will act as the views to display the data.

The quick-product-display.phtml file is a small module that will display up to ten products on the user’s profile page. The index.phtml file is the view that will display a complete collection of CDs, apparel items, and posters the user can purchase. Both pages are linked from a View More Items link in the user’s profile page and the artist profile page.

Listing quick-product-display.phtml

<?php echo $this->doctype('XHTML1_STRICT'); ?>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<?php echo $this->headTitle('Loudbite.com - Artist Products'); ?>
</head>
<body>
<?php echo $this->render("includes/header.phtml")?>
<?php if($this->products->totalResults()){ ?>
<table border="1" width="300">
<tr><td colspan="2">You might be interested in these items</td></tr>
<?php foreach($this->products as $product){?>
<tr><td><img src="<?php echo $product->SmallImage->Url ?>" width="50"
height="50"></td>
<td>
href="<?php echo $product->DetailPageURL ?>"><?php echo $product->Title ?>
</td></tr>
<?php } ?>
</table>
<?php } ?>
</body>
</html>

Once you save the file, you will see a list of CDs for the band Guns n’ Roses. The index.phtml page is very similar except you build a table of posters and T-shirts as well as CDs. Create the index.phtml file within the application/views/scripts/product directory by copying the code shown in Listing, saving it, and then loading. That’s all there is to it!

You’ve learned about the latest web service technology as well as how Zend Framework uses its built-in web service components to talk with external applications such as YouTube to expand on your application. Now let’s focus on how to provide additional content on the site using syndicated content with RSS feeds.

All rights reserved © 2020 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

Zend Topics