サンプル・プログラムの実行例

サンプル・プログラム
解説:準備
20: //Amazon Web Service
21: //http://www.pahoo.org/e-soul/webtech/php06/php06-54-01.shtm 参照
22: const ASSOCIATETAG = '**********'; //アソシエイトID
23: const AWSACCESSKEYID = '**********************'; //アクセスキーID
24: const AWSSECRETKEY = '**********************'; //シークレットキー
25: const AWSURL = 'http://ecs.amazonaws.jp/onca/xml';
26: const AWSVERSION = '2013-08-01'; //APIバージョン

Amazonアソシエイト(アフィリエイト)のアカウントを持っていない方は、まず、「Amazonアソシエイト(アフィリエイト)にようこそ!」から、アカウントを作成する。


Amazonアソシエイト管理画面の上部メニュー「Product Advertising API」をクリックする。

あとは画面の指示にしたがって、必要な情報を記入し、アカウントを作成する。


「アクセスキー情報」にある「こちらのリンク」をクリックする。


ここまでの手順の詳細は、「AWS アクセスキー発行手順」(RTpro)が詳しい。
WebAPI:Amazon Web Service
リクエストURL |
---|
https://ecs.amazonaws.jp/onca/xml |
項目名 | フィールド名 | 型 | 内 容 |
---|---|---|---|
サービス名 | Service | string | 【必須】AWSECommerceService |
アソシエイトID | AssociateTag | string | 【必須】上記で入手したもの。 |
アクセスキーID | AWSAccessKeyId | string | 【必須】上記で入手したもの。 |
APIバージョン | Version | string | 【必須】2013-08-01 |
タイムスタンプ | Timestamp | string | 【必須】世界標準時をRFC3339形式で表現したもの。 例:2016-01-23T00:15:35.000Z |
シグネチャ | Signature | string | 【必須】※後述 |
オペレーション | Operation | string | 【必須】ItemSearch:商品検索 |
絞り込み条件 | SearchIndex | string | 【必須】All(全て)、Books(本)、DVD、Music(ミュージック)、Toy(おもちゃ)、等々 |
レスポンスグループ | ResponseGroup | string | 【必須】ItemAttributes(商品属性、Images(商品画像)、等々 複数指定するときはカンマ ',' で区切る。 例:ItemAttributes,Images |
検索条件 | Keywords, Title, Author, 等々 | string | 【必須】検索条件 |
一番厄介なのはシグネチャであるが、次の手順で求める。

まず、キーのアルファベット順にパラメータを並べる。
AssociateTag=hagehage
AWSAccessKeyId=hogehoge
Operation=ItemSearch
ResponseGroup=ItemAttributes%2CImages
SearchIndex=Books
Service=AWSECommerceService
Timestamp=2016-01-23T00%3A15%3A33.00Z
Title=PHP
Version=2013-08-01

すべてのパラメータを & で接続する。
AssociateTag=hagehage&AWSAccessKeyId=hogehoge
&Operation=ItemSearch&ResponseGroup=
ItemAttributes%2CImages&SearchIndex=Books
&Service=AWSECommerceService&Timestamp=
2016-01-23T00%3A15%3A33.00Z
&Title=PHP&Version=2013-08-01

冒頭に GET, ecs.amazonaws.jp, /onca/xml の3行を加える。
GET
ecs.amazonaws.jp
/onca/xml
AssociateTag=hagehage&AWSAccessKeyId=hogehoge
&Operation=ItemSearch&ResponseGroup=
ItemAttributes%2CImages&SearchIndex=Books
&Service=AWSECommerceService&Timestamp=
2016-01-23T00%3A15%3A33.00Z&Title=PHP
&Version=2013-08-01

このテキストをHMAC-SHA256によりハッシュ化する。
具体的には、関数 hash_hmac の第一引数を "sha256" に、第2引数に上述のテキストを、第3引数に冒頭で入手した シークレットキー を、第4引数に TRUE を指定する。
得られたシグネチャは、 base64_encode と urlencode を通してテキスト化し、リクエストURLの最後に付け加える。

シグネチャを含む呼び出しURLは、Amazon公式サイトにある「Signed Requests Helper」で手作業で作成することができる。プログラムのデバッグ時に役立つだろう。
解説:AWSの呼び出し
76: /**
77: * Amazon Web Service のURLを取得する
78: * @param array $reqs リクエスト・パラメータ(キー:変数名)
79: * @return string URL URL
80: */
81: function getURL_AWS($reqs) {
82: foreach ($reqs as $key=>$val) {
83: $reqs[$key] = urlencode($val);
84: }
85: $reqs['Service'] = 'AWSECommerceService';
86: $reqs['AWSAccessKeyId'] = self::AWSACCESSKEYID;
87: $reqs['AssociateTag'] = self::ASSOCIATETAG;
88: $reqs['Version'] = self::AWSVERSION;
89: $reqs['Timestamp'] = urlencode(gmdate('Y-m-d') . 'T' . gmdate('H:i:s') . '.000Z');
90:
91: //Signature生成
92: ksort($reqs); //キー順ソート
93: $str_req = '';
94: $cnt = 0;
95: foreach ($reqs as $key=>$val) {
96: if ($cnt > 0) $str_req .= '&';
97: $str_req .= $key . '=' . $val;
98: $cnt++;
99: }
100: $arr = parse_url(self::AWSURL);
101: $message = array('GET', $arr['host'], $arr['path'], $str_req);
102: $message = join("\n", $message);
103:
104: $hash = hash_hmac('sha256', $message, self::AWSSECRETKEY, TRUE);
105: $reqs['Signature'] = urlencode(base64_encode($hash));
106:
107: //リクエストURL生成
108: $url = self::AWSURL;
109: $cnt = 0;
110: foreach ($reqs as $key=>$val) {
111: if ($cnt == 0) $url .= '?' . $key . '=' . $val;
112: else $url .= '&' . $key . '=' . $val;
113: $cnt++;
114: }
115:
116: return $url;
117: }
解説:書籍検索
119: /**
120: * Amazonで書籍検索
121: * @param string $query 書名
122: * @param array $items 情報を格納する配列
123: * @return int ヒットした商品数
124: */
125: function searchBooks($query, &$items) {
126: $reqs = array();
127: $reqs['Operation'] = 'ItemSearch';
128: $reqs['SearchIndex'] = 'Books';
129: $reqs['ResponseGroup'] = 'ItemAttributes,Images';
130: $reqs['Title'] = $query;
131: $reqs['Sort'] = 'daterank';
132: $reqs['ItemPage'] = 1;
133:
134: $url = $this->getURL_AWS($reqs); //リクエストURL
135: $this->webapi = $url;
136:
137: $res = @simplexml_load_file($url);
138: //レスポンス・チェック
139: if (! isset($res->Items->Request->IsValid) ||
140: (preg_match('/True/i', $res->Items->Request->IsValid) == 0)) {
141: $this->error = TRUE;
142: $this->errmsg = 'AmazonWebServiceのトラブル';
143: $this->hits = 0;
144: return FALSE;
145: }
146: //合計ページ数
147: $total_pages = (int)$res->Items->TotalPages;
148: if ($total_pages > 10) $total_pages = 10; //制限
149: //データ読み込み
150: $cnt = 1;
151: $page = 1;
152: do {
153: foreach ($res->Items->Item as $item) {
154: //電子書籍は除外
155: if (preg_match('/eBooks/iu', (string)$item->ItemAttributes->ProductGroup) > 0) continue;
156: //成人向けコンテンツは除外
157: if ((int)$item->ItemAttributes->IsAdultProduct > 0) continue;
158: $items[$cnt]['ISBN'] = (string)$item->ItemAttributes->EAN;
159: $items[$cnt]['ASIN'] = (string)$item->ASIN;
160: $items[$cnt]['Title'] = (string)$item->ItemAttributes->Title;
161: $items[$cnt]['Author'] = (string)$item->ItemAttributes->Author;
162: $items[$cnt]['Publisher'] = (string)$item->ItemAttributes->Publisher;
163: $items[$cnt]['ReleaseDate'] = (string)$item->ItemAttributes->ReleaseDate;
164: $items[$cnt]['PublicationDate'] = (string)$item->ItemAttributes->PublicationDate;
165: $items[$cnt]['Price'] = (int)$item->ItemAttributes->ListPrice->Amount;
166: $items[$cnt]['ProductGroup'] = (string)$item->ItemAttributes->ProductGroup;
167: $items[$cnt]['Url'] = (string)$item->DetailPageURL;
168: $items[$cnt]['LargeImage'] = (string)$item->LargeImage->URL;
169: $items[$cnt]['MediumImage'] = (string)$item->MediumImage->URL;
170: $items[$cnt]['SmallImage'] = (string)$item->SmallImage->URL;
171: $cnt++;
172: }
173: $page++;
174: $reqs['ItemPage'] = $page;
175: $url = $this->getURL_AWS($reqs); //リクエストURL
176: $this->webapi = $url;
177: $res = @simplexml_load_file($url);
178: if (! isset($res->Items->Request->IsValid) ||
179: (preg_match('/True/i', $res->Items->Request->IsValid) == 0)) continue;
180:
181: } while ($page <= $total_pages);
182:
183: $this->error = FALSE;
184: $this->errmsg = '';
185: $this->hits = $cnt - 1;
186:
187: return $this->hits;
188: }

Amazon Web Service は同時に1ページ(10件)しか取得できない。そこで、Items->TotalPages のページ数だけ繰り返し Amazon Web Service を呼び出す。
参考書籍
![]() |
Amazon Web Services実践入門 | ||
著者 | 舘岡守/今井智明 | ||
出版社 | 技術評論社 | ||
サイズ | 単行本 | ||
発売日 | 2015年11月10日頃 | ||
価格 | 2,838円(税込) | ||
ISBN | 9784774176734 | ||
柔軟な開発を可能にするインフラ構築・運用の勘所。ブラウザでの設定もコマンド操作も丁寧に解説。 | |||
![]() |
Amazon Web Services パターン別構築・運用ガイド | ||
著者 | NRIネットコム株式会社/佐々木拓郎 | ||
出版社 | SBクリエイティブ | ||
サイズ | 単行本 | ||
発売日 | 2015年03月26日頃 | ||
価格 | 3,740円(税込) | ||
ISBN | 9784797382570 | ||
目的に応じたサービスの選び方と導入方法を詳細にわかりやすく解説。構築手順がよくわかる! | |||
![]() |
Amazon Web Services入門 | ||
著者 | 加藤章 | ||
出版社 | インプレス | ||
サイズ | 単行本 | ||
発売日 | 2014年09月 | ||
価格 | 2,530円(税込) | ||
ISBN | 9784844336471 | ||
![]() |
Amazon Web Services 徹底活用ガイド | ||
著者 | 日経systems編集部/日経network編集部 | ||
出版社 | 日経BP | ||
サイズ | ムックその他 | ||
発売日 | 2014年12月13日頃 | ||
価格 | 2,640円(税込) | ||
ISBN | 9784822269999 | ||
参考サイト
- Amazon Web Service(AWS)
- PHPで楽天ブックスAPIを使って書籍検索:ぱふぅ家のホームページ
- AWS SDK for PHPのVersion 3が利用可能になりました:Amazon Web Services ブログ
- さあ、AWSをはじめよう! for PHPer:Shin x blog
- Amazon Web Servicesを利用した中規模Webシステムの構築・運用事例について
- Amazonのサービス一覧:PHPプログラマのバリ・ポジ情報ブログ