Help us understand the problem. What is going on with this article?

PHPでAmazon API を使い商品画像を取得

More than 5 years have passed since last update.

Amazon Product Advertising API
を使ってASINから商品画像を取得した時の雑なメモ

手順

  1. パラメータ設定 REST リクエストの構造
  2. 署名認証  RESTリクエストの認証方法
  3. URL組み立ててリクエスト
  4. Xmlパース
<?php
//ASIN
$asin = 'B013PUTPHK';

//アクセスキー
$access_key_id = '';
//シークレットキー
$secret_access_key = '';
//アソシエイトタグ
$associateTag = '';

//APIエンドポイントURL
$endpoint = 'http://ecs.amazonaws.jp/onca/xml';

// パラメータ
$params = array(
    //共通↓
    'Service' => 'AWSECommerceService',
    'AWSAccessKeyId' => $access_key_id,
    'AssociateTag' => $associateTag,
    //リクエストにより変更↓
    'Operation' => 'ItemLookup',
    'ItemId' => $asin,
    'ResponseGroup' => 'ItemAttributes,Images',
    //署名用タイムスタンプ
    'Timestamp' => gmdate('Y-m-d\TH:i:s\Z'),
);

//パラメータと値のペアをバイト順?で並べかえ。
ksort($params);

//RFC 3986?でURLエンコード
$string_request = str_replace(
    array('+', '%7E'),
    array('%20', '~'),
    http_build_query($params)
);

//URL分解
$parse_url = parse_url($endpoint);

//署名対象のリクエスト文字列を作成。
$string_signature = "GET\n{$parse_url["host"]}\n{$parse_url["path"]}\n$string_request";

//RFC2104準拠のHMAC-SHA256ハッシュ化しbase64エンコード(これがsignatureとなる)
$signature = base64_encode(hash_hmac('sha256', $string_signature, $secret_access_key,true));

//URL組み立て
$url = $endpoint . '?' . $string_request . '&Signature=' . $signature;


// xml取得
$xml = simplexml_load_string(getHttpContent($url));

$item = $xml->Items->Item;
echo "画像URL:".$item->LargeImage->URL."\n";


function getHttpContent($url)
{
    try {
        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
        ]);
        $body = curl_exec($ch);
        $errno = curl_errno($ch);
        $error = curl_error($ch);
        curl_close($ch);
        if (CURLE_OK !== $errno) {
            throw new RuntimeException($error, $errno);

        }
        return $body;
    } catch (Exception $e) {
        echo $e->getMessage();
    }
}



Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away