PHP Example for Amazon Signed Request

      Comments Off on PHP Example for Amazon Signed Request

Simple Example of PHP software changes to comply with Authenticated / Signed Request / Query to Amazon’s AWS / Product Advertising API for affiliate websites – which may affect some homeschool websites.

Amazon documents hint at how to do this, but there’s no sample code for PHP programming –
Here’s how I got it to work…
// example starts with a typical AWS operation – no keys or timestamp yet
$request = ‘Operation=ItemLookup&ResponseGroup=Tags&TagsPerPage=20&Marketplace=us&Version=2008-04-07&ItemId=1604591935’;

if ($THE_OLD_UNSIGNED_WAY) {
// Here’s the simple unsigned method that works until August 15 2009
$request = ‘http://webservices.amazon.com/onca/xml?Service=AWSECommerceService&AWSAccessKeyId=YOUR_ACCESS_ID&’.$request;
$response = file_get_contents($request);
if ($response) $simple_response = simplexml_load_string($response);
} else {
// START CHANGES FOR SIGNED REQUEST
// see http://docs.amazonwebservices.com/AWSECommerceService/latest/DG/index.ht… for more details

//Substitute your real Access Id here…
$request = ‘Service=AWSECommerceService&’.
‘AWSAccessKeyId=YOUR_ACCESS_ID&’.
‘Timestamp=’.gmdate(“Y-m-d\TH:i:s\Z”).’&’.
$request;

// encode url – replace commas w/ %2C, replace colon w/ %3A
// Could use urlencode($request) here, but $request may already be partially encoded
$request = str_replace(‘,’,’%2C’, $request);
$request = str_replace(‘:’,’%3A’, $request);

//break request string into key/value pairs,
$reqarr = explode(‘&’,$request);

//sort on byte value
sort($reqarr);

// tie back together w/ &’s
$string_to_sign = implode(“&”, $reqarr);

$string_to_sign = “GET\nwebservices.amazon.com\n/onca/xml\n”.$string_to_sign;

//Substitute your real Secret Key here…
$signature = urlencode(base64_encode(hash_hmac(“sha256”, $string_to_sign, ‘YOUR_SECRET_KEY’, True)));

$request .= ‘&Signature=’.$signature;

$request = ‘http://webservices.amazon.com/onca/xml?’.$request;

echo ‘NEW REQ ‘.$request;

// For this example, the above echo should yield:
// NEW REQ http://webservices.amazon.com/onca/xml?Service=AWSECommerceService&AWSAc…
// – obviously this is a bogus request as we used placeholders for AccessId and SecretKey

$response = file_get_contents($request);

if ($response) $simple_response = simplexml_load_string($response);

// if your signed request is invalid – AWS will give error response such as:
// The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.

// more help at: http://mierendo.com/software/aws_signed_query/
}