Amazon® AWS HMAC signed request using PHP

The Amazon® Product Advertising API can be used to access Amazon's data for advertising purpose. By August 15, 2009, all calls to the API must be signed to authenticate the request. I have written a simple function in PHP that lets you make authenticated requests with only a few lines of code.

Source Code

  1. <?php
  2.  
  3. function aws_signed_request($region, $params, $public_key, $private_key)
  4. {
  5.     /*
  6.     Copyright (c) 2009 Ulrich Mierendorff
  7.  
  8.     Permission is hereby granted, free of charge, to any person obtaining a
  9.     copy of this software and associated documentation files (the "Software"),
  10.     to deal in the Software without restriction, including without limitation
  11.     the rights to use, copy, modify, merge, publish, distribute, sublicense,
  12.     and/or sell copies of the Software, and to permit persons to whom the
  13.     Software is furnished to do so, subject to the following conditions:
  14.  
  15.     The above copyright notice and this permission notice shall be included in
  16.     all copies or substantial portions of the Software.
  17.  
  18.     THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19.     IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  20.     FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  21.     THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  22.     LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  23.     FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  24.     DEALINGS IN THE SOFTWARE.
  25.     */
  26.  
  27.     /*
  28.     Parameters:
  29.         $region - the Amazon(r) region (ca,com,co.uk,de,fr,jp)
  30.         $params - an array of parameters, eg. array("Operation"=>"ItemLookup",
  31.                         "ItemId"=>"B000X9FLKM", "ResponseGroup"=>"Small")
  32.         $public_key - your "Access Key ID"
  33.         $private_key - your "Secret Access Key"
  34.     */
  35.  
  36.     // some paramters
  37.     $method = "GET";
  38.     $host = "ecs.amazonaws.".$region;
  39.     $uri = "/onca/xml";
  40.  
  41.     // additional parameters
  42.     $params["Service"] = "AWSECommerceService";
  43.     $params["AWSAccessKeyId"] = $public_key;
  44.     // GMT timestamp
  45.     $params["Timestamp"] = gmdate("Y-m-d\TH:i:s\Z");
  46.     // API version
  47.     $params["Version"] = "2009-03-31";
  48.  
  49.     // sort the parameters
  50.     ksort($params);
  51.  
  52.     // create the canonicalized query
  53.     $canonicalized_query = array();
  54.     foreach ($params as $param=>$value)
  55.     {
  56.         $param = str_replace("%7E", "~", rawurlencode($param));
  57.         $value = str_replace("%7E", "~", rawurlencode($value));
  58.         $canonicalized_query[] = $param."=".$value;
  59.     }
  60.     $canonicalized_query = implode("&", $canonicalized_query);
  61.  
  62.     // create the string to sign
  63.     $string_to_sign = $method."\n".$host."\n".$uri."\n".$canonicalized_query;
  64.  
  65.     // calculate HMAC with SHA256 and base64-encoding
  66.     $signature = base64_encode(hash_hmac("sha256", $string_to_sign, $private_key, True));
  67.  
  68.     // encode the signature for the request
  69.     $signature = str_replace("%7E", "~", rawurlencode($signature));
  70.  
  71.     // create request
  72.     $request = "http://".$host.$uri."?".$canonicalized_query."&Signature=".$signature;
  73.  
  74.     // do request
  75.     $response = @file_get_contents($request);
  76.  
  77.     if ($response === False)
  78.     {
  79.         return False;
  80.     }
  81.     else
  82.     {
  83.         // parse XML
  84.         $pxml = simplexml_load_string($response);
  85.         if ($pxml === False)
  86.         {
  87.             return False; // no xml
  88.         }
  89.         else
  90.         {
  91.             return $pxml;
  92.         }
  93.     }
  94. }
  95. ?>

Download

icon
The PHP Function (1.6kB)It uses hash_hmac and requires PHP 5 >= 5.1.2

Documentation

After downloading and extracting aws_signed_request.zip you can include aws_signed_request.php in your PHP scripts. The function contained in this file takes four parameters. $region is the Amazon region (for example "com" or "fr"). $params is an array of parameters with the parameter names as keys. $public_key and $private_key are your keys you have got from Amazon.

Here is an example (you have to replace $public_key and $private_key with your own identifiers)

  1. include("aws_signed_request.php");
  2.  
  3. $public_key = "xxxxxx";
  4. $private_key = "xxxxxx";
  5. $pxml = aws_signed_request("com", array("Operation"=>"ItemLookup","ItemId"=>"B000X9FLKM","ResponseGroup"=>"Small"), $public_key, $private_key);
  6. if ($pxml === False)
  7. {
  8.     echo "Did not work.\n";
  9. }
  10. else
  11. {
  12.     if (isset($pxml->Items->Item->ItemAttributes->Title))
  13.     {
  14.         echo $pxml->Items->Item->ItemAttributes->Title, "\n";
  15.     }
  16.     else
  17.     {
  18.         echo "Could not find item.\n";
  19.     }
  20. }

The result would be something like this

  1. The Lord of the Rings: The Motion Picture Trilogy (Theatrical Editions) [Blu-ray]

That's it. Feel free to comment if you think something could be improved.