How to Add Top 10 Amazon Products to Your Affiliate Website - Stevie Tee - Stevie Tee

How to Add Top 10 Amazon Products to Your Affiliate Website

When I set up an affiliate site, one of the first things I look to do is add a dynamic bestsellers list to the sidebar. Invariably I use wordpress for my affiliate sites and as far as I know there is no actual wordpress plugin available to do this easily (but then again, I haven’t looked, so theres a possibility that this post is moot…). So depending upon the theme I am using this means I have to edit the theme code directly. Now I know that you can lift a bit of javascript from the Amazon associates site itself and that will nicely iframe a bestselling products widget, but a lot of the time I just want a simple list that blends in with the wordpress theme I’m using and that I can incorporate on as many or as few pages in the site that I like. Now the point of this post is to share with you how I do this, and you have to bear in mind that I come from a coding background so some of it may be little advanced, however if you have edited WordPress themes before then it shouldn’t be too much trouble.

However before we get to that there are one of two things you need to do first.

1. Sign up as an Amazon Associate. – You’ll need this to affiliate your amazon links.

2. Sign up to the Amazon API – Once you have done that you will be able to create your API access keys, which you will need to add to the API calls we plan to make.

Ok so assuming you have covered the basics and have yourself an Amazon affiliate and API account we can progress to the next stage. If you don’t have a website yet then you need to get one, for the purposes of this article we will assume that you have a self-hosted wordpress site. Ideally you will be able to work on a site which has content which is suitable for promoting products on Amazon UK.

Vist http://www.amazon.co.uk – Link will open in a new tab and depending upon your personal settings you should see something like this:

Amazon Home.gif

I’m pretty sure you will be familiar with it. On the left hand side there are the categories. So say for example you are going to set up a site about the Playstation 3. A good site feature that will provide a little bit of value for your visitors (and some constant affiliated Amazon traffic for you) would be Amazon’s top 10 bestselling Playstation 3 games. So from the categories section on the Amazon homepage, hilight the Computers & Office category and Click on PC and Video Games. You should see something like this:

Amazon Video Games

Here we can choose from all of the sub-categories under the Video Games category itself. Since we are interested in Playstation 3 Games you should click the Playstation 3 category which will take you to the following screen:

Amazon PS3

On the right hand side of this screen you will see a best-sellers box like this one:

Amazon PS3 Bestsellers

Click on the link at the top that says: PC & Videogames : Sony Playstation 3. This will take you to the full rundown of the best selling Playstation 3 games on Amazon. Here we need to look at the URL in the address bar of your browser. To access a specific product category in the Amazon API you need the to know the category node. Now that you have drilled right down to the Playstation 3 bestsellers category you should be able to see the node as part of the url in the address bar:

Amazon Node

You can see for the Playstation 3 this is 676457011, but it will be different for you depending upon which category you are querying. You should make a note of this number, you will need it later on.

Now we need to get into the gory bits of the task. Editing the code. To keep things as simple as possible I am going to describe adding the relevant code changes for the default wordpress ‘TwentyTen’ theme. Now I wouldnt recommend you do this on a live implementation of this theme because as soon as you update wordpress (when a new version comes out for example), the code will be overwritten. So we’ll just use this theme for teaching purposes but I would recommend that you implement in any theme other than the one’s supplied with wordpress itself when you are ready to go.

So head to the theme folder and create a new php file called top10.php, the following php code can be copied and pasted directly into top10.php with only a few modifications. Now much of the code that deals with ‘signing’ the amazon query isn’t my own. Amazon introduced signed requests a year or so ago which caused mucho problems for many of us. Unfortunately I don’t recall the original source to credit them at the moment.

 <?php


  $serviceURL = 'http://ecs.amazonaws.co.uk/onca/xml?AWSAccessKeyId=[ACCESSKEY]&AssociateTag=
