Utilizing the Amazon API


Developer tag in hand, you are now ready to start working with Amazon's API. The big choice that you're going to need to make early on is whether you want to work with it via its REST interface or the SOAP interface. Both provide similar functionality; the difference is going to be how you access it. While researching this book, I encountered countless examples utilizing the REST interface, and very few demonstrating the SOAP interface. To get the most out of this chapter, I've decided to take the opposite stance — this chapter concentrates on SOAP with only a brief introduction to REST.

Sample REST Search

Performing any API call over REST, especially during testing, should be quite easy. First, create a simple web form pointing to the appropriate URL, and set the form to use the GET method. Create hidden form variables for any required elements, and use a text box for any user-specified elements. For example, using the following page and entering a search for paul reinheimer will constitute a valid, and useful, REST request:

 <html> <head> <title>Rest Sample</title> </head> <body> <form method="get" action="http://webservices.amazon.com/onca/xml"> <input type="hidden" name="t" value="preinheimerco-20"> <input type="hidden" name="Service" value="AWSECommerceService"> <input type="hidden" name="SubscriptionId"value="1PHH5VTRY7D300H7JTR2"> <input type="hidden" name="Operation" value="ItemSearch"> <input type="hidden" name="SearchIndex" value="Books"> <input type="text" name="Keywords" value="Books"> <input type="submit" name="submit" value="post"> </form> </body> </html> 

Most of the parameters there are self-explanatory, but a few could do with some explanation. The parameter named t with a value of preinheimerco-20 contains my associate ID (from joining the Amazon Associates program), which will allow the API to encode resultant URLs with my ID for revenue tracking. The SubscriptionID and value represent my developer key, necessary for all requests. Operation indicates what type of request I am performing this time — an ItemSearch — and SearchIndex indicates that I want to search only Amazon's book inventory this time. Finally, the text input field allows users to enter their own search Keywords.

The result from Amazon is quite verbose, but still readable. First some basic information about the request is returned, followed by the actual result items. Each item contains an ASIN (Amazon Standard Identification Number), the URL for the item, a title, and other basic information. In the following request, the authors of the book are returned.

 <?xml version="1.0" encoding="UTF-8"?> <ItemSearchResponse xmlns="http://webservices.amazon.com/AWSECommerceService/2005-01-19"> <OperationRequest>  <HTTPHeaders>   <Header Name="UserAgent" Value="Mozilla/5.0 (Windows; U; Windows NT 5.1;     rv:1.7.3) Gecko/20041001 Firefox/0.10.1"></Header>  </HTTPHeaders>  <RequestId>0JQ4GT363KKWN5RBNS6X</RequestId>  <Arguments>   <Argument Name="Service" Value="AWSECommerceService"></Argument>   <Argument Name="submit" Value="post"></Argument>   <Argument Name="SearchIndex" Value="Books"></Argument>   <Argument Name="t" Value="preinheimerco-20"></Argument>   <Argument Name="SubscriptionId" Value="1PHH5VTRY7D300H7JTR2"></Argument>   <Argument Name="Keywords" Value="paul reinheimer"></Argument>   <Argument Name="Operation" Value="ItemSearch"></Argument>  </Arguments>  <RequestProcessingTime>0.0342471599578857</RequestProcessingTime> </OperationRequest> <Items>  <Request>   <IsValid>True</IsValid>   <ItemSearchRequest>    <Keywords>paul reinheimer</Keywords>    <SearchIndex>Books</SearchIndex>   </ItemSearchRequest>  </Request>  <TotalResults>1</TotalResults>  <TotalPages>1</TotalPages>  <Item>   <ASIN>0764589547</ASIN>   <DetailPageURL>http://www.amazon.com/exec/obidos/redirect?tag=ws%26link_code=xm2   %26camp=2025%26creative=165953%26path=http://www.amazon.com/gp/redirect.html%253f   ASIN=0764589547%2526location=/o/ASIN/0764589547%25253FSubscriptionId=1PHH5VTRY7   D300H7JTR2</DetailPageURL>   <ItemAttributes>    <Author>Paul Reinheimer</Author>    <Author>Chris Shiflett</Author>    <ProductGroup>Book</ProductGroup>    <Title>Professional Web APIs with PHP: eBay, Google, Paypal, Amazon, FedEx plus      Web Feeds</Title>   </ItemAttributes>  </Item> </Items> </ItemSearchResponse> 

