LoginSignup
28
21

More than 5 years have passed since last update.

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

Posted at

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();
    }
}



28
21
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
28
21