Setup Amazon Affiliate API with PHP - Product Advertising API

This tutorial is going to show you how to connect to Amazon's Affiliate API (Product Advertising API) using PHP to obtain product data.


Table Of Contents

  1. Introduction to the Amazon Affiliate API
  2. How to find an Amazon Item's ASIN
  3. How to get Amazon Product Advertising API Keys
  4. Amazon Affiliate API PHP Tutorial
  5. Full PHP code
  6. Existing Amazon API PHP Libraries

Introduction to the Amazon Affiliate API

Connecting to Amazon's API is a very powerful way display up-to-date data on various products your customers might be interested in. Amazon Affiliate Sites are some of the most profitable websites on the internet, far surpassing Google Adsense sites.

Amazon's Affiliate API is actually called the Product Advertising API, after being renamed from Amazon Associates Web Service. Using this API, we can lookup specific products on Amazon and obtain their information, such as live price, images, description and seller details.

This tutorial is going to show you, in the most simplest terms, how to lookup a product. We'll be using PHP's cURL library to access the API and extracting the returned data into an array for us to use.

Product Advertising Operations

We are going to be using Amazon's ItemLookup operation. Amazon has a few operations:

Operation Description
ItemSearch Search for items on Amazon
SimilarityLookup Look for similar items to ones you've already searched for
ItemLookup Lookup a specific item by amazon ID (ASIN) or ISBN.
Cart Operations A bundle of different cart operations for adding items directly into a user's cart

You can read more about the different Amazon Operations in their documentation.

How To Find an Amazon Items ASIN

Since we'll be using ItemLookup, we need to use either the item's amazon ASIN or ISBN (if it's a book) to lookup the item we are trying to find. You can obtain this information by looking up any item on amazon.com and searching for it on the item page. The ASIN is also found in the URL:

https://www.amazon.com/gp/product/B01IG0E1F0/ref=s9u_nwrsa_gw_i1?

The bolded part is the Amazon ASIN.

How to get Amazon Product Advertising API Keys

We have our item details, we know what operation we'll be using and we know the language we will be coding in (PHP!).

The last piece of the puzzle is to get our developer access keys. If you've ever used an API, you'll be familiar with this process.

Just head over to Amazon's Product Adversting API page and sign up to access it. You can use your Amazon account to do this quickly. Next, you'll need to register for a secret key and an access key. This can be done by going to the Manage Your Account section and clicking on the security credentials area.

Amazon Developer Keys Setup

Amazon Affiliate API PHP Tutorial

Now let's write some code.

For the purpose of this tutorial, I'll create a simple PHP Class that we'll use to make any calls to the API. We can then build on this class to add in more operations in the future.

Class Skeleton:

<?php

class AmazonAPI {

    var $amazon_aff_id;
    var $amazon_access_key;
    var $amazon_secret_key;

    var $url_params;
    var $itemID;
    var $xml;

    var $operation;
    var $signature;
    var $response_groups = "Small,Images,OfferSummary";

    var $error_message;
    var $error=0;
    

    public function __construct($affid, $access, $secret)
    {
        $this->amazon_aff_id = $affid;
        $this->amazon_access_key = $access;
        $this->amazon_secret_key = $secret;
    }

    public function build_url()
    {
        
    }

    public function item_lookup()
    {
        
    }

}

This simple skeleton class is our starting point. If you just want to skip to the fully working code without understanding the nuts and bolts, click here.

Every time we use this class, we'll initiate it like so:

$amazon = new Amazon($affid, $secret, $access);

The $affid corresponds to our associates-id at Amazon.com that we use for Affiliates. The Secret and Access codes you can obtain from the How To Obtain Product Advertising API Keys section.

Building the Amazon API URL

In order to use the ItemLookup function, we need to make a call to the Amazon API URL:

http://webservices.amazon.com/onca/xml?

This URL takes several variables that will determine what we lookup. We need to specify the following:

Variable Example
Access Key 382hfh2hgfy3yy4y8385838528
Associates ID Patchesoft-13
Operation ItemLookup
Response Group Small,Images,OfferSummary
Service AWSECommerceService
Timestamp 2017-03-18 02:22:22
Version 2013-08-01

Some of the above variables we don't need to worry about at all, such as Service and Version. But let's take a look at some of the ones we don't know:

Operation - we mentioned the API has several operations you can use. We are using the ItemLookup operation here but you can use any of the listed ones in their API.

Response Group - This determines what data you wish to receive from your API request. In the above example, we use Small,Images,OfferSummary. Each Response Group can be separated by a comma. In this case Small means we want a basic summary of the items data, a list of all images associated with the product and a list of information about the item's pricing. List of Response Groups.

TimeStamp - We need to make sure the request we make has a valid timestamp in the required format. If you follow this guide, you'll be fine.

Taking all this information in, let's write our build_link function which will apply all these variables to our Amazon API URL.

public function build_url()
    {
        $url = "http://webservices.amazon.com/onca/xml?";

        $this->response_groups = str_replace(",", "%2C", $this->response_groups);

        $url_params = "AWSAccessKeyId=" . $this->amazon_access_key;
        $url_params .= "&AssociateTag=" . $this->amazon_aff_id;

        if(!empty($this->itemID)) {
            $url_params .= "&ItemId=" . $this->itemID;
        }

        $url_params .= "&Operation=" . $this->operation;
        $url_params .= "&ResponseGroup=" . $this->response_groups;
        $url_params .= "&Service=AWSECommerceService";
        $url_params .= "&Timestamp=" . rawurlencode(gmdate("Y-m-d\TH:i:s\Z"));
        $url_params .= "&Version=2013-08-01";

        $this->url_params = $url_params;

        $url .= $url_params;
        $url .= "&Signature=" . $this->generate_signature();

        return $url;
    }

We assign all our variables to the the variable $url_params. In some instances, we need to take care of URL formatting because Amazon requires the data to be properly formatted when sent to them. I.e. $this->response_groups = str_replace(",", "%2C", $this->response_groups);

We'll be assigning the $this->itemID in another function.

The generate_signature() function will be explained next.

But this takes care of most of the hard work we need for building our API request.

Amazon API Signature Request

Each API request we make requires a signature. This signature is made up of a hash sequence of data, including making use of your secret key you obtained earlier. The code for generating the signature is below:

public function generate_signature()
    {
        $this->signature = base64_encode(hash_hmac("sha256",
            "GET\nwebservices.amazon.com\n/onca/xml\n" . $this->url_params,
            $this->amazon_secret_key, True));
        $this->signature = str_replace("+", "%2B", $this->signature);
        $this->signature = str_replace("=", "%3D", $this->signature);
        return $this->signature;
    }

ItemLookup Operation

Finally, we complete the ItemLookup function.

public function item_lookup($id)
    {
        $this->operation = "ItemLookup";
        $this->itemID = $id;

        $url = $this->build_url();

        $ch = curl_init();  

        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);

        $output = curl_exec($ch);

        curl_close($ch);

        $this->xml = simplexml_load_string($output);
        return $this;
    }

