Os Amazon1 PDF

Embed Size (px)

Citation preview

  • 8/14/2019 Os Amazon1 PDF

    1/39

    Create an Amazon storefront using PHP, Part 1:Getting content with Amazon ECSHow to build a storefront and display its wares

    Skill Level: Intermediate

    Tyler Anderson ([email protected] )Freelance WriterStexar Corp.

    25 Oct 2005

    This is the first of a two-part tutorial titled "Create an Amazon storefront using PHP "that constructs an Amazon storefront using PHP and the Amazon E-CommerceService (ECS). The storefront constructed will allow shoppers to view items displayedin lists or search for specific items in the store. Part 2 will cover the shopping cart,

    recommendation service, and constructing a collectibles shop.

    Section 1. Before you start

    This tutorial is for programmers interested in creating a storefront that automates theprocess of connecting to Amazon Web Services and displaying the result usingPHP. This assumes you are familiar with basic PHP concepts, including for andwhile loops, and form handling. If you are uncertain of your PHP prowess, thereare great tutorials available to help you get up to speed (see Resources ).

    You should be familiar with Amazon Web Services, which are introduced in thedeveloperWorks series "Boost application development with Amazon Web Services"(see Resources ).

    About this series

    Getting content with Amazon ECS Copyright IBM Corporation 1994, 2008. All rights reserved. Page 1 of 39

    mailto:[email protected]://www.ibm.com/developerworks/views/opensource/libraryview.jsp?search_by=amazon+storefronthttp://www.ibm.com/developerworks/views/opensource/libraryview.jsp?search_by=amazon+storefronthttp://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/developerworks/views/opensource/libraryview.jsp?search_by=amazon+storefrontmailto:[email protected]
  • 8/14/2019 Os Amazon1 PDF

    2/39

    In this two-part series, we create an Amazon shopping cart with PHP. Part 1 willcover the storefront architecture, displaying selections and browsing categories bycommunicating to Amazon Web Services through item search requests. We will alsocreate a search box.

    Part 2 will cover creating, adding to, and modifying a shopping cart that will bestored entirely on Amazon servers using a technique called cart requests. We willcover building a collectibles shop and giving shoppers the ability to browse forsimilar items.

    About this tutorial

    We will build an Amazon storefront containing category links and a search box,allowing shoppers to browse categories in your store. Unlike most PHP applications,this one requires no local database, as data is stored on Amazon's servers.

    Therefore, this tutorial relies heavily on the Simple Object Access Protocol (SOAP),a Web services protocol that organizes information in XML. Web services is the wayin which applications, like the PHP application you will build throughout this tutorial,communicate with central servers to obtain information.

    Through the Amazon E-Commerce Service (ECS), you will obtain and displaycontent from categories that shoppers choose. When a category is selected, you willcreate parameters indicating that category, collect other relevant information, andlaunch a SOAP client. The SOAP client will take the parameters, form an XMLdocument, and relay the XML document to the SOAP server. The Amazon serveraccesses its databases to create an XML document containing items that match thecriteria. Finally, the server returns an XML document to your SOAP client, whichparses it into a data structure from which you extract the requested data.

    Prerequisites

    To follow along with this tutorial, you will need to install and test the following tools,and retrieve two identifiers from Amazon:

    Web serverPick any Web server and operating system. Feel free to use Apache V2.X , orthe IBM HTTP Server .

    PHPYou can follow along in this tutorial without PHP, but if you are interested ininteracting with the sample application, download PHP V5 . Make sure to buildPHP with --enable-soap to enable the PHP SOAP extensions.

    Amazon

    developerWorks ibm.com/developerWorks

    Getting content with Amazon ECSPage 2 of 39 Copyright IBM Corporation 1994, 2008. All rights reserved.

    http://httpd.apache.org/download.cgihttp://www14.software.ibm.com/webapp/download/product.jsp?s=p&id=RBAR-5LER2Thttp://www.php.net/downloads.phphttp://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/legal/copytrade.shtmlhttp://www.php.net/downloads.phphttp://www14.software.ibm.com/webapp/download/product.jsp?s=p&id=RBAR-5LER2Thttp://httpd.apache.org/download.cgi
  • 8/14/2019 Os Amazon1 PDF

    3/39

  • 8/14/2019 Os Amazon1 PDF

    4/39

    This is what a SOAP message looks like. In the PHP and Web services section, youwill learn about how to use SOAP messages to make and receive requests fromSOAP servers.

    The storefrontPopular storefronts have clean, simple layouts. In this tutorial, we will design a basicstorefront that's light on style so that we can focus on the mechanical parts thatmake it go. The finished product will have a side panel holding categories and asearch box, displaying the items in the main content section on the right (see Figure1).

    Figure 1. The final application

    developerWorks ibm.com/developerWorks

    Getting content with Amazon ECSPage 4 of 39 Copyright IBM Corporation 1994, 2008. All rights reserved.

    http://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/legal/copytrade.shtml
  • 8/14/2019 Os Amazon1 PDF

    5/39

  • 8/14/2019 Os Amazon1 PDF

    6/39

    The categories shown are possible SearchIndex values, which we will use to

    developerWorks ibm.com/developerWorks

    Getting content with Amazon ECSPage 6 of 39 Copyright IBM Corporation 1994, 2008. All rights reserved.

    http://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/legal/copytrade.shtml
  • 8/14/2019 Os Amazon1 PDF

    7/39

    search for items.

    Items

    By default, Amazon categories contain hundreds of pages full of items. Shoppersneed to narrow their searches to find what they want. The item search you willdesign will search within categories for products and display the results to yourshopper, showing similar results to the items displayed on Amazon. See figures 3and 4.

    Figure 3. Items shown in the Baby category in the final application

    Figure 4. Items shown in the Baby category on Amazon

    ibm.com/developerWorks developerWorks

    Getting content with Amazon ECS Copyright IBM Corporation 1994, 2008. All rights reserved. Page 7 of 39

    http://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/legal/copytrade.shtml
  • 8/14/2019 Os Amazon1 PDF

    8/39

    Notice that the first three items in Figure 4 are the same. Not all items appear in theexact same order. However, the items displayed are the same.

    Section 3. What is Amazon ECS?

    The Amazon E-Commerce Service (ECS) allows programmers to gain access to allthe information found when browsing Amazon. This section will explore methods ofretrieving information from Amazon.

    developerWorks ibm.com/developerWorks

    Getting content with Amazon ECSPage 8 of 39 Copyright IBM Corporation 1994, 2008. All rights reserved.

    http://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/legal/copytrade.shtml
  • 8/14/2019 Os Amazon1 PDF

    9/39

    Request types

    There are several methods for searching for items or other content. Here, we willfocus solely on ItemSearch . Part 2 will also use ItemSearch , as well as

    ItemLookup , CartCreate , CartAdd , CartModify , CartClear , and CartGet .Here's a list of all possible requests:

    BrowseNodeLookup -- Returns information about a specific Amazonproduct area

    CartAdd -- Adds an item to the cart.

    CartClear -- Removes all the contents of a cart.

    CartCreate -- Created with one item specified, this request creates a

    new cart. CartGet -- Retrieves the contents of a shopping cart.

    CartModify -- Used to modify quantity of items in a shopping cart.Setting a quantity to zero removes that item from the cart. Items may alsobe moved to and from the saved cart.

    CustomerContentLookup -- Used to retrieve publicly available contentwritten by specific Amazon customers.

    CustomerContentSearch -- Allows you to search for Amazoncustomers by name or e-mail address.

    Help -- Used to retrieve information about developing with Amazon ECS.

    ItemLookup -- Allows you to retrieve information for up to 10 products byaccessing reviews, similarities, etc.

    ItemSearch -- Used to search for products based on category andkeywords.

    ListLookup -- Allows you to retrieve all items from a specific list.

    ListSearch -- Allows you to search for a wish list, baby registry, orwedding registry.

    SellerListingLookup -- Allows you to look up Amazon Shops andMarketplace products.

    SellerListingSearch -- Allows you to search for Amazon Shops andMarketplace listings.

    SellerLookup -- Allows you to retrieve information about specific

    ibm.com/developerWorks developerWorks

    Getting content with Amazon ECS Copyright IBM Corporation 1994, 2008. All rights reserved. Page 9 of 39

    http://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/legal/copytrade.shtml
  • 8/14/2019 Os Amazon1 PDF

    10/39

    sellers, including customer feedback ratings, location, etc.

    SimilarityLookup -- Allows you to retrieve similar items of a product.

    TransactionLookup -- Allows you to retrieve limited information on thestatus of transactions made by Amazon customers.

    Understanding the parameters

    Each request requires parameters for Amazon ECS to process your requestproperly. The parameters and their descriptions used in this series:

    Service -- This is always AWSECommerceService .

    SubscriptionId -- The developer token from Amazon.

    AssociateTag -- The Associates ID from Amazon.

    Operation -- The type of operation or request you will perform. Usually,you will just add Request to each request type. For the request type,ItemSearch , the operation will be ItemSearchRequest ). ForItemLookup , the operation will be ItemLookupRequest , etc.

    ResponseGroup -- This is important because it tells Amazon how muchinformation you want: from Small , Medium , and Large to specific partsof the available XML elements.

    Some available response groups:

    Accessories -- Returns a list of accessory items for each product in thelist that has accessories.

    Cart -- Returns the shopping cart identifiers, as well as informationspecific to each product.

    Images -- Returns URLs for all images a product has.

    Offers -- Returns information about the offers for each product in thelist.

    Small -- Provides a "Small" amount of information for each item in the

    list. Medium -- Provides a "Medium" amount of information for each item in

    the list.

    Large -- Provides a "Large" amount of information for each item in thelist.

    developerWorks ibm.com/developerWorks

    Getting content with Amazon ECSPage 10 of 39 Copyright IBM Corporation 1994, 2008. All rights reserved.

    http://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/legal/copytrade.shtml
  • 8/14/2019 Os Amazon1 PDF

    11/39

    SOAP vs. REST

    The data returned from the server for each request type is identical. However, bothhave differences in how the request is set up and used. REST requests are the

    simplest because they are long URLs containing the variables and their values foreach item -- very similar to GET requests in PHP.

    SOAP requests, on the other hand, are more complex and are, thus, more powerful.They are XML documents transmitted to the SOAP server by way of HTTP. SOAPrequests are more powerful than GET requests because they can accept moreparameters, and several requests can be bundled in one SOAP XML document,which allows for simultaneous requests. Also, SOAP requests have priority, whichimproves the overall responsiveness of your store.

    You will use REST requests in this tutorial to learn the data returned from the server.

    In contrast, you will use SOAP requests in the final application (in Part 2) becausethey offer the potential to allow you to do much more than simple REST requests.

    Simple REST request

    You will be performing a REST request here to learn what the returned data is. Do anItemSearch , as this is what you will be doing later in the tutorial. First, you willneed to set up the parameters.

    The value of service will be AWSECommerceService , Operation will beItemSearchRequest , ResponseGroup will be Small , SubscriptionId will beyour developer token, and AssociateTag will be your Amazon Associates ID.Search through the Sporting Goods category, so SearchIndex will beSportingGoods, and search specifically for golf clubs, so Keywords will be golfclubs. Following is the URL, as shown in Listing 2.

    Listing 2. URL for the REST request

    http://webservices.amazon.com/onca/xml?Service=AWSECommerceService&SubscriptionId=01AJBKQ38K8HM2R33Q82&Operation=ItemSearch&ResponseGroup=Small&AssociateTag=scubanecessit-20&SearchIndex=SportingGoods&Keywords=golf%20clubs

    Amazon ECS will now return an XML document containing information about thesearched items.

    REST response

    ibm.com/developerWorks developerWorks

    Getting content with Amazon ECS Copyright IBM Corporation 1994, 2008. All rights reserved. Page 11 of 39

    http://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/legal/copytrade.shtml
  • 8/14/2019 Os Amazon1 PDF

    12/39

    Because the response is so large, only a portion of it will be shown here. However,you can see the full response by pointing your browser to the URL in Listing 2.Listing 3 shows a snippet of the REST response.

    Here is where the items array begins. It plays back to the sender what the search

    terms were. The first element begins the information for the first item in theresponse sent from Amazon ECS. It shows the ASIN, the item ID, a URL that -- ifpointed to by the browser -- would display detailed information about the product. Italso shows basic attributes, as we requested a small ResponseGroup , like theitem's title.

    Understanding Amazon's WSDL file

    A Web Services Description Language (WSDL) file defines the information a Webservice expects, as well as what it should return. This way, you can build your

    application without wondering what the information is that you need to send, whereyou're expected to send it, and what you can expect as a response.

    Amazon's WSDL file describes the available commands and syntax of possiblelookup and search requests.

    Consider the ItemSearch entry in the above file, shown in Listing 4 .

    For REST requests, the elements shown in Listing 5 are simply inserted into theItemSearch element (Listing 3). The AWSECommerceService service defineswhere the request should be made, which is exactly what you used in the URL ofyour GET request in the REST response panel.

    Listing 5. ItemSearchRequest entry

    ...

    The WSDL file defines the structure of SOAP requests and responses, and RESTresponses. ( REST requests are just URLs with encoded parameters.) Notice that theelement named Request in Listing 5 defines the type of request that can be made,an ItemSearchRequest ; and Listing 5 contains the structure of such a request,which makes the connection between the ItemSearch request and theItemSearchRequest operation. You can refer to this file as you follow along, andagain when you finish this tutorial and make plans to build your own application.

    developerWorks ibm.com/developerWorks

    Getting content with Amazon ECSPage 12 of 39 Copyright IBM Corporation 1994, 2008. All rights reserved.

    http://localhost/var/www/apps/conversion/tmp/scratch_6/listing3.htmlhttp://webservices.amazon.com/AWSECommerceService/AWSECommerceService.wsdlhttp://localhost/var/www/apps/conversion/tmp/scratch_6/listing4.htmlhttp://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/legal/copytrade.shtmlhttp://localhost/var/www/apps/conversion/tmp/scratch_6/listing4.htmlhttp://webservices.amazon.com/AWSECommerceService/AWSECommerceService.wsdlhttp://localhost/var/www/apps/conversion/tmp/scratch_6/listing3.html
  • 8/14/2019 Os Amazon1 PDF

    13/39

    Section 4. PHP and Web services

    In this section, you will learn how a simple SOAP request is sent and received viaPHP, and how to extract data from the response in PHP.

    Creating a SOAP request

    To create the SOAP request, you need to set up the parameters. Because SOAP ismore complex than REST , you will start with a simple example: the product in-stockchecker. The XML document is shown in Listing 6.

    Listing 6. SOAP request in XML for the product in-stock checker

    UWHD0023

    The code in Listing 6 is how the SOAP request would look in XML. It specifies anEnvelope with an empty Header . The Body contains the parameters being sent.PHP can now send this request to the SOAP server via HTTP.

    Creating a SOAP client in PHP

    To create the SOAP client, you can take advantage of the built-in SOAP functionality

    of PHP:

  • 8/14/2019 Os Amazon1 PDF

    14/39

    Transmitting the SOAP request in PHP

    Now that the client has been created, you will need to set up the SOAP parametersand call the example function, InStockCheck , as shown in Listing 7.

    Listing 7. Set up the parameters and send the SOAP request

    The above code sends the SOAP request to the server specified in the WSDL file,

    the URL you used in your REST request. Now you will move onto the SOAPresponse.

    The SOAP response

    The SOAP response is also an XML document (see Listing 8).

    Listing 8. SOAP response in XML for the product in-stock checker

    15

    The resultant data structure holds the answer to your request inInStockQuantity . Next, you will receive and extract the needed data in PHP.

    Receiving and extracting data from the response in PHP

    The response is captured in PHP by the code in Listing 9.

    developerWorks ibm.com/developerWorks

    Getting content with Amazon ECSPage 14 of 39 Copyright IBM Corporation 1994, 2008. All rights reserved.

    http://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/legal/copytrade.shtml
  • 8/14/2019 Os Amazon1 PDF

    15/39

    Listing 9. Captured response

    ...$client-lInStockCheck($params);$answer = $result->lInStockQuantity;?>

    You now know how to transmit and receive a simple SOAP request and response.Later, you will make more complex SOAP requests with hierarchy.

    Handling faults

    A fault can occur for a variety of reasons. To catch faults on your own, withoutexceptions, and display them to the screen, use the following PHP code.

    Listing 11. Handle a SOAP fault

    ...$result = $client->InStockCheck($params);$client = new

    SoapClient("http://webservices.example.com/services/example.wsdl");$result = $client->InStockCheck($params);if(is_soap_fault($result)){

    print("A fault occurred: " . $result->faultstring);}else{

    $answer = $result->InStockQuantity;}?>

    If a problem occurs on your side or the server's, a fault will be returned in the SOAPresponse, and you will be notified with the above code. A fault looks just like aregular SOAP response. However, the variable faultstring contains the reasonwhy a fault occurred.

    ibm.com/developerWorks developerWorks

    Getting content with Amazon ECS Copyright IBM Corporation 1994, 2008. All rights reserved. Page 15 of 39

    http://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/legal/copytrade.shtml
  • 8/14/2019 Os Amazon1 PDF

    16/39

    Section 5. Designing the storefront architecture

    This section will cover the design of the storefront architecture. It will guide youthrough creating templates for your Web site that will be used to display a title, aside panel for categories, a search box for searching within categories, and footer atthe end of each page.

    Processing point: storeFront.php

    Now that Web services have been covered, let's begin designing the storefront.Create a root directory for your storefront and create a file: storeFront.php .Begin coding it, as shown in Listing 12.

    Listing 12. Process requests and display storefront

    The above will introduce your storefront. When a category is selected later, it will calla method that will connect to Amazon ECS and display returned category items oritems corresponding to search terms.

    Home link and title

    The storeFront.php file is used to direct and receive all requests by yourapplication, which you need to create the rest of the content to display as yourstorefront. Create a file named header.php and place it in the same directory asstoreFront.php . Begin coding it as shown in Listing 13.

    Listing 13. Home link and title

    developerWorks ibm.com/developerWorks

    Getting content with Amazon ECSPage 16 of 39 Copyright IBM Corporation 1994, 2008. All rights reserved.

    http://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/legal/copytrade.shtml
  • 8/14/2019 Os Amazon1 PDF

    17/39

  • 8/14/2019 Os Amazon1 PDF

    18/39

    ');...

    Listing 14 starts by creating the side panel that will house the category links. When acustomer clicks on one of the categories, the category and displayCat , the valueto display for the current category, will be set in the URL. This way, your applicationcan process the variables and display the appropriate items and information usingthe GET array.

    Figure 5 shows the current storefront with category links.

    Figure 5. Display the category links

    The category links are shown in the left-side panel. Now you will move on to clickingfrom category to category.

    The processGETString will place the current variables in the GET array,propagating their values with each click in your storefront. This is important so thateach time a customer clicks through your storefront, his current data is not lost.Place this function in functions.php , as shown in Listing 15.

    developerWorks ibm.com/developerWorks

    Getting content with Amazon ECSPage 18 of 39 Copyright IBM Corporation 1994, 2008. All rights reserved.

    http://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/legal/copytrade.shtml
  • 8/14/2019 Os Amazon1 PDF

    19/39

    Listing 15. Process and return the variables encoded in the URL

    function processGETString($vetoString=''){$string = '';if($_GET['pagenum'] != '' && strstr($vetoString, 'pa') == '')

    $string .= "&pagenum=".$_GET['pagenum'];if($_GET['keyword'] != '' && strstr($vetoString, 'ke') == '')

    $string .= "&keyword=".$_GET['keyword'];if($_GET['category'] != '' && strstr($vetoString, 'ca') == '')

    $string .= "&category=".$_GET['category'];if($_GET['displayCat'] != '' && strstr($vetoString, 'di') == '')

    $string .= "&displayCat=".$_GET['displayCat'];return $string;

    }

    This function concatenates all current variables to a single variable used for creatinglinks, thus propagating the variable's values from one click to the next. The$vetoString variable that gets passed in as a parameter, with value cadikepa isused to signify that if that variable exists, its value will not be propagated. This is

    important when a customer wants to switch categories. Use displayCat to showthe new category. The keyword and pagenum variables will need to be droppedaltogether.

    Click on the Baby category, and notice the current category and displayCatvalues in the URL:

    http://localhost.localdomain/amazon_ecs_part1/storeFront.php?category=Baby&displayCat=Baby

    Now click on the Computers category.

    http://localhost.localdomain/amazon_ecs_part1/storeFront.php?category=PCHardware&displayCat=Computers

    See how the old category and displayCat values didn't get propagated? It'sbecause they were vetoed by the processGETString() function by passing in 'ca'to veto category, and 'di' to veto displayCat .

    The side panel: Search box

    You have now set up the ability to browse categories. Next, you will add functionalityto search in the current category by creating a search box, continuing withheader.php , as shown in Listing 16.

    Listing 16. Display the search box

    ibm.com/developerWorks developerWorks

    Getting content with Amazon ECS Copyright IBM Corporation 1994, 2008. All rights reserved. Page 19 of 39

    http://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/legal/copytrade.shtml
  • 8/14/2019 Os Amazon1 PDF

    20/39

    ...');

    if(isset($_GET['category'])){print('

    Search within
    this category

    ...');print('

    ');...

    The HTML code in Listing 16 will display a search box. Once the Search button ispressed, it will submit the entered keyword, as well as the current displayCat andcategory variables as hidden inputs. This will allow your application to process thedata and display the appropriate items as results.

    See the current storefront with the search box by clicking one of the category links,

    as shown in Figure 6.

    Figure 6. Display the search box

    developerWorks ibm.com/developerWorks

    Getting content with Amazon ECSPage 20 of 39 Copyright IBM Corporation 1994, 2008. All rights reserved.

    http://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/legal/copytrade.shtml
  • 8/14/2019 Os Amazon1 PDF

    21/39

    The search box is displayed in the left-side panel with a button. You will coversearching through items within categories in the Searching for items section. Nowyou will move on to the main content area.

    Main content area: Setup and contents

    For this part of the tutorial, the side panel is complete. There will be some otherthings to add to the panel in Part 2, so be sure to read that.

    Here, you will set up the main content area, where you will later display itemsreturned from Amazon. The code will close off the side panel and begin the maincontent area:

    print('');

    ibm.com/developerWorks developerWorks

    Getting content with Amazon ECS Copyright IBM Corporation 1994, 2008. All rights reserved. Page 21 of 39

    http://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/legal/copytrade.shtml
  • 8/14/2019 Os Amazon1 PDF

    22/39

    The contents of the main content area are ready to be displayed. Before you do that,you need to finish it off with a footer.

    Footer: Site information

    Your footer will be a rather simple file, which you can make more complex if youwant to at a later time. Create it, footer.php , and place it in the same directory asheader.php . Place the following example code in it, as shown in Listing 17.

    Listing 17: Display the site and copyright info


    Copyright 2005, TylerCo.
    Product/information and pictures Copyright Amazon

    You can tailor your site and copyright information for your own application. Thiscompletes the storefront. Sample output shown by the browser after pointing tostoreFront.php is shown in Figure 7.

    Figure 7. The completed storefront

    developerWorks ibm.com/developerWorks

    Getting content with Amazon ECSPage 22 of 39 Copyright IBM Corporation 1994, 2008. All rights reserved.

    http://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/legal/copytrade.shtml
  • 8/14/2019 Os Amazon1 PDF

    23/39

    Your storefront should include a title, a side panel with category links, an empty maincontent area to the right, and a footer displaying site and copyright information. Thesearch box isn't shown here because a category hasn't yet been chosen.

    Now you will move onto the fun stuff and begin retrieving content from Amazon.

    Section 6. Browsing categories

    Now that your storefront is designed complete with category links, it's time to requestdata from Amazon ECS and display the returned items for customers to browse.

    Retrieving the current category from the GET array

    First you need to click on a category. Start by clicking on the Sporting Goodscategory, which you will process in storeFront.php , as shown in Listing 18.

    ibm.com/developerWorks developerWorks

    Getting content with Amazon ECS Copyright IBM Corporation 1994, 2008. All rights reserved. Page 23 of 39

    http://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/legal/copytrade.shtml
  • 8/14/2019 Os Amazon1 PDF

    24/39

    Listing 18. Process the category variable out of the GET array

    ...require('header.php');

    if($_GET['category'] != ''){printCategoryItems();

    }else{

    print("

    Welcome to TylerCo., where you will findgreat value and great service!Guaranteed!

    Please browse the products on our Web siteby clickingon one of the categories to the left");}

    This time, instead of introducing your storefront, the category variable in the GETarray will exist, indicating to your application that a category has been selected,

    which will call printCategoryItems() . To see what the code in Listing 18 does,you can create an empty function, printCategoryItems() and place it in thefunctions.php file.

    Validating a selected category

    You have selected a category, and now you need to verify whether it is a validcategory in your storefront. Create the following function in a file, functions.php ,and place it in a subdirectory to your storefront called, includes , as shown inListing 19.

    Listing 19. Verify that the selected category is valid in your storefront

    define(TOKEN, "YourDeveloperTokenHere");define(ASSOCID, "YourAssociatesIdHere");

    function printCategoryItems(){...

    $category = $_GET['category'];$displayCat = $_GET['displayCat'];

    switch($category){case 'Baby':case 'PCHardware':case 'OutdoorLiving':case 'Software':case 'SportingGoods':

    $innerTitle = "$displayCat";break;

    default:print("The $category category doesn't exist");return;

    }

    if(isset($_GET['pagenum'])){$pagenum = $_GET['pagenum'];

    developerWorks ibm.com/developerWorks

    Getting content with Amazon ECSPage 24 of 39 Copyright IBM Corporation 1994, 2008. All rights reserved.

    http://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/legal/copytrade.shtml
  • 8/14/2019 Os Amazon1 PDF

    25/39

    }else{

    $pagenum = "1";}

    ...

    Include this file at the top of storeFront.php .The first two lines define your developer token and Amazon Associates ID. You willneed to replace these values with the ones you get from Amazon. If the categoryisn't valid, the method will return, notifying the customer. If it is valid, however, thetitle of the main content area will become the value used to display the category,which is more readable than using the code passed to Amazon as the category. The$pagenum variable indicates which page of the results Amazon will return fordisplaying to your customer.

    Setting up the parametersYou can now set up the parameters that will be sent to Amazon ECS. For searchingitems within a category, you will use the parameters shown in Listing 20.

    Listing 20. Parameters for searching items within a category

    ...$pagenum = "1";

    }$array = array('Operation' => 'ItemSearchRequest',

    'ItemPage' => $pagenum,'SearchIndex' => $category,'ResponseGroup' => 'Medium','Keywords' => $displayCat);

    ...

    The operation indicates to Amazon that you will perform an ItemSearchRequest ,and the first page is 1, as indicated by ItemPage . SearchIndex specifies whichcategory to search, and ResponseGroup tells Amazon how much info you want.You will use $displayCat as Keywords , indicating that you are going to ask forthe entire category. The Keywords parameter is required and cannot be empty, sothe $displayCat variable, containing the category display name, will be used asthe keywords.

    Creating a request function

    Create another function in functions.php , which will send our request to Amazonand return the result, as shown in Listing 21.

    Listing 21. Send a request to Amazon ECS and return the result

    ibm.com/developerWorks developerWorks

    Getting content with Amazon ECS Copyright IBM Corporation 1994, 2008. All rights reserved. Page 25 of 39

    http://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/legal/copytrade.shtml
  • 8/14/2019 Os Amazon1 PDF

    26/39

    function callSOAPFunction($function, $array){$params = array('Service' => 'AWSECommerceService',

    'AssociateTag' => ASSOCID,'SubscriptionId' => TOKEN,'Request' => array($array));

    $client = newSoapClient("http://webservices.amazon.com/AWSECommerceService

    /AWSECommerceService.wsdl",array('exceptions' => 0));

    return $client->__soapCall($function, array($params));}

    This function takes a function name (as determined in the WSDL file), and the arrayof parameters you created in the previous panel. A new SOAP client is then created,pointing to the Amazon ECS WSDL file. The parameter 'exceptions' => 0indicates that you will handle exceptions manually. Finally, you send the request toAmazon, indicating the function of the WSDL file you desire to use, $function , andthe array of parameters, $params . If valid, the function will return a data structurecontaining items that match your search request.

    Using the request function

    You can now make the request by calling callSOAPFunction . Add the code to theprintCategoryItems() function, as shown in Listing 22.

    Listing 22. Call callSOAPFunction and store the result in $result

    ...'ResponseGroup' => 'Medium','Keywords' => $displayCat);

    $result = callSOAPFunction("ItemSearch", $array);...

    The result is now stored in $result , which can now be processed.

    Displaying the items section

    If your request was valid and everything worked, you can display the iteminformation for your customer. Exception handling will be covered at the end of thissection. Add onto the printCategoryItems() function, as shown in Listing 23.

    Listing 23. Determine if items were returned from the request, displaying theitems, and page navigation

    developerWorks ibm.com/developerWorks

    Getting content with Amazon ECSPage 26 of 39 Copyright IBM Corporation 1994, 2008. All rights reserved.

    http://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/legal/copytrade.shtml
  • 8/14/2019 Os Amazon1 PDF

    27/39

    ...$result = callSOAPFunction("ItemSearch", $array);$items = $result->Items->Item;if($items){

    printItemsSection($innerTitle, $items); printPrevNextPage($result->Items->TotalPages, $pagenum);

    }}>>>>>>>>

    First, you need to retrieve the array of items from the returned SOAP construct,$items = $result->Items->Item . Next, if $items exist,printItemsSection() prints out all the items, and printPrevNextPage() willprint out the page navigation links.

    Now you will need to loop through all the items in the $items array if it's an array, orprint out the single item in $items if it isn't an array. See Listing 24 for the code andplace this function in functions.php .

    Listing 24. Print the item's sections title and loop through all the items

    function printItemsSection($title, $items){print("$title");print("

    ");if(is_array($items)){

    foreach($items as $i){printItem($i);

    }}else{

    printItem($items);}print("");

    }

    The function printItem() gets called on every item element. This is where theactual HTML for each item will be sent to the Web browser. Add the function shownin Listing 25 to functions.php .

    Listing 25. Print an item by retrieving item data from the $i variable

    function printItem($i){print("");

    print("");print(" ");print("".$i->ItemAttributes->Title." ");

    $price = $i->OfferSummary->LowestNewPrice->FormattedPrice;

    print(" ");print("Price: $price ");print(" ");

    }

    ibm.com/developerWorks developerWorks

    Getting content with Amazon ECS Copyright IBM Corporation 1994, 2008. All rights reserved. Page 27 of 39

    http://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/legal/copytrade.shtml
  • 8/14/2019 Os Amazon1 PDF

    28/39

    First, the image is displayed with the URL, $i->SmallImage->URL . Then, thename of the item, $i->ItemAttributes->Title , followed by the price,$i->OfferSummary->LowestNewPrice->FormattedPrice . Each itemdisplayed is actually an object with various attributes that match the XML filereturned in the SOAP response.

    Figure 8 shows the sample browser output of your application thus far.

    Figure 8. Display the first page of the Sporting Goods category

    Next, you need navigation links to navigate between the pages of the category.

    Displaying page navigation links

    developerWorks ibm.com/developerWorks

    Getting content with Amazon ECSPage 28 of 39 Copyright IBM Corporation 1994, 2008. All rights reserved.

    http://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/legal/copytrade.shtml
  • 8/14/2019 Os Amazon1 PDF

    29/39

    In Listing 23 , there was a reference to the printPrevNextPage() function. Addthis function, as shown in Listing 26, to functions.php .

    Listing 26. Retrieve the data for the previous and next page links, and displaythem

    function printPrevNextPage($totalPages, $pagenum){$previousPage = processPrevPage();$nextPage = processNextPage($totalPages);

    print("");

    print("$previousPage");print("Page ".$pagenum);print(" of $totalPages");print("$nextPage

    ");print("
    The

    above information came from ");print("Amazon.com. We make no guarantees to the accuracy of the above ");print("information.");

    }

    The function in Listing 26 calls two subfunctions: processPrevPage() andprocessNextPage() . The function takes the returned links and displays them,which allows customers to traverse pages. It also displays a disclaimer, noting thatthe author of the Web site isn't responsible for the information provided by Amazon.

    Add the code for functions, processPrevPage() and processNextPage() , tofunctions.php , as shown in listings 27 and 28.

    Listing 27. Calculate the previous page link

    function processPrevPage($pagenum){if($pagenum > 1){

    $previousPage = "Previous Page";}else{

    $previousPage = "Previous Page";}return $previousPage;

    }

    Listing 28. Calculate the next page link

    function processNextPage($totalPages, $pagenum){if($pagenum < 300 && ($pagenum+1)

  • 8/14/2019 Os Amazon1 PDF

    30/39

    $nextPage = "Next Page";}return $nextPage;

    }

    The code in these listings processes the link for the previous and next pages. Notice

    that the veto string for the processGETString() will be sent as pa , ensuring thatthe current pagenum variable isn't propagated.

    The code for displaying navigation links is now in place. See Figure 9 for samplebrowser output showing the navigation links.

    Figure 9. Display the navigation links at the bottom of the first page of theSporting Goods category

    developerWorks ibm.com/developerWorks

    Getting content with Amazon ECSPage 30 of 39 Copyright IBM Corporation 1994, 2008. All rights reserved.

    http://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/legal/copytrade.shtml
  • 8/14/2019 Os Amazon1 PDF

    31/39

    Exception handling

    Now that you have made the request, it is important to verify that no errors occurred.First, create a function, error() , as shown in Listing 29.

    Listing 29. Display error information

    function error($msg, $err, $result){print($msg);if(is_array($err)){

    $msg2 = $err[0]->Message;}else{

    $msg2 = $err->Message;}print($msg2);print_r($result->faultstring);print("

    ");print_r($result);

    }

    This function will display error information, providing that an error has occurred.Modify the printCategoryItems() , as shown in Listing 30. This code tests forerrors and uses the new error() function.

    Listing 30. Test $result for errors and display error information, if true

    ...$result = callSOAPFunction("ItemSearch", $array);

    if($result->faultstring || $result->Items->Request->Errors){error("Your search return 0 results, or perhaps there was anerror processing your request. The returned XML file withadditional error information is as follows:

    ",$result->Items->Request->Errors->Error, $result);

    }else{

    $items = $result->Items->Item;if($items){

    printItemsSection($innerTitle, $items);printPrevNextPage($result->Items->TotalPages, $pagenum);

    }}...

    There are two parts to look for in the returned SOAP construct. One is to check for$result->faultstring , and if a fault didn't occur, you need to check for errors inyour request by reviewing $result->Items->Request->Errors . If eithercondition exists, error information will be displayed; otherwise, code execution willresume.

    Your application is coming together nicely! Now you will move onto the search boxso your customers can better narrow down their searches.

    ibm.com/developerWorks developerWorks

    Getting content with Amazon ECS Copyright IBM Corporation 1994, 2008. All rights reserved. Page 31 of 39

    http://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/legal/copytrade.shtml
  • 8/14/2019 Os Amazon1 PDF

    32/39

    Section 7. Searching for items

    In this section, you will learn how to use the search box you created in to set up thecorrect SOAP request and retrieve specific items within a category, allowingcustomers to concentrate their searches. This section will reuse a lot of the codefrom the Browsing categories section, so the goal of this section is to show you howto dynamically parameterize your item search requests to Amazon.

    Retrieving submitted keywords from the search box

    Before you retrieve submitted keywords, you will need to enter some keywords intothe search box. Enter "golf clubs" into the keyword box, as shown in Figure 10.

    Figure 10. Enter keywords "golf clubs" in the keyword box

    developerWorks ibm.com/developerWorks

    Getting content with Amazon ECSPage 32 of 39 Copyright IBM Corporation 1994, 2008. All rights reserved.

    http://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/legal/copytrade.shtml
  • 8/14/2019 Os Amazon1 PDF

    33/39

    Now hit Enter or click the Search button. Now you will add to and parameterize theprintCategoryItems() function using the keywords variable submitted via GET(see Listing 31).

    Listing 31. Retrieving the keyword variable from the GET array

    function printCategoryItems(){

    if(isset($_GET['keyword'])){$keyword = $_GET['keyword'];$innerTitle = "Results for '$keyword' ";

    }$category = $_GET['category'];

    ...

    This will allow you to parameterize the request sent to Amazon.

    ibm.com/developerWorks developerWorks

    Getting content with Amazon ECS Copyright IBM Corporation 1994, 2008. All rights reserved. Page 33 of 39

    http://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/legal/copytrade.shtml
  • 8/14/2019 Os Amazon1 PDF

    34/39

    Parameterize the search parameters

    To parameterize the search parameters created in the $array construct, see Listing32.

    Listing 32. Parameterize the parameters, $array, used to construct the requestsent to Amazon

    ...print("The $category category doesn't exist");return;

    }

    $array = array('Operation' => 'ItemSearchRequest','ItemPage' => $pagenum,'SearchIndex' => $category,'ResponseGroup' => 'Medium','Keywords' => getKeyword($keyword, $displayCat));

    $result = callSOAPFunction("ItemSearch", $array);...

    Through getKeyword() , you can dynamically change the keywords passed to theitem search request. Create a function, getKeyword() , and place it in thefunctions.php file (see Listing 33).

    Listing 33. Return the needed keyword, depending whether $keyword is set

    function getKeyword(){if($_GET['keyword'] == ''){

    return $_GET['displayCat'];}else{

    return $_GET['keyword'];}

    }

    Thus, if keyword is set, meaning that a customer searched using the search box,the keyword will be returned from the function in Listing 33 and used as theKeywords input to the request, allowing you to change the input to the requestdynamically.

    This is all you need to do to change the input parameters dynamically to the itemsearch request. See the sample output for golf clubs in the Sporting Goods categoryin Figure 11.

    Figure 11. Search results for golf clubs in the Sporting Goods category

    developerWorks ibm.com/developerWorks

    Getting content with Amazon ECSPage 34 of 39 Copyright IBM Corporation 1994, 2008. All rights reserved.

    http://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/legal/copytrade.shtml
  • 8/14/2019 Os Amazon1 PDF

    35/39

    Notice that the results of your search terms match what you entered into the searchbox! You now have a functioning Web site, where users can browse items in specificcategories of Amazon, as well as search for items within these categories.

    Section 8. SummaryYou have created an Amazon storefront in PHP that allows customers to browsecategories and search for specific items within those categories. Your applicationsuccessfully submits and receives requests to and from Amazon ECS, allowing youto display products on your Web site. In Part 2 of this series, you will create ashopping cart for your application, allowing customers to purchase items securely at

    ibm.com/developerWorks developerWorks

    Getting content with Amazon ECS Copyright IBM Corporation 1994, 2008. All rights reserved. Page 35 of 39

    http://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/legal/copytrade.shtml
  • 8/14/2019 Os Amazon1 PDF

    36/39

    Amazon -- and providing you with a commission.

    developerWorks ibm.com/developerWorks

    Getting content with Amazon ECSPage 36 of 39 Copyright IBM Corporation 1994, 2008. All rights reserved.

    http://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/legal/copytrade.shtml
  • 8/14/2019 Os Amazon1 PDF

    37/39

    Downloads

    Description Name Size Download methodSource code for the Amazon store, Part 1 os-amazonphpstore1.zip 4KB HTTP

    Information about download methods

    ibm.com/developerWorks developerWorks

    Getting content with Amazon ECS Copyright IBM Corporation 1994, 2008. All rights reserved. Page 37 of 39

    http://download.boulder.ibm.com/ibmdl/pub/software/dw/opensource/os-amazonphpstore1.ziphttp://www.ibm.com/developerworks/library/whichmethod.htmlhttp://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/developerworks/library/whichmethod.htmlhttp://download.boulder.ibm.com/ibmdl/pub/software/dw/opensource/os-amazonphpstore1.zip
  • 8/14/2019 Os Amazon1 PDF

    38/39

    ResourcesLearn

    For a series of tutorials designed to broaden your PHP skills, see "Learning

    PHP," Part 1 , Part 2 , and Part 3 . "Boost application development with Amazon Web Services, Part 1" provides

    an overview of Amazon Web Services (AWS). AWS exposes raw productinformation and key parts of Amazon technology to third-party developers foruse in their applications.

    "Boost application development with Amazon Web Services, Part 2: Introductionto the Amazon Simple Queue Service" is the second in a series on creatingapplications with Amazon Web Services and, in this installment, you can learnhow to implement a Web service by using the Amazon Simple Queue Service.

    Learn how to configure Apache and PHP together . The default installation isPHP V4. Install PHP V5, and you shouldn't run into trouble.

    For more information about PHP SOAP, see the PHP manual: SOAP Functions .

    Back parameters for Amazon Web Services are available at GeneralParameters to all Operation Requests .

    The golden handbook on the Amazon E-Commerce Service (ECS) is AmazonWeb Services WSDL File .

    Learn more about using WSDL with SOAP by reading "Using WSDL in SOAPapplications ."

    For more Web services information, including IBM's Web services tools, seeNew to SOA and Web services .

    For an excellent developerWorks article on PHP, Web services, and SOAP,read "Access an enterprise application from a PHP script ."

    Visit the developerWorks Open source zone for extensive how-to information,tools, and project updates to help you develop with open source technologiesand use them with IBM's products.

    Visit the developerWorks SOA and Web services zone for extensiveinformation.

    Get products and technologies

    Before you begin to develop your Amazon storefront, you need an AmazonWeb Services developer token .

    You also need an Amazon Associates ID .

    Innovate your next open source development project with IBM trial software ,

    developerWorks ibm.com/developerWorks

    Getting content with Amazon ECSPage 38 of 39 Copyright IBM Corporation 1994, 2008. All rights reserved.

    http://www.ibm.com/developerworks/edu/os-dw-os-phptut1-i.htmlhttp://www.ibm.com/developerworks/edu/os-dw-os-phptut1-i.htmlhttp://www.ibm.com/developerworks/edu/os-dw-os-phptut1-i.htmlhttp://www.ibm.com/developerworks/edu/os-dw-os-phptut2-i.htmlhttp://www.ibm.com/developerworks/edu/os-dw-os-phptut3-i.htmlhttp://www.ibm.com/developerworks/edu/ws-dw-ws-aws1.htmlhttp://www.ibm.com/developerworks/edu/ws-dw-ws-aws2.htmlhttp://www.ibm.com/developerworks/edu/ws-dw-ws-aws2.htmlhttp://dan.drydog.com/apache2php.htmlhttp://us2.php.net/soaphttp://www.amazon.com/gp/aws/sdk/main.html/?s=AWSEcommerceService&v=4-0&p=PgOperationsCommonParameters#Optionalhttp://www.amazon.com/gp/aws/sdk/main.html/?s=AWSEcommerceService&v=4-0&p=PgOperationsCommonParameters#Optionalhttp://webservices.amazon.com/AWSECommerceService/AWSECommerceService.wsdlhttp://webservices.amazon.com/AWSECommerceService/AWSECommerceService.wsdlhttp://www.ibm.com/developerworks/webservices/library/ws-soap/http://www.ibm.com/developerworks/webservices/library/ws-soap/http://www.ibm.com/developerworks/webservices/library/ws-soap/http://www.ibm.com/developerworks/webservices/newto/http://www.ibm.com/developerworks/opensource/library/os-phpws/http://www.ibm.com/developerworks/opensource/library/os-phpws/http://www.ibm.com/developerworks/opensourcehttp://www.ibm.com/developerworks/webserviceshttp://www.amazon.com/developerhttp://www.amazon.com/developerhttp://www.amazon.com/associateshttp://www.ibm.com/developerworks/downloads/?S_TACT=105AGX44http://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/developerworks/downloads/?S_TACT=105AGX44http://www.amazon.com/associateshttp://www.amazon.com/developerhttp://www.amazon.com/developerhttp://www.ibm.com/developerworks/webserviceshttp://www.ibm.com/developerworks/opensourcehttp://www.ibm.com/developerworks/opensource/library/os-phpws/http://www.ibm.com/developerworks/webservices/newto/http://www.ibm.com/developerworks/webservices/library/ws-soap/http://www.ibm.com/developerworks/webservices/library/ws-soap/http://webservices.amazon.com/AWSECommerceService/AWSECommerceService.wsdlhttp://webservices.amazon.com/AWSECommerceService/AWSECommerceService.wsdlhttp://www.amazon.com/gp/aws/sdk/main.html/?s=AWSEcommerceService&v=4-0&p=PgOperationsCommonParameters#Optionalhttp://www.amazon.com/gp/aws/sdk/main.html/?s=AWSEcommerceService&v=4-0&p=PgOperationsCommonParameters#Optionalhttp://us2.php.net/soaphttp://dan.drydog.com/apache2php.htmlhttp://www.ibm.com/developerworks/edu/ws-dw-ws-aws2.htmlhttp://www.ibm.com/developerworks/edu/ws-dw-ws-aws2.htmlhttp://www.ibm.com/developerworks/edu/ws-dw-ws-aws1.htmlhttp://www.ibm.com/developerworks/edu/os-dw-os-phptut3-i.htmlhttp://www.ibm.com/developerworks/edu/os-dw-os-phptut2-i.htmlhttp://www.ibm.com/developerworks/edu/os-dw-os-phptut1-i.htmlhttp://www.ibm.com/developerworks/edu/os-dw-os-phptut1-i.html
  • 8/14/2019 Os Amazon1 PDF

    39/39

    available for download or on DVD.

    Discuss

    Get involved in the developerWorks community by participating indeveloperWorks blogs .

    About the authorTyler AndersonTyler Anderson graduated with a degree in computer science from Brigham YoungUniversity in 2004 and is currently in his last semester as a master's student incomputer engineering. In the past, he worked as a database programmer forDPMG.com, and he is currently an engineer for Stexar Corp., based in Beaverton,Ore.

    ibm.com/developerWorks developerWorks

    http://www.ibm.com/developerworks/blogs/http://www.ibm.com/developerworks/blogs/