Posted by: mashuphowto | mars 24, 2008

Amazon Associates & AWS - PHP5 and jQuery

http://docs.amazonwebservices.com/AWSEcommerceService/2005-03-23/index.html 

Amazon Associates & AWS - PHP5 and jQueryWork in progress

http://moblur.org/workshop/ajax_amazon_associates/ 

Part #1 - Search engineEnter Title keywords and press the Return key (US books only).Examples : xml, jquery, php 5, perl
 
by Rajesh Lal - Professional Web Widgets with CSS, DOM, JSON and Ajax
by LynnAnne Merten - DTIC technical report
by Joshua Eichorn - Understanding AJAX: Consuming the Sent Data with XML and JSON, Digital ShortcutPHP5 Source codeBasicaly, this script builds the SOAP Query array, instanciate a Soap client with various options, place a call to Amazon Web Service and return the data.
Note: You must be registered with Amazon web services (AWS) to use this script.
 
<?
define(’SITE_ROOT’, $_SERVER['DOCUMENT_ROOT']);
 
/**
 * I set up a cronjob to update this one every hour (see below)
 */
$wsdl_path = SITE_ROOT . ‘/path/cache/AWSECommerceService.wsdl’;
 
$subscription_id = ‘<your AWS subscription id>’;
 
/**
 * The best pratice here would be to sanitize the keywords
 */
$search_query     = array(
                 ‘SubscriptionId’ => $subscription_id,
                 ‘AssociateTag’   => ‘moblurorg-21′,
                 ‘Request’        => array(
                                         “Title”         => $_GET['keywords'],
                                         “Count”         => $_GET['count'],
                                         “SearchIndex”   => “Books”,
                                         “ResponseGroup” => “Medium”
                                ),
                   );
 
/**
 * PHP5 SoapClient initialization
 */
$c = new SoapClient($wsdl_path, array(
    ‘encoding’=>’UTF-8′, 
    ‘compression’ => SOAP_COMPRESSION_ACCEPT | SOAP_COMPRESSION_GZIP
    )
);
 
/**
 * Calling the Soap method
 */
$result = $c->__call(’ItemSearch’, array(’body’ => $search_query));
 
/**
 * If there’s any error, return it using json_encode()
 */
if(is_object($result->Items->Request->Errors->Error)) {
    print json_encode($result->Items->Request->Errors->Error);
    

else {
    /**
     * No error, returning the whole php object as Json data using json_encode()
     */
    if(is_array($result->Items->Item)) {
        print json_encode($result->Items->Item);
    }
}
?>
Minimum xHTML
<input type=”text” name=”keyword” value=”" id=”keyword”/>
<span id=”waiter” style=”display:none;”>
   <img src=”ajax-loader-small.gif” mce_src=”ajax-loader-small.gif” style=”border: none;” alt=”loading…”/>
</span>
 
<div id=”container”></div>
Minimum CSS 2.0
#container {
    text-align: center;
    width: 100%;
}
.book {
    float:left;
    text-align:center;
    width:30%;
    height:200px;
}
Javascript - jQuery Source code
function get_books(options) {
 
 var defaults = {
  ‘keywords’   : ”,
  ‘max_items’   : 3,
  ‘debug’    : true
 };
 
 if(options.keywords && options.keywords.length > 0) {
 
  /** 
   * Setting unsetted options to defaults
  */
  for (var o in defaults) {
   if(!options[o] || options[o] == undefined) {
    options[o] = defaults[o];
   }
  }
  
  /** 
   * jQuery Ajax
  */
  $.ajax(
   {
    type:   ‘GET’,
    url:   ’service.php?keywords=’ + options.keywords + ‘&count=’ + options.max_items,
    cache:  false,
    dataType: ‘json’,
    success:  function(json){
         /** 
          * We’ve got an error from AWS, displaying it.
         */
         if(json['Message'] != undefined) {
          $(”#container”).html(’ ‘);
          $(”#container”).append(’<p>’+json['Message']+’</p>’);
          return;
         } 
         else {
          /** 
           * Trimming results to minimum from ever options 
           * or AWS answer, wichever is the lesser 
          */
          var stop_at = Math.min.apply({},[options.max_items, json.length-1]);
 
          /** 
           * Looping through records
          */
          for (var i in json) {
           i = parseInt(i);
           /** 
            * This is a new search, reseting the container
           */
           if(i == 0) {$(”#container”).html(’ ‘);}
 
           /** 
            * The item has image informations
           */
           if(typeof(json[i]['SmallImage']) == ‘object’) {
            var img_url = json[i]['SmallImage']['URL'];
            var img_w  = json[i]['SmallImage']['Width']['_'];
            var img_h  = json[i]['SmallImage']['Height']['_']
           }
           else {
            /** 
             * Default image settings
            */
            var img_url = ‘/public/no-img.gif’;
            var img_w  = 60;
            var img_h  = 40;
           }
           
           /** 
            * Appending result to the container
           */
           $(”#container”).append(’<p class=”book”><a href=”‘+json[i]['DetailPageURL']+
              ‘”><img src=”‘+ img_url +’” width=”‘+img_w+’” height=”‘+img_h+
              ‘” alt=”‘+ json[i]['ItemAttributes']['Title'] + ‘”/></a><br/>by ‘+
              json[i]['ItemAttributes']['Author'] + ‘ - ‘ + json[i]['ItemAttributes']['Title']+
              ‘</p>’);
           
           /** 
            * Safely closing our display if stop’s reached
           */
           if(i == stop_at) {
              $(”#container”).append(’<div style=”clear:both;”></div>’);
              return;
           }
          }
          
         }
        }
   }
  );
 } 
}
 
$(document).ready(function() {
 
 /** 
  * Displaying the ‘Ajax web2.0 waiter’ during AWS calls
 */
 $(”#waiter”).ajaxStart(function(){
  $(this).show();
 }).ajaxComplete(function(){
  $(this).hide();
 });
 
 /** 
  * The fonction is triggered each time the input receive the keycode 13 (return)
 */
  $(’#keyword’).bind(’keyup’, function(e) {
   if(parseInt(e.keyCode) == 13) {
    get_books({’keywords’: $(’#keyword’).attr(’value’)});
   }
  });
 
});
Appendix - CronjobThe content of “http://webservices.amazon.com/AWSECommerceService/AWSECommerceService.wsdl” will be saved as /path/cache/AWSECommerceService.wsdl every hour at 05 minutes. 
#5 * * * * wget -q -O /path/cache/AWSECommerceService.wsdl \ 
http://webservices.amazon.com/AWSECommerceService/AWSECommerceService.wsdl

OR

AMAZON.COM CURL-REST Parser.
Copyright ©2004, Jon Ellis-Jones.

This script is a nice and easy way of parsing REST data from Amazon. The
idea is, you can obtain data about Amazon products for display/storage in
a database, eg. If you had a website about books, you could store amazon’s
review or price, images, dimensions etc about each book - the posibilities
are endless.

see: http://www.amazon.com/webservices for more information.

NB : this script works for all amazon subsites, such as amazon.co.uk/amazon.de,
just modify the areas in the script. for more help, see the URL above.

PREREQUISITES:
————–

You must have the cURL extension enabled in PHP. See below URL for details:
http://www.weberdev.com/Manuals/PHP/ref.curl.html

Leave a response

Your response:

Catégories