Make an authenticated request to Amazon’s Product ItemLookup API with wp_remote_get()

If you like my WordPress work, check out my new plugin, Bylines. Thanks!

Amazon has a helpful ItemLookup API for fetching details about a given product. Authenticating your request is a bit tricky though. It requires signing your request with a signature. Here’s an overview to how it works in WordPress.


$query_args = array(
	'AssociateTag'   => AMAZON_ASSOCIATE_TAG,
	'AWSAccessKeyId' => AMAZON_PRODUCT_API_ACCESS_KEY,
	'ItemId'         => $item_id, // Something like B0027Z8VES
	'Operation'      => 'ItemLookup',
	'ResponseGroup'  => 'Large',
	'Service'        => 'AWSECommerceService',
	'Timestamp'      => rawurlencode( date( 'Y-m-d\TH:i:s\Z' ) ),
);

// Signature body must be produced from args sorted by natural byte length.
uksort( $query_args, 'strnatcmp' );

// The first part of the signature body is the request method, domain, and URL.
$signature_body = 'GET' . PHP_EOL . 'webservices.amazon.com' . PHP_EOL . '/onca/xml' . PHP_EOL;;
foreach( $query_args as $key => $value ) {
	$signature_body .= $key . '=' . $value . '&';
}
$signature_body = rtrim( $signature_body, '&' );

// After the signature is generated, it needs to be doubly-encoded to make sure it is URL-safe.
$query_args['Signature'] = rawurlencode( base64_encode( hash_hmac( 'sha256', $signature_body, AMAZON_PRODUCT_API_ACCESS_SECRET, true ) ) );

// Make the request and do whatever you want with the response.
$response = wp_remote_get( add_query_arg( $query_args, 'http://webservices.amazon.com/onca/xml' ) );