Money-Code

Coding For Online Success

Amazon Product API: SignatureDoesNotMatch error response

| 7 Comments

On August 15, 2009, all Product Advertising API developers were required to authenticate ALL calls using a hmac/sha256 signing token. For some reason, this was a major pain in the ass for me, but I finally got things to work.

If you’re having trouble, and you’re using PHP5, this may help you.

The first item you’ll need is the ‘secret’. You need to log into the Amazon Web Services area (https://developer.amazonwebservices.com). After logging in (assuming you already have a account if you’re using their API), you need to hover over ‘Your Account’, and click ‘Access Identifiers’. Here you will see ‘Access Key ID’ and ‘Secret Access Key’. We’ll be referring Access Key ID as the public key and Secret Access Key as the private key in a function provided below. Copy these two values and add them to your code somewhere.

You will need to ensure that PHP is built with hash support. You can verify this with by view info (<?phpinfo()?>). If hash support is there we can use the built in hash_hmac() function. The concept is pretty straight forward (eventhough, I’ve been fighting it all night prior to this post). You create a string, and ‘hash’ it with our private key, then we pass the string to Amazon’s API, and they hash the same string with our private key. The value should be the same, and if so, we’re good. If something is off any where in that sequence you’ll be getting the dreaded ‘SignatureDoesNotMatch‘ message in your XML return.

I came across Ulrich Mierendorff’s function for sending a signed AWS request on the developer forum, and it was the only PHP code snippet that worked for me, so I need to pass it on. Below is the function:

function aws_signed_request($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.
    */

    /*
    Parameters:
        $region – the Amazon(r) region (ca,com,co.uk,de,fr,jp)
        $params – an array of parameters, eg. array("Operation"=>"ItemLookup",
                        "ItemId"=>"B000X9FLKM", "ResponseGroup"=>"Small")
        $public_key – your "Access Key ID"
        $private_key – your "Secret Access Key"
    */

    // some paramters
    $method = "GET";
    $host = "ecs.amazonaws.".$region;
    $uri = "/onca/xml";

    // additional parameters
    $params["Service"] = "AWSECommerceService";
    $params["AWSAccessKeyId"] = $public_key;
    // GMT timestamp
    $params["Timestamp"] = gmdate("Y-m-d\TH:i:s\Z");
    // API version
    $params["Version"] = "2009-03-31";

    // sort the parameters
    ksort($params);

    // create the canonicalized query
    $canonicalized_query = array();
    foreach ($params as $param=>$value)
    {
        $param = str_replace("%7E", "~", rawurlencode($param));
        $value = str_replace("%7E", "~", rawurlencode($value));
        $canonicalized_query[] = $param."=".$value;
    }
    $canonicalized_query = implode("&amp;", $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));

    // create request
    $request = "http://".$host.$uri."?".$canonicalized_query."&amp;Signature=".$signature;

    // do request
        $ch                             = curl_init();
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_URL, $request);
        $response                       = curl_exec($ch);
        curl_close($ch);

    if ($response === False)
    {
        return False;
    }
    else
    {
        // parse XML
        $pxml = simplexml_load_string($response);
        if ($pxml === False)
        {
            return False; // no xml
        }
        else
        {
            return $pxml;
        }
    }
}

To call the function you create a array of arguments and pass it to the function along with the keys values.

$amazontag      = ‘asdfasfd-20′;
$public_key = "asfdasdfasdfasfdasfda";
$private_key = "SECRETKEYasfdasdfasdfasfdasfda";
$param          = array("Operation"=>"ItemSearch",
                                "IdType"=>"ASIN",
                                "MerchantId"=>"All",
                                "ResponseGroup"=>"Large",
                                "SearchIndex"=>$searchindex,
                                "BrowseNode"=>$BrowseNode,
                                "Keywords"=>$safeQuery,
                                "AWSAccessKeyId"=>$amazontag);
$xml            = aws_signed_request("com",$param, $public_key, $private_key);

This worked perfectly for me, and got my Amazon sites back on line. Hope this helps!!