This function uses cURL to send a request to the Amazon API URL we just constructed in build_url(). It then takes the response given back and loads it into an XML object using the native php simplexml_load_string().

We can now access the item data from Amazon using the $this->XML variable.

For example, to grab the item's name, we can do:

$itemname = $this->XML->Items->Item->ItemAttributes->Title;

Learning the XML structure can be a bit of a pain in the beginning, but using var_dump on the object will help you understand it better. I wrote a simple function to get the data I needed below:

public function check_for_errors()
    {
        if(isset($this->xml->Error)) {
            $this->error_message = $this->xml->Error->Message;
            $this->error = 1;
        }
        if(isset($this->xml->Items->Request->Errors)) {
            $this->error_message = $this->xml->Items->Request->Errors->Error->Message;
            $this->error = 1;
        }
        return $this->error;
    }

    public function get_item_price($product)
    {
        $price = 0;
        if(isset($product->LowestNewPrice)) {
            $price = $product->LowestNewPrice->Amount;
        } elseif(isset($product->LowestUsedPrice)) {
            $price = $product->LowestUsedPrice->Amount;
        } elseif(isset($product->LowestCollectiblePrice)) {
            $price = $product->LowestCollectiblePrice->Amount;
        } elseif(isset($product->LowestRefurbishedPrice)) {
            $price = $product->LowestRefurbishedPrice->Amount;
        }
        return $price;
    }

    public function get_item_data()
    {
        if($this->check_for_errors()) return null;

        $product = $this->xml->Items->Item;
        $item = new STDclass;
        $item->detailedPageURL = $product->DetailPageURL;
        $item->link = "https://www.amazon.com/gp/product/".$this->itemID."/?tag=" . $this->amazon_aff_id;
        $item->title = $product->ItemAttributes->Title;
        $item->smallImage = $product->SmallImage->URL;
        $item->mediumImage = $product->MediumImage->URL;
        $item->largeImage = $product->LargeImage->URL;

        $item->price = $this->get_item_price($product->OfferSummary);

        return $item;
    }

Using the Amazon Affiliate API

To use the class, just simple do the following:

$amazon = new AmazonAPI("associate-id", "secret-key", "access-key");
$item = $amazon->item_lookup("ASIN")->get_item_data();

