Amazon Payments PHP Integration

May 16th, 2012


I’ve spent the last week integrating Amazon Checkout with a client’s bespoke PHP shopping cart. Amazon has set itself up as a payment services provider, challenging the mighty Paypal. Checkout by Amazon is a complete checkout and payments service for e-commerce retailers. Offer Checkout by Amazon to enable millions of Amazon customers to use shipping addresses and payment information in their Amazon.com accounts to buy on your e-commerce or mobile website. Customers complete purchases quickly and conveniently, without ever leaving your website.”

Amazon Checkout API

Working with the Amazon API is not for the feint-hearted and the whole process took a massive 30-40 hours to complete. However, that includes work with the back end PHP shopping cart as well as the Amazon API section. Since 2009, Amazon has beefed up security and require you to ‘sign’ each basket request. Signature version 2 is an encrypted method which uses the entire request URI as the basis for the signature calculation. The signature is calculated using your Amazon Secret Key which hopefully only you and Amazon know. After you send a query request with the signature, Amazon calculate their own version and compare it to yours. If they match, your query gets executed. If not, you get a request signature” error. And I got a lot of those…

Inline Checkout

Most developers will chose to go down the Inline route which allows you to integrate the Amazon address book and payment methods into your existing checkout. You can use the combination of Inline Checkout Widgets and API’s to create an Amazon checkout experience within your own site. It is particularly useful if you calculate your own postage.

Amazon PHP Library

The PHP library and pdf’s are quite overwhelming and there are way too many documents to wade through. The only code I needed to communicate with the API was the class below written by Ulrich Mierendorff which does the job perfectly. Calling the class is simple once you have included it and instantiated it like so:

<?

include('class_amazon.php');
$fps = new amazon;

$fps->amazon_api('SetPurchaseItems', 'uk', $params, $public_key, $private_key);
$fps->amazon_api('SetContractCharges', 'uk', $params, $public_key, $private_key);
$fps->amazon_api('CompletePurchaseContract', 'uk', $params, $public_key, $private_key);

?>

Here is the amazon class. I added another parameter ‘$action’ as well as the get_address and get_orderid functions because I needed to store these variables as $_SESSIONS.

<?

class amazon {

function amazon_api($action, $region, $params, $public_key, $private_key) {

/*
Copyright (c) 2009 Ulrich Mierendorff

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/

// some parameters
$method = "GET";
$host = "payments-sandbox.amazon.co.".$region;
$uri = "/cba/api/purchasecontract/";

$params["AWSAccessKeyId"] = $public_key; // additional parameters
$params["Timestamp"] = gmdate("Y-m-d\TH:i:s\Z"); // GMT timestamp
$params["Version"] = "2010-08-31"; // API version
$params["Action"] = $action;
$params["SignatureVersion"] = "2";
$params["SignatureMethod"] = "HmacSHA256";
$params["PurchaseContractId"] = $_COOKIE['apay-pcId'];

ksort($params); // sort the parameters

$canonicalized_query = array(); // create the canonicalized query

foreach ($params as $param=>$value) {
    $param = str_replace("%7E", "~", rawurlencode($param));
    $value = str_replace("%7E", "~", rawurlencode($value));
    $canonicalized_query[] = $param."=".$value;
}

$canonicalized_query = implode("&", $canonicalized_query); // create the string to sign
$string_to_sign = $method. "\n" .$host. "\n". $uri. "\n". $canonicalized_query; // calculate HMAC with SHA256 and base64-encoding
$signature = base64_encode(hash_hmac("sha256", $string_to_sign, $private_key, True));

// encode the signature for the request
$signature = str_replace("%7E", "~", rawurlencode($signature));
$request = "https://" . $host.$uri. "?". $canonicalized_query. "&Signature=". $signature; // create request

// do request
$response = @file_get_contents($request);

if ($response === False) {
	return False;
	} else {

	$pxml = simplexml_load_string($response);

	switch($action) {

		case('CompletePurchaseContract'):
		$this->get_orderid($response);
		break;

		case('SetContractCharges'):
		$this->get_address($response);
		break;

	} // Close switch   

	} // Close else

} // Close function

function get_address($response) {

    $start = 0;
	$end = 0;		

    $search = array(
    "PostalCode", "PhoneNumber", "Name", "CountryCode", "City"
    );

	foreach($search as $i => $row) {
    	$start =  strpos($response, '<' . $row . '>');
    	$end = strpos($response, '');    		
		$_SESSION['address'][$i] = substr($response, $start, ($end - $start));
		}

} // Close function


function get_orderid($response) {

    $start = 0;
	$end = 0;		
    
    $start =  strpos($response, '');
    $end = strpos($response, '');    		
	$_SESSION['orderid'] = substr($response, $start, ($end - $start));

} // Close function

} // Close class

?>