11/08/09: Amazon API Changes, Bookdata, PHP (Sorry)
Warning: deeply dull post ahead. But, we’ve had a lot of discussion about bookdata, APIs, and Amazon on this blog, so it would be remiss of me not to post this.
From August 15th, Amazon requires all API requests to be signed, which to the layman means that you need to add a timestamp, and a ’signature’, which is a hash of the entire request, and your private Amazon key.
There are a bunch of PHP examples for doing this on the web, but because I had to tweak them all slightly to get them to work, I thought I’d put it out there to be helpful – I’ve just implemented this on bkkeepr and Bookseer and a few other places…
<?php
// Build your request string, e.g.
$request = 'Service=AWSECommerceService&'.'AWSAccessKeyId=[YOUR AWS ACCESS KEY]&'.'Timestamp='.gmdate("Y-m-d\TH:i:s\Z").'&Operation=ItemSearch&Title='.$title.'&SearchIndex=Books';
// Encode and sort the request string
$request = str_replace(',','%2C', $request);
$request = str_replace(':','%3A', $request);
$reqarr = explode('&',$request);
sort($reqarr);
$string_to_sign = implode("&", $reqarr);
// Append endpoint
$string_to_sign = "GET\necs.amazonaws.co.uk\n/onca/xml\n".$string_to_sign;
// Create signature hash
$signature = urlencode(base64_encode(hash_hmac("sha256", $string_to_sign, '[YOUR AWS PRIVATE KEY]', True)));
// Append signature to original request
$request .= '&Signature='.$signature;
// Append endpoint to original request
$request = 'http://ecs.amazonaws.co.uk/onca/xml?'.$request;
// Make request
Append signature to original request
$curl_handle = curl_init();
curl_setopt($curl_handle, CURLOPT_URL, $request);
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
$book_data = curl_exec($curl_handle);
curl_close($curl_handle);
return $book_data;
?>
It’s actually pretty simple when you get your head round it, although Amazon has done an atrocious job of helping people make the change. You need to be quite the developer – or, in my case, read piles of unhelpful documentation and a hell of a lot of helpful blogs – to get your head round it, but I hope that helps someone.
Remember, you can make your own changes to the $request string in the example above – don’t forget the Timestamp, it’s important – and change the endpoint from .co.uk to .com, .fr etc. There’s also a slightly helpful Amazon helper here.
If anyone has questions, I’ll try to help – but not promising anything…





.
Designed and built by 