This request only returned a single result (item). Had there been more results, the item tag would have repeated.

As you can see, the elements required to perform a transaction using REST are relatively straightforward. It would have been trivial to retrieve the result document with file_get_contents() (or any of a number of similar constructs) and parse the XML with a tool like SimpleXML or MiniXML. You would then be able to present results to the user in an attractive manner. Alternatively, you could use an XSLT stylesheet to directly translate the result set into a user-accessible document.

The remainder of this chapter concentrates on the SOAP interface to the Amazon API. The REST services are quite well documented, and there is an abundance of sample code already available. My hope is that by providing samples for SOAP, which presently seem to be lacking, you will be better able to use the API in whatever manner you wish.

Performing Searches with SOAP

Amazon breaks the mold set by most major APIs in presenting access to its database through both SOAP and REST. Both request types allow access to essentially the same internal functions, the key difference being the structure of the request.

When exploring complicated APIs, it is often very useful to be presented with an easy-to-read list of available queries. To that end I would recommend taking a look at the Generic Soap Client available at http://soapclient.com/SoapTest.html. Give it the URL to any .wsdl file, and it will display the different available requests and the parameters for each request. It also goes the additional step of allowing you to actually make the query, in which case it will display either the request or response depending on your selection.

A Simple Search Request

Performing the same search as used in the REST request using SOAP requires a slightly different approach:

 <?php require('../lib/nusoap.php'); $client = new soapclient("http://soap.amazon.com/schemas2/AmazonWebServices.wsdl", true); 

The NuSOAP libraries are included and the $client object is created. The .wsdl file here is for the U.S. version of the API. Different .wsdl documents are used for the regional sites.

 $query = array(              'keyword'    => 'paul reinheimer',              'page'        => 1,              'mode'        => 'books',              'tag'         => 'preinheimerco-20',              'type'        => 'lite',              'devtag'      => '1PHH5VTRY7D300H7JTR2' ); 

The query itself is generated. The same search is being performed as in the REST request. Notice the additional element type, set to lite. The same request performed with the heavy tag instead of the lite tag is presented shortly.

 $namespace = 'http://soap.amazon.com'; $action = 'http://soap.amazon.com'; $method = "KeywordSearchRequest"; $result = $client->call($method,   array('KeywordSearchRequest' => $query),   $namespace, $action); print_r($result); ?> 

