Search code examples
phpamazon-web-services

amazon api request return SignatureDoesNotMatch


SignatureDoesNotMatch" ["Message"]=> string(178) "The request signature we calculated does not match the signature you provided

here is code

$keywords=$this->input->post('searchbook');
            if($keywords){ 
$associate_tag = " xxxxx";
$aws_secret_access_key = "xxxxx";
$aws_access_key_id = "xxxxx";
$item_page=10;

$base_url = 'http://ecs.amazonaws.com/onca/xml?Service=AWSECommerceService&AWSAccessKeyId='. $aws_access_key_id .'&';
  $url_params = array(
        'Operation'=>'ItemSearch',
        'ItemPage'=>$item_page,
        'AssociateTag'=>$associate_tag,
        'Version'=>'2013-08-01',
        'ResponseGroup'=>'Images,ItemAttributes,EditorialReview',
         'SearchIndex'=>'Books',
         'Keywords'=>rawurlencode($keywords)
     );
    $url_parts = array();
    foreach(array_keys($url_params) as $key)
        $url_parts[] = $key."=".$url_params[$key];
    sort($url_parts);
   $url = $base_url . implode('&',$url_parts);
    $host = parse_url($base_url . implode('&',$url_parts),PHP_URL_HOST);
    $timestamp = gmstrftime('%Y-%m-%dT%H:%M:%S.000Z');
    $url = $url. '&Timestamp=' . $timestamp;
    $paramstart = strpos($url,'?');
    $workurl = substr($url,$paramstart+1);
    $workurl = str_replace(",",",",$workurl);
    $workurl = str_replace(":",":",$workurl);
    $params = explode("&",$workurl);
    sort($params);
    $signstr = "GET\n" . $host . "\n/onca/xml\n" . implode("&",$params);
    $signstr = base64_encode(hash_hmac('sha256', $signstr,$aws_secret_access_key, true));
    $signstr = urlencode($signstr);
    $signedurl = $url . "&Signature=" . $signstr;
    $request = $signedurl;
      $request;

    //Send request to AWS
    $session = curl_init($request);
    curl_setopt($session, CURLOPT_HEADER, false);
    curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($session);
    curl_close($session); 
    $parsed_xml = simplexml_load_string($response);
    var_dump($parsed_xml);exit;
   }

how to solved it and where is problem i want to get books details from amazon when i send request then return SignatureDoesNotMatch


Solution

  • When you don't use any AWS SDK to send http request, you must handle sign request yourself. Only access key & security key is not enough. Please reference this document.