Created
August 14, 2013 15:05
-
-
Save DQNEO/6231929 to your computer and use it in GitHub Desktop.
Amazon Product Advertising APIをPHPから使うサンプルコード。PEAR非依存。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
main(); | |
function main() | |
{ | |
// https://images-na.ssl-images-amazon.com/images/G/09/associates/paapi/dg/index.html?CommonRequestParameters.html | |
$params = array( | |
'AssociateTag' => '393910-22', | |
'Operation' => 'ItemLookup', | |
'IdType' => 'ISBN', | |
'ItemId' => '4873114799', //'4894712741', //ISBN | |
'SearchIndex' => 'Books', | |
'ResponseGroup' => 'OfferSummary', //'OfferFull,ItemAttributes', | |
); | |
$amazon = new Amazon($params); | |
$url = $amazon->getAPIURL(); | |
// この URL にアクセスすれば、API リクエストができます | |
echo $url . PHP_EOL; | |
//echo file_get_contents($url); | |
$amazon_xml=simplexml_load_string(@file_get_contents($url)); | |
print_r($amazon_xml->Items); | |
} | |
class Amazon | |
{ | |
private $params = array( | |
'Service' => 'AWSECommerceService', | |
'Version' => '2009-03-31', | |
); | |
function __construct($params) | |
{ | |
$this->params = array_merge($this->params,$params); | |
} | |
function getAPIURL() | |
{ | |
$params = $this->params; | |
$params['AWSAccessKeyId'] = $_ENV["ACCESS_KEY"]; | |
$secret_access_key = $_ENV["SECRET_KEY"]; | |
/* | |
$params['Operation'] = 'ItemSearch'; // ← ItemSearch オペレーションの例 | |
$params['Keywords'] = 'もやし'; // ← 文字コードは UTF-8 | |
*/ | |
// Timestamp パラメータを追加します | |
// - 時間の表記は ISO8601 形式、タイムゾーンは UTC(GMT) | |
$params['Timestamp'] = gmdate('Y-m-d\TH:i:s\Z'); | |
// パラメータの順序を昇順に並び替えます | |
ksort($params); | |
// canonical string を作成します | |
$canonical_string = ''; | |
foreach ($params as $k => $v) { | |
$canonical_string .= '&'.urlencode_rfc3986($k).'='.urlencode_rfc3986($v); | |
} | |
$canonical_string = substr($canonical_string, 1); | |
// 署名を作成します | |
// - 規定の文字列フォーマットを作成 | |
// - HMAC-SHA256 を計算 | |
// - BASE64 エンコード | |
$baseurl = 'http://ecs.amazonaws.jp/onca/xml'; | |
$parsed_url = parse_url($baseurl); | |
$string_to_sign = "GET\n{$parsed_url['host']}\n{$parsed_url['path']}\n{$canonical_string}"; | |
$signature = base64_encode(hash_hmac('sha256', $string_to_sign, $secret_access_key, true)); | |
// URL を作成します | |
// - リクエストの末尾に署名を追加 | |
$url = $baseurl.'?'.$canonical_string.'&Signature='.urlencode_rfc3986($signature); | |
return $url; | |
} | |
} | |
// RFC3986 形式で URL エンコードする関数 | |
function urlencode_rfc3986($str) | |
{ | |
return str_replace('%7E', '~', rawurlencode($str)); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output (XML)