Amazon Associates

Scriam inainte de a intra in concediu ca Amazon va introduce incepand cu 15 august autentificarea pentru folosirea API-ului lor. Drept urmare m-am trezit pe siteul meu de versuri cu o problema …

The request must contain the parameter Signature.

Am cautat si in forumul lor, am si googalit … si-am dat de solutia lui Brandon Checketts (THANK YOU, Brandon! ;) ).

function signAmazonUrl($url)
{
    global $CONFIG;
    $original_url = $url;

    // Decode anything already encoded
    $url = urldecode($url);

    // Parse the URL into $urlparts
    $urlparts       = parse_url($url);

    // Build $params with each name/value pair
    foreach (split('&', $urlparts['query']) as $part) {
        if (strpos($part, '=')) {
            list($name, $value) = split('=', $part, 2);
        } else {
            $name = $part;
            $value = '';
        }
        $params[$name] = $value;
    }

    // Include a timestamp if none was provided
    if (empty($params['Timestamp'])) {
        $params['Timestamp'] = gmdate('Y-m-d\TH:i:s\Z');
    }

    // Sort the array by key
    ksort($params);

    // Build the canonical query string
    $canonical = '';
    foreach ($params as $key => $val) {
        $canonical  .= "$key=".rawurlencode($val)."&";
    }
    // Remove the trailing ampersand
    $canonical = preg_replace("/&$/", '', $canonical);

    // Some common replacements and ones that Amazon specifically mentions
    $canonical = str_replace(array(' ', '+', ',', ';'), array('%20', '%20', urlencode(','), urlencode(':')), $canonical);

    // Build the si
    $string_to_sign = "GET\n{$urlparts['host']}\n{$urlparts['path']}\n$canonical";

    // Calculate our actual signature and base64 encode it
    $signature = base64_encode(hash_hmac('sha256', $string_to_sign, $CONFIG['AMAZON_SECRET_KEY'], true));

    // Finally re-build the URL with the proper string and include the Signature
    $url = "{$urlparts['scheme']}://{$urlparts['host']}{$urlparts['path']}?$canonical&Signature=".rawurlencode($signature);
    return $url;
}

Tot ce trebuie facut acum este sa setati o variabila globala $CONFIG[‘AMAZON_SECRET_KEY’] si apoi sa chemati functia signAmazonUrl() in orice loc aveati un URL de la Amazon API; ca in exemplul meu:

$rss_parser_nuebun = "https://ecs.amazonaws.com/onca/xml?Service=AWSECommerceService&AWSAccessKeyId=<AWSAccessKeyId>&Version=2008-04-07&AssociateTag=<tagul-tau>&Operation=ItemSearch&SearchIndex=Music&Title=<cuvinte-pentru-cautare>&ResponseGroup=Images,ItemAttributes,OfferSummary";

$rss_parser = signAmazonUrl($rss_parser_nuebun);

PS: Nu stii ce e Amazon? Vezi aici.