Finally the namespace, action, and method are defined and the query is run against the API server. The results are printed, and shown here:

 Array (   [TotalResults] => 1   [TotalPages] => 1   [Details] => Array   (     [0] => Array     (       [Url] => http://www.amazon.com/exec/obidos/ASIN/0764589547/         preinheimerco-20?dev-t=1PHH5VTRY7D300H7JTR2%26camp=2025%26link_code=sp1       [Asin] => 0764589547       [ProductName] => Professional Web APIs with PHP: eBay, Google, Paypal,         Amazon, FedEx plus Web Feeds       [Catalog] => Book       [Authors] => Array       (         [0] => Paul Reinheimer         [1] => Chris Shiflett       }       [ReleaseDate] => 18 July, 2005       [Manufacturer] => John Wiley & Sons       [ImageUrlSmall] => http://images.amazon.com/images/P/0764589547.01.THUMBZZZ.jpg       [ImageUrlMedium] => http://images.amazon.com/images/P/0764589547.01.MZZZZZZZ.jpg       [ImageUrlLarge] => http://images.amazon.com/images/P/0764589547.01.LZZZZZZZ.jpg       [Availability] => This item is currently not available.     )   ) ) 

The results returned are very similar to what you saw with the REST request. Note that the SOAP request isn't prepended with your original request.

Note 

I have used my name as an example for a search to ensure the result listing is brief; however, because the book isn't actually available yet, you may have noticed some fields are missing, namely the price. Available products will contain a ListPrice element. Note that this is indeed the list price, which is likely higher than Amazon's actual selling price. Amazon's selling price is available via a heavy request.

Using the previous code, but replacing the lite type tag with heavy, gives the following:

 Array (   [TotalResults] => 1   [TotalPages] => 1   [Details] => Array   (     [0] => Array     (       [Url] => http://www.amazon.com/exec/obidos/ASIN/0764589547/         preinheimerco-20?dev-t=1PHH5VTRY7D300H7JTR2%26camp=2025%26link_code=sp1       [Asin] => 0764589547       [ProductName] => Professional Web APIs with PHP: eBay, Google, Paypal,         Amazon, FedEx plus Web Feeds       [Catalog] => Book       [Authors] => Array       (         [0] => Paul Reinheimer         [1] => Chris Shiflett       )       [ReleaseDate] => 18 July, 2005       [Manufacturer] => John Wiley & Sons       [ImageUrlSmall] => http://images.amazon.com/images/P/0764589547.01.THUMBZZZ.jpg       [ImageUrlMedium] => http://images.amazon.com/images/P/0764589547.01.MZZZZZZZ.jpg       [ImageUrlLarge] => http://images.amazon.com/images/P/0764589547.01.LZZZZZZZ.jpg       [BrowseList] => Array       (         [0] => Array         (             [BrowseName] => Computer Programming         )         [1] => Array         (             [BrowseName] => Computers / Programming / General         )       )       [Media] => Paperback       [Isbn] => 0764589547       [Availability] => This item is currently not available.     )   ) ) 

More information is returned, such as the ISBN and Amazon's categorization of the item. The information returned in this request is rather slim because the book hasn't been released yet. When available, a heavy request will include information like similar products, user comments, and an array of applicable browse listings.

Presenting Results

Presenting the results from a given search in a usable manner isn't much more difficult. The query against the API will be performed as before (though with different criteria), but this time, rather than using print_r() to view the results, the results will be iterated through, and outputted with accompanying HTML:

 <?php require('../lib/nusoap.php'); $client = new soapclient("http://soap.amazon.com/schemas2/AmazonWebServices.wsdl", true); $params = array(              'keyword'    => 'elements of style',              'page'        => 1,              'mode'        => 'books',              'tag'         => 'preinheimerco-20',              'type'        => 'heavy',              'devtag'      => '1PHH5VTRY7D300H7JTR2' ); $namespace = 'http://soap.amazon.com'; $action = 'http://soap.amazon.com'; $method = "KeywordSearchRequest"; $result = $client->call($method,   array('KeywordSearchRequest' => $params),   $namespace, $action); $resultItems = $result['Details']; foreach ($resultItems AS $item) {   $title = $item['ProductName'];   $url = $item['Url'];   $image = $item['ImageUrlSmall'];   $authorList = implode($item['Authors'], ", ");   $price = $item['ListPrice'];   echo "<img src=\"$image\" align=\"left\">";   echo "<a href=\"$url\" title=\"Learn More at Amazon.com\">$title<a><br>";   echo "Author(s): " . $authorList . "<br>";   echo "List Price: " . $price;   echo "<hr>"; } ?> 

Here a basic foreach() loop iterates through each of the result items, and variables are created for each of the desired result elements. This is done mainly for clarity and compatibility with the size of this printed page; generally I would use something more like this:

 echo "<a href=\"{$item['Url']}\" title=\"Learn More at Amazon.com\">{$item['ProductName']}<a><br>"; 

This is a little harder to read, but it saves on a variable assignment. The implode() function is very useful here, quickly turning the array of authors into a comma-delimited string. The output of this function shows the results of a search for "elements of style," shown in Figure 7-1.

image from book
Figure 7-1

Usable Search Page

Previous examples worked well and began to explore some of the functionality that the Amazon API presents; however, they did not include any error checking, and used hard-coded search terms and criteria. As already mentioned, it is always best not to trust any external content just in case — you never know what you are going to get.

Accordingly, the following program allows an end user to search for products. Functionally, the program will have three main components: presenting the search form and validating passed data, performing the query, and presenting the results.

Different product types contain different information — books have authors, movies have stars, and music has artists. As such, results will be passed to one of three different functions, one each for the different search types presented.

 function displayBook($resultItems) {   foreach ($resultItems AS $item)   {     $title = $item['ProductName'];     $url = $item['Url'];     $image = $item['ImageUrlSmall'];     $authorList = implode($item['Authors'], ", ");     $price = $item['ListPrice'];     if ($url != "") echo "<img src=\"$image\" align=\"left\">";     echo "<a href=\"$url\" title=\"Learn More at Amazon.com\">$title<a><br>";     echo "Author(s): " . $authorList . "<br>";     echo "List Price: " . $price;     echo "<hr>";   } } 

The displayBook() function is identical (except for the function wrapping) to the code shown in the previous example.

 function displayDVD($resultItems) {   foreach ($resultItems AS $item)   {     $title = $item['ProductName'];     $url = $item['Url'];     $image = $item['ImageUrlSmall'];     $stars = @implode($item['Starring'], ", ");     $price = $item['ListPrice'];     if ($url != "") echo "<img src=\"$image\" align=\"left\">";     echo "<a href=\"$url\" title=\"Learn More at Amazon.com\">$title<a><br>";     if ($stars != "") echo "Starring: " . $stars . "<br>";     echo "List Price: " . $price . "<br><br>";     echo "<hr>";   } } 

For DVDs, the Starring value is imploded to be displayed.

 function displayCD($resultItems) {   foreach ($resultItems AS $item)   {     $title = $item['ProductName'];     $url = $item['Url'];     $image = $item['ImageUrlSmall'];     $artists = implode($item['Artists'], ", ");     $price = $item['ListPrice'];     if ($url != "") echo "<img src=\"$image\" align=\"left\">";     echo "<a href=\"$url\" title=\"Learn More at Amazon.com\">$title<a><br>";     echo "Artist(s): " . $artists . "<br>";     echo "List Price: " . $price;     echo "<hr>";   } } 

For CDs, the artist's value is again imploded for display.

Although the differences presented here are not too significant, using different functions for different object types does allow a lot of flexibility. Displaying Director in the DVD function would be trivial, as would choosing to display the label for music or the publisher for books. It's important not to feel constrained to displaying the data common across all types when working with the API, because there is such a great variety. That being said, further examples in this chapter concentrate on books; the code for other result types tends to be repetitive.

 function runSearchQuery($client, $keywords, $page, $mode, $type = 'lite') {   $params = array(     'keyword'    => $keywords,     'page'        => $page,     'mode'        => $mode,     'tag'         => 'preinheimerco-20',     'type'        => $type,     'devtag'      => '1PHH5VTRY7D300H7JTR2'   );   $namespace = 'http://soap.amazon.com';   $action = 'http://soap.amazon.com';   $method = "KeywordSearchRequest";   $result = $client->call($method,   array('KeywordSearchRequest' => $params),   $namespace, $action);   return $result; } 

Running the query against the Amazon API uses code very similar to the previous example. The hardcoded variables for keyword, page, mode, and type have been replaced with variables. The encapsulation of this code into its own function should help keep things clear, and will save on overhead later.

Finally, here is the body of the code itself:

 <html> <head> <title>Amazon.com Search Interface</title> </head> <body> <form action="./soap.search.php" method="get"> <input type="text" name="query"> <input type="hidden" name="page" value="1"> <select name="mode"> 

Here a basic form is started to allow users to enter their search criteria. The page variable is used to allow users to navigate through multiple pages of search results.

 <?php $modes = array(); $modes[] = "books"; $modes[] = "dvd"; $modes[] = "cd"; foreach ($modes as $mode) {   echo "<option value=\"$mode\">$mode</option>"; } ?> </select> <input type="submit"> </form> 

An array is created to contain each type of request the program is capable of performing. Structuring your code in this manner allows you to add other search types easily later on, and will come in handy when it comes time to validate the user's input.

 <?php if (!isset($_GET['query'])) {   exit; }else {   $query = $_GET['query']; } 

If a query has not been received, there is no point in continuing. This is most likely the case when a user visits the page for the first time.

 if (in_array($_GET['mode'], $modes)) {   $mode = $_GET['mode']; }else {   echo "Invalid mode selected was " . $_GET['mode'];   exit; } 

Here the array originally used to populate the select box is used to validate the data. Looking at the form, it may seem impossible to receive any other value, but remember that the request is passed in the address bar, and requests can be created by other parties manually.

 if (is_numeric($_GET['page'])) {   $page = $_GET['page']; }else {   echo "Invalid page requested, was: " . $_GET['page'];   exit; } 

Finally, the page variable is populated if the passed variable is numeric.

 require('../lib/nusoap.php'); $client = new soapclient("http://soap.amazon.com/schemas2/AmazonWebServices.wsdl", true); $error = $client->getError(); if ($error) {     echo 'Error creating search client, please try again later';     // It would be a great idea to email $error to an administrator     exit; } 

The NuSOAP library is included into the program at this point rather than earlier to save on overhead when it isn't needed (which is the case for the first request). The SOAP client is created, and is checked for errors. If an error is encountered at this point, it is likely that the .wsdl file was either inaccessible or invalid. It would be a great idea to do something with errors like this when you encounter them.

 $result = runSearchQuery($client, $query, $page, $mode, 'heavy'); $error = $client->getError(); if ($client->fault || $error) {   echo "I wasn't able to retrieve your search results, please try again later";   //It would be a great idea to email $client->fault to an admin   exit; } 

Next the query is run, and again errors are checked for. A client fault is different from an error, so both are checked for at this point. Again, don't just check for errors, do something about them.

 $resultItems = $result['Details']; switch ($mode) {   case "dvd":     displayDVD($resultItems);     break;   case "books":     displayBook($resultItems);     break;   case "cd":     displayCD($resultItems);     break; } if ($result['TotalPages'] > $page) {   $page++;   echo "<a href=\"soap.search.php?query=$query&mode=$mode&page=$page\">Next 10 Results</a>"; } 

Finally, the resultItems variable is created to contain all of the result items, and the appropriate display function is called. If the current page is less than the total number of pages available (as indicated by Amazon), it displays a link to the next page.

And that's it; users can now perform searches for books, DVDs, or CDs, page through the results, and click on a link to be taken directly to that item on Amazon. Hopefully they make a purchase, because the inclusion of my tag with the query will ensure I make a percentage of any referred sale! A search for a DVD is shown in Figure 7-2, and a search for a music CD is shown in Figure 7-3.

image from book
Figure 7-2

image from book
Figure 7-3

Searching by Author

In a previous example I searched for my name, which managed to return exactly what I was looking for in that case. However, that search included both the title of books and the author when examining records, which may have undesired results. For example, a search for "Winston Churchill" will result in books by and about him. In order to perform a search specifically by author, a separate function is called.

Note 

Though I am only presenting the search for Author here, similar search functions are available to search for Actors, Directors, or Artist.

This function performs in a similar manner to the earlier search example. However, the main difference is the fact that it calls AuthorSearchRequest rather than KeywordSearchRequest:

 function runAuthorSearchQuery($client, $author, $page, $mode, $type = 'lite') {   $params = array(     'author' => $author,     'page' => $page,     'mode' => $mode,     'tag' => 'preinheimerco-20',     'type' => $type,     'devtag' => '1PHH5VTRY7D300H7JTR2'   );   $namespace = 'http://soap.amazon.com';   $action = 'http://soap.amazon.com';   $method = "AuthorSearchRequest";   $result = $client->call($method,   array('AuthorSearchRequest' => $params),   $namespace, $action);   return $result; } 

As mentioned, this function is quite similar to the earlier keyword search function. The two differences are the call to AuthorSearchRequest rather than KeywordSearchRequest, and the keyword parameter is replaced with author.

 <?php if (!isset($_GET['author'])) {   echo "no author";   exit; }else {   $author = $_GET['author']; } if (is_numeric($_GET['page'])) {   $page = $_GET['page']; }else {   $page = 1; } require('../lib/nusoap.php'); $client = new soapclient("http://soap.amazon.com/schemas2/AmazonWebServices.wsdl", true); $result = runAuthorSearchQuery($client, $author, $page, 'books', 'heavy'); $error = $client->getError(); if ($error) {   echo "<pre>";   print_r($error);   echo "</pre>";   exit; } $resultItems = $result['Details']; displayBook($resultItems); if ($result['TotalPages'] > $page) {   $page++;   echo "<a href=\"soap.author.php?author=$author&page=$page\">Next 10 Results</a>"; } 

Much of the code here is identical to the last example. $_GET['AUTHOR'] is confirmed to exist rather than the query used in the last example. A change is also made to the handling of the page variable. This page will be linked to in future examples, and it will be easier not to require the page variable set in the URL.

Figure 7-4 shows a search for "Dan Brown."

image from book
Figure 7-4

Examining a Product in Depth

Using Amazon's search function returns information on a large set of items. However, frequently you will only need the information for one specific product, or only want to display a single product to the end user. You can retrieve that information using the API's AsinSearchRequest method.

Conceptually, this script isn't too different from earlier examples, though a few extra functions have been created to make the page more interactive.

 function runASINQuery($client, $asin, $type = 'heavy') {   $params = array(                     'asin'        => $asin,                     'type'        => $type,                     'tag'         => 'preinheimerco-20',                     'devtag'      => '1PHH5VTRY7D300H7JTR2'   );   $namespace = 'http://soap.amazon.com';   $action = 'http://soap.amazon.com';   $method = "AsinSearchRequest";   $result = $client->call($method,   array('AsinSearchRequest' => $params),   $namespace, $action);   return $result; } 

Here the actual call to the API is made. Notice the lack of parameters used previously, such as mode, which are irrelevant because the ASIN points to a specific item within Amazon's catalog. All previous query functions defaulted to requesting the lite result set; this one defaults to heavy. Because only a single item is being displayed, you can make use of the additional data returned. This will require you to implement a few more functions as follows:

 function getAuthorList($authors) {   $authorList = "";   foreach($authors as $item)   {     $a = urlencode($item);     $authorList .= "<a href=\"./soap.author.php?author=$a\"       title=\"More from $item\">$item</a>, ";   }   return $authorList; } 

This is the first function used to aid in the display of data. Here the list of authors of the book is parsed, and each author is presented as a link. This links to the previous script, so users can find books from the same author quickly. Note the use of urlencode(); this is important because author names will frequently contain spaces, which should be encoded before being presented in a link.

 function getCategoryList($browseList) {   $categoryList = "";   foreach ($browseList as $item)   {     $categoryList .= $item['BrowseName'] . ", ";   }   return $categoryList; } 

You will also present a list of categories to which the book belongs. This information is nested twice, so a foreach() loop is used rather than a simple implode() call.

Finally, here is the main portion of the code:

 <?php if (!isset($_GET['asin'])) {   exit; }else {   $asin = $_GET['asin']; } require('../lib/nusoap.php'); $client = new soapclient("http://soap.amazon.com/schemas2/AmazonWebServices.wsdl", true); $result = runASINQuery($client, $asin, 'heavy'); $error = $client->getError(); if ($error) {   echo "<pre>";   print_r($error);   echo "</pre>";   exit; } $result = $result['Details']['0']; 

As usual, the passed parameter is checked first, before any other files are included. Results to an ASIN query are presented in the same manner as search results, within Details, then an array is presented (which has a single element). To make accessing that data easier, the $result variable is set to that smaller scope.

 $image = $result['ImageUrlMedium']; $url = $result['Url']; $productName = $result['ProductName']; $authors = getAuthorList($result['Authors']); $listPrice = $result['ListPrice']; $amazonPrice = $result['OurPrice']; $categories = getCategoryList($result['BrowseList']); $availability = $result['Availability']; $rating = $result['Reviews']['AvgCustomerRating']; echo "<img src=\"$image\" align=\"left\">"; echo "<b>Title</b>: <a href=\"$url\"    title=\"Buy at Amazon!\">$productName</a><br>"; echo "<b>Authors</b>: $authors<br>"; echo "<b>List Price</b>: $listPrice, <b>Amazon's Price</b>: $amazonPrice<br>"; if ($categories) echo "<b>Categories</b>: $categories<br>"; echo "<b>Availability</b>: $availability<br>"; echo "<b>Average Customer Rating</b>: $rating<br><br>"; $customerReviews = $result['Reviews']['CustomerReviews']; foreach ($customerReviews AS $review) {   echo "<b>Rating</b>: {$review['Rating']}<br>";   echo "<b>Summary</b>: {$review['Summary']}<br>";   echo "<b>Comment</b>: {$review['Comment']}<br><br>"; } 

Finally, the results are echo'd to the end user. Notice that the medium-sized image was used in this case, rather than the small image used in search results. Both the list price and Amazon's price are displayed. Also notice that a full category listing, linked author names, and a listing of customer reviews are also provided. Figure 7-5 shows detailed information on "The Elements of Style."

image from book
Figure 7-5

This details page works best when linked to from other result pages. For example, change the destination in both the Keyword search and Author search programs to point to this page. Users will then see a larger cover image and more detailed pricing information.

Monitoring Prices

Amazon offers a wide selection and competitive pricing, but you may encounter products priced a little higher than you would like. Both businesses and individuals take a keen interest in pricing, and may want to be informed if the price on any particular item they are interested in changes. With the code presented here, you can save those products and have your script periodically check for lowered prices.

 require('../common_db.php'); require('../lib/nusoap.php'); $client = new soapclient("http://soap.amazon.com/schemas2/AmazonWebServices.wsdl", true); $query = "SELECT * FROM `07_amazon_monitor_price_list`"; $results = getAssoc($query); foreach($results AS $item) {   $result = runASINQuery($client, $item['asin']);   $result = $result['Details']['0'];   $listPrice = $result['ListPrice'];   $amazonPrice = $result['OurPrice'];   $query = "INSERT INTO 07_amazon_monitor_price_results     (`asin`, `listPrice`, `amazonPrice`, `timestamp`)     VALUES ('{$item['asin']}', '$listPrice', '$amazonPrice', null)";   insertQuery($query); } 

I have removed the error checking to keep this example light, but the concept should be clear. A list of desired ASINs to watch is retrieved from the database, each item is checked in turn, and both its list price and Amazon's price are recorded, along with the timestamp.

What you do with this information is entirely up to you. You could graph prices of books over time, send a message when the price drops, or anything else, for that matter. The two tables used are shown here:

 CREATE TABLE `07_amazon_monitor_price_results` (   `asin` varchar(10) NOT NULL default '',   `listPrice` varchar(10) NOT NULL default '0',   `amazonPrice` varchar(10) NOT NULL default '0',   `timestamp` timestamp(14) NOT NULL ) TYPE=MyISAM; CREATE TABLE `07_amazon_monitor_price_list` (   `asin` varchar(10) NOT NULL default '',   PRIMARY KEY (`asin`) ) TYPE=MyISAM; INSERT INTO `07_amazon_monitor_price_list` VALUES ('059600656X'); INSERT INTO `07_amazon_monitor_price_list` VALUES ('0672324547'); INSERT INTO `07_amazon_monitor_price_list` VALUES ('0764589547'); INSERT INTO `07_amazon_monitor_price_list` VALUES ('1565926811'); 

In both tables, a length of 10 is specified for the length of the ASIN — ASINs are always 10 characters long.

Monitoring Amazon Sales Rank

Another useful piece of information Amazon makes available is the sales rank for all its products. This is of particular interest if you (for example) wrote a book and are curious as to how it is performing. This code fits into the same framework as the previous example.

 $query = "SELECT * FROM `07_amazon_monitor_rank_list`"; $results = getAssoc($query); foreach($results AS $item) {   $result = runASINQuery($client, $item['asin']);   $result = $result['Details']['0'];   $salesRank = $result['SalesRank'];   $query = "INSERT INTO 07_amazon_monitor_rank_results     (`asin`, `rank`, `timestamp`)     VALUES ('{$item['asin']}', '$salesRank', null)";   insertQuery($query); } 

Again, all of the error checking code has been removed to save on space. The two tables used are shown here:

 CREATE TABLE `07_amazon_monitor_rank_results` (   `asin` varchar(10) NOT NULL default '',   `rank` int(11) NOT NULL default '0',   `timestamp` timestamp(14) NOT NULL ) TYPE=MyISAM;\ CREATE TABLE `07_amazon_monitor_rank_list` (   `asin` varchar(10) NOT NULL default '',   PRIMARY KEY (`asin`) ) TYPE=MyISAM; INSERT INTO `07_amazon_monitor_rank_list` VALUES ('059600656X'); INSERT INTO `07_amazon_monitor_rank_list` VALUES ('0672324547'); INSERT INTO `07_amazon_monitor_rank_list` VALUES ('0764589547'); INSERT INTO `07_amazon_monitor_rank_list` VALUES ('1565926811'); 

Using the information gleaned in this example, as well as the sales data obtained from the previous example, can yield interesting information. Does the sales rank increase when price drops, how does the sales rank change as time passes since the book's release increases, and so on.




Professional Web APIs with PHP. eBay, Google, PayPal, Amazon, FedEx, Plus Web Feeds
Professional Web APIs with PHP. eBay, Google, PayPal, Amazon, FedEx, Plus Web Feeds
ISBN: 764589547
EAN: N/A
Year: 2006
Pages: 130

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net