PEAR Articles

  Home arrow PEAR Articles arrow Page 2 - Using Web Service APIs (Amazon and Yah...
PEAR ARTICLES

Using Web Service APIs (Amazon and Yahoo!) with PEAR
By: Chris Moyer
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 3
    2008-07-23

    Table of Contents:
  • Using Web Service APIs (Amazon and Yahoo!) with PEAR
  • Services_Amazon
  • Services_Yahoo
  • Further Steps

  •  
     

    SEARCH CODEWALKERS

    TOOLS YOU CAN USE

    advertisement

    Using Web Service APIs (Amazon and Yahoo!) with PEAR - Services_Amazon


    (Page 2 of 4 )

    Installation of PEAR packages is straightforward:


    pear install --alldeps channel://pear.php.net/XML_Serializer-0.18.0

    pear install -alldeps channel://pear.php.net/Services_Amazon-0.7.1


    You need to use the full package name and manually install XML_Serializer, rather than simply "pear install Services_Amazon," because they are still considered beta releases. Keep this in mind; if you update these packages later, the interface may change. In my experience, while they are "beta," they still provide a robust and useful encapsulation of the Amazon API.

    To use the Amazon API, you'll need to obtain an Access Key and Associate ID. For the Access Key, you'll need to sign up for an Amazon Web Services Account, and then navigate to the "View Access Key Identifiers" section, where you can cut and paste the access key. To obtain an Associate ID, you'll need to sign up for the Amazon Affiliate Program, and receive an Associate ID during that process. This ID allows Amazon to credit your account with a percentage of sales generated through your use of their web services.

    The Services_Amazon package includes an interface to the disabled Amazon ECS3 service, in addition to the active ECS4 service. You'll want to be sure to use the latter. The code below assumes that you've loaded your access key and associate ID into variables named $ACCESS_KEYY and $ASSOC_ID.

    require('PEAR.php');

    require('Services/AmazonECS4.php');


    $amazon = &new Services_AmazonECS4($ACCESS_KEY, $ASSOC_ID);

    At this point, we've created an interface object through which we'll perform our interactions. The Amazon API uses a simple REST (Representational State Transfer) API, so a connection isn't established until you actually issue requests. At that point, the API will make an HTTP GET request to the appropriate Amazon URL and return a pre-parsed dataset. Most API calls will return an associative array including the Result Code, Request Parameters and Result data.

    To get an idea for what the API is doing behind the scenes, you can use the getLastuUrl() and getRawResult() methods on the Services_AmazonECS4 instance.


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

    array('Keywords' => 'web development'));

    if (PEAR::isError($results)) {

    die('Sorry, there was a problem with your search: ' .

    $results->getMessage());

    }

    print $amazon->getLastUrl();


    This will output a URL similar to the following:


    http://webservices.amazon.com/onca/xml?
    Service=AWSECommerceService&Keywords=web+development&Operation=
    ItemSearch&SearchIndex=Books&AWSAccessKeyId=[ACCESSKEY]2&AssociateTag=
    [ASSOCIATE_ID]&Version=2005-10-05


    And the raw output obtained with getRawResult() (this is trimmed down from the full result set):


    <ItemSearchResponse>

    <OperationRequest>

    <HTTPHeaders>

    <Header Name="UserAgent" Value="Services_AmazonECS4/0.7.1"/>

    </HTTPHeaders>

    <RequestId>0XYS02YS3EK8QHRSMEA0</RequestId>

    <Arguments>

    <Argument Name="SearchIndex" Value="Books"/>

    <Argument Name="Service" Value="AWSECommerceService"/>

    <Argument Name="Keywords" Value="web development"/>

    <Argument Name="Operation" Value="ItemSearch"/>

    <Argument Name="Version" Value="2005-10-05"/>

    <Argument Name="AssociateTag" Value="[ASSOCIATE ID]"/>

    <Argument Name="AWSAccessKeyId" Value="[ACCESS KEY]"/>

    </Arguments>

    <RequestProcessingTime>0.0638430118560791</RequestProcessingTime>

    </OperationRequest>

    <Items>

    <Request>

    <IsValid>True</IsValid>

    <ItemSearchRequest>

    <Keywords>web development</Keywords>

    <SearchIndex>Books</SearchIndex>

    </ItemSearchRequest>

    </Request>

    <TotalResults>3234</TotalResults>

    <TotalPages>324</TotalPages>

    <Item>

    <ASIN>0321344758</ASIN>

    <DetailPageURL>http://www.amazon.com/gp/redirect.html%3FASIN=0321344758%
    26tag=iar-20%26lcode=xm2%26cID=2025%26ccmID=165953%26location=/Dont-Make-
    Me-Think-Usability/dp/0321344758%
    253FSubscriptionId=0TSEV33DPJ44TA9Y2E82</DetailPageURL>

    <ItemAttributes>

    <Author>Steve Krug</Author>

    <Manufacturer>New Riders Press</Manufacturer>

    <ProductGroup>Book</ProductGroup>

    <Title>

    Don't Make Me Think: A Common Sense Approach to Web Usability, 2nd Edition

    </Title>

    </ItemAttributes>

    </Item>


    ... More Items ...


    </Items>

    </ItemSearchResponse>


    As you can see, the Services_Amazon interface takes quite a bit of complexity and turns it into some simple API calls. Here we'll again make use of the itemSearch() method and generate a listing of books.


    <?

    require('PEAR.php');

    require('Services/AmazonECS4.php');


    $amazon = &new Services_AmazonECS4($ACCESS_KEY, $ASSOC_ID);

    $results = $amazon->itemSearch('Books', array('Keywords' => 'web development'));


    if (PEAR::isError($results)) {

    die('Sorry, there was a problem with your search: ' . $results-
    >getMessage());

    }


    print '<ul>';

    foreach ($results['Item'] as $product) {

    printf('<li><a href="%s">%s</a> - %s</li>',

    $product['DetailPageURL'],

    $product['ItemAttributes']['Title'],

    join(', ', $product['ItemAttributes']['Author']));

    }

    print '</ul>';

    ?>


    The API takes care of many details: parsing the XML, turning the Authors into an array and checking for errors.

    In addition to searching the Amazon inventory, the API also allows for the creation and maintenance of a shopping cart. You can add items to the cart based on the ASIN parameter of the product results. Once the user is done shopping you'll redirect them or provide them a link to the cart's PurchaseURL, where Amazon will take care of billing the user and crediting your Associate ID with a portion of the sale.

    In this example, we create a cart, add two pre-selected items to it, and send the user to Amazon.


    $cart = $amazon->CartCreate(

    array('ASIN' => '0321344758', 'Quantity' => 1));

    $amazon->CartAdd($cart['CartId'], $cart['HMAC'],

    array('ASIN' => '0596517742', 'Quantity' => 2));


    header('location: ' . $cart['PurchaseURL']);


    For brevity, error checking of the API calls has been omitted. For a production application, it should always be included.

    The Amazon API with the Services_Amazon wrapper from PEAR provides an easy way to allow users to search for books, music and nearly everything else under the sun. When used with an associate id, it is a simple way to build a store front using the Amazon System.

    More PEAR Articles Articles
    More By Chris Moyer

    blog comments powered by Disqus

    PEAR ARTICLES ARTICLES

    - Installing PEAR
    - PEAR: an Introduction
    - Managing robots.txt using PHP: Generating Dy...
    - Deleting Authors from a PEAR Content Managem...
    - PEAR CMS: Index and Delete Scripts
    - Listing Articles for a PEAR Content Manageme...
    - Building an Authors Page for a PEAR CMS
    - Building the View Details Page in a PEAR CMS
    - Creating the Main Pages of a PEAR CMS
    - Completing the Login Script for a PEAR CMS
    - User Authentication for a PEAR CMS
    - A PEAR CMS: Examining the Code
    - Building a Content Management System with PE...
    - Installing a PEAR Package
    - My PEAR: The Beginning


    © 2003-2012 by Developer Shed. All rights reserved. DS Cluster 3 - Follow our Sitemap