echo $item->title;
exit();

You can now make your own affiliate script to obtain products from Amazon. There are some great Amazon Affiliate examples on the internet that you can take a look at to see how they advertise products. With the API toolset, you can be a lot more creative with your advertising marketing.

You can find the full code for this tutorial below:

<?php

class AmazonAPI {

    var $amazon_aff_id;
    var $amazon_access_key;
    var $amazon_secret_key;

    var $url_params;
    var $itemID;
    var $xml;

    var $operation;
    var $signature;
    var $response_groups = "Small,Images,OfferSummary";

    var $error_message;
    var $error=0;
    

    public function __construct($affid, $access, $secret)
    {
        $this->amazon_aff_id = $affid;
        $this->amazon_access_key = $access;
        $this->amazon_secret_key = $secret;
    }

    public function build_url()
    {
        $url = "http://webservices.amazon.com/onca/xml?";

        $this->response_groups = str_replace(",", "%2C", $this->response_groups);

        $url_params = "AWSAccessKeyId=" . $this->amazon_access_key;
        $url_params .= "&AssociateTag=" . $this->amazon_aff_id;

        if(!empty($this->itemID)) {
            $url_params .= "&ItemId=" . $this->itemID;
        }

        $url_params .= "&Operation=" . $this->operation;
        $url_params .= "&ResponseGroup=" . $this->response_groups;
        $url_params .= "&Service=AWSECommerceService";
        $url_params .= "&Timestamp=" . rawurlencode(gmdate("Y-m-d\TH:i:s\Z"));
        $url_params .= "&Version=2013-08-01";

        $this->url_params = $url_params;

        $url .= $url_params;
        $url .= "&Signature=" . $this->generate_signature();

        return $url;
    }

    public function generate_signature()
    {
        $this->signature = base64_encode(hash_hmac("sha256",
            "GET\nwebservices.amazon.com\n/onca/xml\n" . $this->url_params,
            $this->amazon_secret_key, True));
        $this->signature = str_replace("+", "%2B", $this->signature);
        $this->signature = str_replace("=", "%3D", $this->signature);
        return $this->signature;
    }

    public function item_lookup($id)
    {
        $this->operation = "ItemLookup";
        $this->itemID = $id;

        $url = $this->build_url();

        $ch = curl_init();  

        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);

        $output = curl_exec($ch);

        curl_close($ch);

        $this->xml = simplexml_load_string($output);
        return $this;
    }

    public function check_for_errors()
    {
        if(isset($this->xml->Error)) {
            $this->error_message = $this->xml->Error->Message;
            $this->error = 1;
        }
        if(isset($this->xml->Items->Request->Errors)) {
            $this->error_message = $this->xml->Items->Request->Errors->Error->Message;
            $this->error = 1;
        }
        return $this->error;
    }

    public function get_item_price($product)
    {
        $price = 0;
        if(isset($product->LowestNewPrice)) {
            $price = $product->LowestNewPrice->Amount;
        } elseif(isset($product->LowestUsedPrice)) {
            $price = $product->LowestUsedPrice->Amount;
        } elseif(isset($product->LowestCollectiblePrice)) {
            $price = $product->LowestCollectiblePrice->Amount;
        } elseif(isset($product->LowestRefurbishedPrice)) {
            $price = $product->LowestRefurbishedPrice->Amount;
        }
        return $price;
    }

    public function get_item_data()
    {
        if($this->check_for_errors()) return null;

        $product = $this->xml->Items->Item;
        $item = new STDclass;
        $item->detailedPageURL = $product->DetailPageURL;
        $item->link = "https://www.amazon.com/gp/product/".$this->itemID."/?tag=" . $this->amazon_aff_id;
        $item->title = $product->ItemAttributes->Title;
        $item->smallImage = $product->SmallImage->URL;
        $item->mediumImage = $product->MediumImage->URL;
        $item->largeImage = $product->LargeImage->URL;

        $item->price = $this->get_item_price($product->OfferSummary);

        return $item;
    }

}

?>

Existing Amazon Affiliate API PHP Libraries

There are a couple of useful pre-built libraries out there that already do this, but they are lot more complicated and feature-rich than what I needed. If you need something more substantial, take a look at these:




Enjoyed that? Check These Posts Out

Pro Login User Management System - PHP

Setup the new Envato API to check Product Codes with PHP

Fullcalendar with PHP and CodeIgniter - Adding Events - Part 3

Fullcalendar with PHP and CodeIgniter - Modifying Events - Part 4

Article Comments

Let us know your thoughts below by adding a quick comment!

Leave A Comment