[ASSOCIATETAG]&BrowseNode=[NODE]&Operation=ItemSearch&ResponseGroup=Medium
&SearchIndex=[SEARCHINDEX]&Service=AWSECommerceService&Sort=salesrank'; 
  $serviceURL = amazonSign($serviceURL,"[SECRETACCESSKEY]");
  
  // Load the call and capture the document returned by eBay API
  $resp = simplexml_load_file($serviceURL);
  echo "<ul>";
  // If the response was loaded, parse it and build links  
  foreach ($resp->Items->Item as $item) {
  
    $url     = $item->DetailPageURL;
    $title    = $item->ItemAttributes->Title;     
    
    echo "<li><a href = \"$url\">$title</a></li>";

  }
  echo "</ul>";

  function amazonEncode($text)
  {
    $encodedText = "";
    $j = strlen($text);
    for($i=0;$i<$j;$i++)
    {
      $c = substr($text,$i,1);
      if (!preg_match("/[A-Za-z0-9\-_.~]/",$c))
      {
        $encodedText .= sprintf("%%%02X",ord($c));
      }
      else
      {
        $encodedText .= $c;
      }
    }
    return $encodedText;
  }

  function amazonSign($url,$secretAccessKey)
  {
    // 0. Append Timestamp parameter
    $url .= "&Timestamp=".gmdate("Y-m-d\TH:i:s\Z");

    // 1a. Sort the UTF-8 query string components by parameter name
    $urlParts = parse_url($url);
    parse_str($urlParts["query"],$queryVars);
    ksort($queryVars);

    // 1b. URL encode the parameter name and values
    $encodedVars = array();
    foreach($queryVars as $key => $value)
    {
      $encodedVars[amazonEncode($key)] = amazonEncode($value);
    }

    // 1c. 1d. Reconstruct encoded query
    $encodedQueryVars = array();
    foreach($encodedVars as $key => $value)
    {
      $encodedQueryVars[] = $key."=".$value;
    }
    $encodedQuery = implode("&",$encodedQueryVars);

    // 2. Create the string to sign
    $stringToSign  = "GET";
    $stringToSign .= "\n".strtolower($urlParts["host"]);
    $stringToSign .= "\n".$urlParts["path"];
    $stringToSign .= "\n".$encodedQuery;

    // 3. Calculate an RFC 2104-compliant HMAC with the string you just created,
    //    your Secret Access Key as the key, and SHA256 as the hash algorithm.
    if (function_exists("hash_hmac"))
    {
      $hmac = hash_hmac("sha256",$stringToSign,$secretAccessKey,TRUE);
    }
    elseif(function_exists("mhash"))
    {
      $hmac = mhash(MHASH_SHA256,$stringToSign,$secretAccessKey);
    }
    else
    {
      die("No hash function available!");
    }

    // 4. Convert the resulting value to base64
    $hmacBase64 = base64_encode($hmac);

    // 5. Use the resulting value as the value of the Signature request parameter
    // (URL encoded as per step 1b)
    $url .= "&Signature=".amazonEncode($hmacBase64);

    return $url;
  }
 
<?php>

The code above can be copied and pasted directly into your own top10.php. But in order for it to work you must change the following 4 items:

ACCESSKEY & SECRETACCESSKEY – You get these from the developer API when you register
ASSOCIATETAG=This is necessary to associate all traffice with your affiliate account
NODE=This is the category BrowseNode we identified earlier.
SEARCHINDEX= This is the category that you are searching – You can find a list of searchindexes here

For our PS3 example, the searchindex is VideoGames.

Having done this we have created the necessary code to display the top 10 bestelling items from your chosen category, now you need to hook it into the theme. Browse to the theme folder again and locate the sidebar.php. Now this is likely going to need tweaking depending upon which theme you are using but in essense you want to add the following code into the sidebar.php:

<ul>
<?php include (TEMPLATEPATH.'/top10.php'); ?>
</ul>

Because of the structure of the twentyten theme you need to stick it in before the dynamic sidebar reference but after this:

<div id="primary" class="widget-area" role="complementary">
<ul class="xoxo">

Which gives you this:

<div id="primary" class="widget-area" role="complementary">
<ul class="xoxo">
<ul>
<?php include (TEMPLATEPATH.'/top10.php'); ?>
</ul>

Note however that each individual sidebar element of the twentyten theme is held inside an list container so the final code would be something like:

<div id="primary" class="widget-area" role="complementary">
<ul class="xoxo">
<li class = "widget-container">
 <h3 class = "widget-title">Top 10 Playstation 3 Games</h3>
 <ul>
<?php include (TEMPLATEPATH.'/top10.php'); ?>
</ul>
</li>

Once you have done all the above you should be able to open up your site and see a basic list of top 10 best selling items from Amazon UK in your chosen category. Its not for everyone, but its a useful starting point and can be fleshed out to add thumbnail images or excerpts from the description if required.


Posted under: Affiliate Code

One Response to “How to Add Top 10 Amazon Products to Your Affiliate Website”

  1. Joe says:

    Thanks for sharing. Will give it a even though I’m no coder.


Leave a Reply