Incoming search terms:

  • SignatureDoesNotMatch
  • amazon SignatureDoesNotMatch
  • aws SignatureDoesNotMatch
  • signaturedoesnotmatch amazon
  • <Code>SignatureDoesNotMatch</Code>
  • AWS Error Code: SignatureDoesNotMatch
  • amazon product api signaturedoesnotmatch
  • amazon product api cartcreate script php
  • cartGet script amazon product api
  • amazon

7 Comments

  1. Well THAT’S a big flapping earlobe to me. I wonder if my scripts are still working? ARGH!!!!!!!!

    (check check check)

    ARGH! (bashes head on wall) glad I stopped by this blog – will get that fixed today. Thanks!

  2. Yep.. I bet things are borken for sure! Good luck on your fixes! Thanks for commenting.
    hanji

  3. hi,
    i want to get api code for amazone adsense, to display. how can i get that sample code. please help me..

    many thanks in advance..

  4. Hello james

    Not sure if I’m understanding you. Amazon adsense? AdSense is a Google service? Are you talking about regular Amazon listings?

    hanji

  5. I’m having some trouble leaving my question – this is a test post to see if I can comment.

  6. I am Barbara Ling’s poor Amazon-ignorant hubby.

    Before August 2009 the effect of HMAC-SHA256 token signature API, our following URL request had always worked fine to bring back 2 pages of results that give a list of items that match Keywords ‘ma rolloer’ together with each item’s ID, icon, description, and reviews.

    The request is made in PHP with the file_get_contents() function call.

    file_get_contents(
    ‘http://webservices.amazon.com/onca/xml?Service=AWSECommerceService&SubscriptionId=__OurID___&Operation=ItemSearch&ItemSearch.Shared.SearchIndex=Blended&ItemSearch.Shared.Keywords=ma%20roller&ItemSearch.Shared.ResponseGroup=ItemIds,Images,ItemAttributes,Reviews,EditorialReview&ItemSearch.1.ItemPage=1&ItemSearch.2.ItemPage=2‘
    );

    I broke up the single long line of query into shorter lines to show more clearly all the individual query parameters.

    http://webservices.amazon.com/onca/xml\
    ?Service=AWSECommerceService&SubscriptionId=__OurID___\
    &Operation=ItemSearch\
    &ItemSearch.Shared.SearchIndex=Blended\
    &ItemSearch.Shared.Keywords=ma%20roller\
    &ItemSearch.Shared.ResponseGroup=ItemIds,Images,ItemAttributes,Reviews,EditorialReview\
    &ItemSearch.1.ItemPage=1\
    &ItemSearch.2.ItemPage=2

    This query request URL no longer works after August 2009.

    I recently began to add Ulrich Mierendorff’s (THANKS to him and others who pointed me there) PHP function aws_signed_request() code for meeting HMAC-SHA256 token signature requirement.

    I followed the instructions given at
    http://www.money-code.com/2009/08/amazon-product-api-signaturedoesnotmatch-error-response/comment-page-1/#comment-792
    to call aws_signed_request() to build and send the same query.

    I tried a number of variations and always get back the following response:

    WS.InvalidOperationParameter The Operation parameter is invalid. Please modify the Operation parameter and retry. Valid values for the Operation parameter include TagLookup, ListLookup, CartGet, SellerListingLookup, CustomerContentLookup, ItemLookup, SimilarityLookup, SellerLookup, ItemSearch, VehiclePartLookup, BrowseNodeLookup, CartModify, ListSearch, CartClear, VehiclePartSearch, CustomerContentSearch, CartCreate, TransactionLookup, VehicleSearch, SellerListingSearch, CartAdd, Help.

    Even using the Operation=Help parameter-value pair returns the same response message.

    Please help. THANKS in advance.

  7. Hello Mo

    Can you show me your simple_aws_signed_request() call? Sounds like you might have a syntax error there.

    Thanks!
    hanji

Leave a Reply

Required fields are marked *.


CommentLuv badge