|
By Lynn Kyle
| A Developer Voice Article--The Developer Voice series features articles by developers for developers. Learn how to submit your own article on the Co-Marketing page. Add your review and let others know what you think. |
In this article, we’ll discuss how to use and connect Amazon Associates Web Service with your Amazon Associates account by using PHP and REST requests to increase your revenue from people who purchase Amazon merchandise through your site. This information is intended as a basic overview for the new developer who is unfamiliar with the power of the Amazon Associates Web Service.
The topics we'll be covering are:
- Getting your Amazon Associates tag and Amazon Web Services access key ID.
- Formulating your REST queries.
- Using your REST queries with PHP.
- Converting XML to PHP.
- Creating a shopping cart.
- Passing your Amazon Associates tag into the query.
- Examining a pre-built example, Simple Store.
- Looking at real-world examples of the web service.
Getting Your Amazon Associates Tag and Amazon Web Services Access Key
The Amazon Associates program offers site owners who feature Amazon products a percentage of the purchase price, up to 8.5 percent. Any merchandise purchased from Amazon through your site will be tagged with your distinct Amazon Associates tag in the query string, allowing Amazon to keep track of and credit you for these purchases. When you sign up, you’ll give Amazon information about how to pay you your percentage.
You can create your Amazon Associates account at http://affiliate-program.amazon.com/gp/associates/join.
You can stop at this step and just place the Amazon-provided code for the Amazon Associates link on your site. You can also create your own storefront with products you recommend with just a few clicks.
However, to truly customize and exploit the vast amount of product information and product reviews, as well as to create unique groupings of products and product searches, you need the web service. With few exceptions, Amazon Associates Web Service grants you access to all the information you see on Amazon.
You can get your access key from Amazon Web Services by joining the community at
http://aws.amazon.com. You’ll be given an AWS key to use in all your web service requests after you register.
Formulating Your REST Queries
Now that you have your Amazon Associates account and Amazon Web Services key, you’ll need to programmatically create requests for information from Amazon Associates Web Service. Currently, either SOAP or REST will work, but REST requests are easier to use. Unlike SOAP, REST has no framework. The downside of REST is that it doesn’t have the ability of SOAP to use multiple protocols and asynchronous requests. However, for small web sites and new systems, REST is generally the better choice. For the purposes of this article, REST is more than sufficient, and it’s both clearer and easier to understand.
Here’s an example. Take a look at the following simple REST request. You should be able to figure out what the results will be.
http://ecs.amazonaws.com/onca/xml?Service=AWSECommerceService&
AWSAccessKeyId=[YourKeyHere]&
Operation=ItemSearch&
SearchIndex=Books&
Author=Rowling
The huge advantage that REST has to offer is the ability to test requests directly and easily. After you modify the request slightly, you can enter it into your browser’s Address bar to see the XML results. The only change you need to make is to put the AWS key you were given when you signed up in place of [YourKeyHere]. The key should be 20 characters long.
Give it a try yourself. Before going any further, add your key and paste the updated request into the Address bar. You should see an XML listing of books by an author named Rowling. Being able to test your REST request directly in the Address bar gives you a distinct advantage over SOAP requests. You can test your REST requests before putting them into your PHP code. We’ll discuss how you can form this request in PHP shortly, but for now, let’s take a look at the specific parts of this REST request:
The base URL is:
http://ecs.amazonaws.com/onca/xml?Service=AWSECommerceService
This URL is used for all requests to Amazon.com. (If you need to reference Amazon in another locale, refer to the technical documentation for the correct base URL.)
The next part of the example is:
AWSAccessKeyId=[YourKeyHere]
As mentioned above, [YourKeyKere] is where you need to insert your own AWS key.
Operation=ItemSearch
In the example above, the REST request is performing a search for an item. This request will result in a broad list of possible matches. In the case of the example above, you get a list of books by the author with the name Rowling.
But ItemSearch is not your only option. You can use other parameters for the Operation parameter, such as ItemLookup and SimilarityLookup.
With ItemLookup, you can zero on a specific item. Note the following example:
http://ecs.amazonaws.com/onca/xml?Service=AWSECommerceService&
AWSAccessKeyId= [YourKeyHere]&
Operation=ItemLookup&
ItemId=0471774979
Instead of the argument SearchIndex, this request uses ItemId. Here, you specify a specific Amazon Standard Identification Number (ASIN). Amazon assigns this unique number to each product. In this case, it’s the book The Unofficial Guide to Macromedia Dreamweaver 8 (Unofficial Guide).
SimilarityLookup returns a list of items that are similar to the one in the query. Note the following example:
http://ecs.amazonaws.com/onca/xml?Service=AWSECommerceService&
AWSAccessKeyId=[YourKeyHere]&
Operation=SimilarityLookup&
ItemId=0471774979
This time, you’ll see results that are similar to results for The Unofficial Guide to Macromedia Dreamweaver 8 (Unofficial Guide). As in the example above, you’ll use an ASIN number.
You can also use SellerListingSearch and SellerListingLookup in much the same way.
By now, you have an idea of the flexibility that the REST requests to the web service give you. What we’ve discussed is just a small part of what you can do. With few exceptions, anything you see on an Amazon product listing can be queried.
For example, if you are using ItemLookup, you can use other parameters to display the condition of the product, the shipping information, or reviews.
After you know what it is you want to query, you have enormous flexibility. One of the most useful web sites for helping you formulate your URL strings for your REST requests is www.awszone.com. At this site, you can create both REST and SOAP requests for any parameter you desire and see them in action. It’s an extremely useful tool that allows you to check your beta code.
Delving more deeply into the specifics of these parameters is outside the scope of this article. For more helpful links, check out the Additional Resources section of this article.
Using Your REST Queries with PHP
Amazon Associates Web Service is a powerful resource, but being able to paste your REST requests into a browser isn’t enough. You need to embed them into your PHP code. As a PHP coder, you can see how breaking apart the query string makes sense. Look at the following sample code:
<?php
$request = 'http://ecs.amazonaws.com/onca/xml?Service=AWSECommerceService&' .
' AWSAccessKeyId=[YourKeyHere]&Operation=ItemSearch&SearchIndex=DVD&Actor=Brad%20Pitt';
$response = file_get_contents($request);
echo htmlspecialchars($response, ENT_QUOTES);
?>
The file_get_contents function does all the work. This function connects to the web service and grabs the resulting data. This then is the basic PHP REST request with no bells and whistles. You can break up the $request into variables that you can use to customize your REST request appropriately, as well as modify the parameters.
After you’ve figured out which parameters you want to run, the next step is to parse the XML data your query returns into HTML.
Converting XML to PHP
Your REST request has worked, and now you have a page full of XML data. You need to do something with the XML data to help your visitors see it in HTML. As a result, they will be able to read the data and possibly make a purchase from your site, earning you money with your Amazon Associates account that you’ve carefully tied into the data. Your best bet for converting the returned XML data into user-friendly HTML is to use an XSLT stylesheet and PHP:PEAR’s XML_Transformer package.Two very useful overviews of the conversion process can be found at the XML.com site here: http://www.xml.com/lpt/a/2003/06/18/php-xml.html and at zend.com here: http://www.zend.com/php5/articles/php5-xmlphp.php
Creating a Shopping Cart
You’ve used REST requests to pull out intriguing information about products mentioned on your web site. Or maybe you’ve created your own storefront with things you should buy for your significant other. Whatever you’ve done with those REST requests, until you can get your Amazon Associates tag into the mix, visitors clicking your links to buy the advertised products are not making you money.
At this point, you need to create a shopping cart. This shopping cart is not the same as the one on the Amazon site. This cart is local to your site, and you have to keep track of it for your customer. Amazon gives you a number of parameters with which you can interact with a customer’s shopping interface.
Note the following code:
http://ecs.amazonaws.com/onca/xml?Service=AWSECommerceService&
AWSAccessKeyId [YourKeyHere]&
Operation=CartCreate&
Item.1.ASIN=[An ASIN]&
Item.1.Quantity=1&
Item.2.ASIN=[An ASIN]&
Item.2.Quantity=1&
Item.3.ASIN=[An ASIN]&Item.3.Quantity=1
This code is an example from the Amazon shopping cart link above, with which you are creating a local shopping cart. Each ASIN is a specific item in that cart, and it’s obvious what Quantity is. When you send this code as a REST request, you get back a purchase URL. This purchase URL is what your PHP code needs to use to send customers to make their actual purchase on the Amazon site. (Additional cart operations include CartAdd, CartModify, CartGet, and CartClear.)
However, if customers purchase with the purchase URL you just received back, no Amazon Associate URL is associated with it. As a result, you do not make any money if they purchase this item. Let’s discuss how you get your payoff.
Passing Your Amazon Associates Tag into the Query
Suppose your customer wants to purchase that exploding golf ball you’ve been raving about. First, give the customer a button to click that will create a shopping cart. Send in your REST request to create the customer’s cart, as follows:
<?php
$request = ‘http://ecs.amazonaws.com/onca/xml?Service=AWSECommerceService&' .
'AWSAccessKeyId=[YourKeyHere]&Operation=CartCreate&' .
' Item.1.ASIN=[ProductASIN]&Item.1.Quantity=1’;
$response = file_get_contents($request);
echo htmlspecialchars($response, ENT_QUOTES);
?>
You’ll receive a URL that the customer can click to purchase the golf ball. But, you still need to add your Amazon Associates tag.
Before you go any further, modify the purchase URL returned in the XML and add your Amazon Associates tag so that you’ll get credit for the purchase. Use the parameter AssociateTag:
<PurchaseURL>
https://www.amazon.com/gp/cart/aws-merge.html?
cart-id=[YourCartID]&
AssociateTag=[YourAssociateTagHere]&
SubscriptionId=1X052B2V5RA5MKNW3Y02&
MergeCart=False
</PurchaseURL>
Examining a Pre-Built Example, Simple Store
By now, you should have a clear picture of the basics of constructing REST requests. To see them used more flexibly and extensibly, take a look at the code for Simple Store located here:
http://developer.amazonwebservices.com/connect/entry.jspa?externalID=498&categoryID=14
Download and unzip the demo. Change the two tags, [YourAccessKeyIdHere] and [YourAssociateTagHere] to contain your ID and tag.
It’s important to note that this program uses CURL requests and has REST requests commented out in several locations. You should change these throughout before running the code. The comments on lines 70, 128, 180, 197, and 234 point out where this occurs. For example:
//The use of `file_get_contents` may not work on all servers because it relies on the ability to open remote URLs using the file manipulation functions.
//PHP gives you the ability to disable this functionality in your php.ini file and many administrators do so for security reasons.
//If your administrator has not done so, you can comment out the following 5 lines of code and uncomment the 6th.
$session = curl_init($request);
curl_setopt($session, CURLOPT_HEADER, false);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($session);
curl_close($session);
//$response = file_get_contents($request);
Let’s take a closer look at what this code is doing.
Lines 12 and 13 set variables to represent your particular ID and tag. Next, the form is written to the page.
define('KEYID','[YourAccessKeyIdHere]');
define('AssocTag','[YourAssocitaeTagHere]');
The next few lines set up the form on the page. Lines 38 through 60 call specific functions based on the specific action being performed.
<?php
if($_GET['Action'] == 'Search'){
if($_GET['Keywords'] == ''){
print("Please enter keywords for your search.");
}else{
$keywords = urlencode($_GET['Keywords']);
ItemSearch($_GET['SearchIndex'], $keywords, $_GET['ItemPage']);
}
}
if($_GET['Action'] == 'SeeDetails'){
ItemLookup($_GET['ASIN'], $_GET['SearchIndex']);
}
if($_GET['Action'] == 'CartAdd'){
if($_GET['CartId'] != ''){
CartAdd($_GET['ASIN']);
}else{
CartCreate($_GET['ASIN']);
}
}
if($_GET['Action'] == 'Remove'){
removeFromCart($_GET['CartItemId']);
}
?>
The default action is Search. Looking more closely at the ‘Search’ action, lines 39-45, here’s what is taking place. First, the code checks to see if the user has actually entered anything in the search box. If not, the code returns a message to the user. If there are search terms entered, the code calls the function ItemSearch().
The function ItemSearch() should be completely familiar to you, it’s basically the code from earlier in this article with the Asssociate tag and Access Key ID parameterized. Most of the code in this example is very much the same, consisting of formulated strings and REST requests. The functions printSearchResults(), printDetails(), and showCartContents() are each used to parse and display the XML results from the REST requests.
Looking at Real-World Examples
Many successful web businesses use Amazon Associates Web Service and step in as middlemen between Amazon and specialized markets. The following are a few examples:
- Associate-O-Matic--Justin Mecham has built a business by being able to offer non-coders a simple way to leverage their Amazon Associates IDs with ease.
- Action Engine--Wireless companies can offer their customers a way to purchase Amazon products.
- SCANBUY--Offers mobile shopping.
- TicTap.com--A comparison shopping site for mobile devices.
You can see these solutions and a lot more in the AWS Developer Connection Solutions Directory.
Going Forward
This article has provided a beginning guide for trying Amazon Associates Web Service. In this article, we have discussed setting up your developer account, managing your REST requests to get specific data, creating a local shopping cart, and modifying the data to include your own Amazon Associate’s ID to get credit for purchases made from your site.
Here are some further ideas for combining these to increase revenue:
- Use your blog to highlight particular classes of products that you like, and then use
SimilarityLookup to create your own shop.
- Find products sold by merchants with glowing recommendations, and create an online shop devoted to goods sold by only highly rated merchants.
- Create a web site that focuses on a specialized product that you offer for sale.
- Market products with all Amazon Associate profits going to a charity or club with which you are involved.
Additional Resources
Lynn Kyle has worked for Yahoo!, Palm, and Google and written many books and articles on web technologies. She is currently writing Head First SQL for O'Reilly.
|