Signing Amazon Requests with PHP

By Jeff Denton Sep 3, 2009

On August 15, 2009 Amazon changed the way it accepts API requests. API requests must now be signed using a painful and error prone 10-step process outlined at the Amazon Developer Guide website. There are a few examples for PHP floating around the web right now but I had to try them all and do a little tweaking myself to get this to work.  The code below is based on this blog post over at Every Good Path.

I'm not going to explain this line by line but I will say that the following request is designed to search for books by ISBN number and return the book image, author, Amazon link, etc.  Have fun!

 

$request =  'Service=AWSECommerceService&'.
				'AWSAccessKeyId='.AMAZON_ACCESS_KEY_ID.'&'.
				'Operation=ItemSearch&'.					
				'Keywords='.$itemISBN.'&'.
				'SearchIndex=Books&'.
				'ResponseGroup=Images,ItemAttributes,Small&'.
				'Version=2009-01-06&'.
				'Timestamp='.gmdate("Y-m-d\TH:i:s\Z");
	
	// 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;

	$signature = urlencode(base64_encode(hash_hmac("sha256", $string_to_sign, AMAZON_SECRET_ACCESS_KEY, True)));

	$request .= '&Signature='.$signature;
	$request = 'http://webservices.amazon.com/onca/xml?'.$request;
	
	$response  = file_get_contents($request);
	$amazonXML = simplexml_load_string($response);	

 

0
In coding