Last active
October 16, 2018 14:22
-
-
Save pandanote-info/2250aa5806b5e5ecba1f1da59f38f67d to your computer and use it in GitHub Desktop.
Amazon product advertising APIを使ってWordpressのサイドバーにリンクを表示するためのサンプルコード。
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 | |
function create_url($params,$aws_secret_key) { | |
// The region you are interested in | |
$endpoint = "webservices.amazon.co.jp"; | |
$uri = "/onca/xml"; | |
// Set current timestamp if not set | |
if (!isset($params["Timestamp"])) { | |
$params["Timestamp"] = gmdate('Y-m-d\TH:i:s\Z'); | |
} | |
// Sort the parameters by key | |
ksort($params); | |
$pairs = array(); | |
foreach ($params as $key => $value) { | |
array_push($pairs, rawurlencode($key)."=".rawurlencode($value)); | |
} | |
// Generate the canonical query | |
$canonical_query_string = join("&", $pairs); | |
// Generate the string to be signed | |
$string_to_sign = "GET\n".$endpoint."\n".$uri."\n".$canonical_query_string; | |
// Generate the signature required by the Product Advertising API | |
$signature = base64_encode(hash_hmac("sha256", $string_to_sign, $aws_secret_key, true)); | |
// Generate the signed URL | |
$request_url = 'http://'.$endpoint.$uri.'?'.$canonical_query_string.'&Signature='.rawurlencode($signature); | |
// echo "Signed URL: \"".$request_url."\""; | |
return $request_url; | |
} | |
function parse_response($response,$http_response_header,$i) { | |
$rcode = 0; | |
foreach($http_response_header as $k=>$v) { | |
if (preg_match("#HTTP/[0-9\.]+\s+([0-9]+)#",$v,$out)) { | |
$rcode = intval($out[1]); | |
} | |
} | |
if ($rcode >= 300) { | |
return ""; | |
} | |
$parsed_xml = null; | |
if (isset($response)) { | |
$parsed_xml = simplexml_load_string($response); | |
} | |
$content = ""; | |
$items = array(); | |
if ($response && isset($parsed_xml) && !$parsed_xml->faultstring && !$parsed_xml->Items->Request->Errors) { | |
foreach ($parsed_xml->Items->Item as $current) { | |
$item = array(); | |
$item["DetailPageURL"] = $current->DetailPageURL; | |
$item["Title"] = $current->ItemAttributes->Title; | |
$item["Publisher"] = $current->ItemAttributes->Publisher; | |
if (isset($current->ItemAttributes->EAN)) { | |
$item["EAN"] = $current->ItemAttributes->EAN; | |
} else { | |
$item["Price"] = $current->ItemAttributes->ListPrice->FormattedPrice; | |
} | |
$item["Feature"] = $current->ItemAttributes->Feature; | |
$item["ImageURL"] = $current->MediumImage->URL; | |
$items[] = $item; | |
} | |
} | |
//var_dump($items); | |
if (count($items) == 0) { | |
return ""; | |
} | |
return $items[mt_rand(0,count($items))]; | |
} | |
function get_card() { | |
global $wpdb; | |
$cards = array(); | |
// First, I try to get card on the database. | |
$card_rows = $wpdb->get_results("select card_for_index,card_for_page from link_cache where generated_at < NOW() and generated_at > SUBDATE(NOW(), INTERVAL 3600 SECOND)",ARRAY_A); | |
if (count($card_rows) != 0) { | |
$cards["index"] = $card_rows[0]["card_for_index"]; | |
$cards["page"] = $card_rows[0]["card_for_page"]; | |
return $cards; | |
} | |
// Get some keys from the database. | |
$key_rows = $wpdb->get_results("鍵の読みだし用のSQL文",ARRAY_A); | |
if (count($key_rows) != 0) { | |
$aws_access_key_id = $key_rows[0]["アクセスキー"]; | |
$aws_secret_key = $key_rows[0]["秘密鍵"]; | |
$amazon_associate_id = $key_rows[0]["アソシエイトID"]; | |
} else { | |
return ''; | |
} | |
$rows = $wpdb->get_results("select search_term from amazon_product_link where search_term is not null and disabled=0 order by rand() limit 0,1",ARRAY_A); | |
if (count($rows)==0) { | |
//echo "No rows. Abort here!\n"; | |
return ''; | |
} | |
$kws = $rows[0]['search_term']; | |
$params = array( | |
"Service" => "AWSECommerceService", | |
"Operation" => "ItemSearch", | |
"AWSAccessKeyId" => $aws_access_key_id, | |
"AssociateTag" => $amazon_associate_id, | |
"SearchIndex" => "All", | |
"ResponseGroup" => "Images,ItemAttributes,Offers", | |
"Keywords" => $kws | |
); | |
//echo "Keywords:".$kws."\n"; | |
$context = stream_context_create(array( | |
'http' => array('ignore_errors' => true))); | |
$response = file_get_contents(create_url($params,$aws_secret_key),false,$context); | |
$pos = strpos($http_response_header[0], '200'); | |
if ($pos === FALSE) { | |
// Workaround against an error. | |
$card_rows = $wpdb->get_results("select card_for_index,card_for_page from link_cache order by id desc limit 0,1",ARRAY_A); | |
if (count($card_rows) != 0) { | |
$cards["index"] = $card_rows[0]["card_for_index"]; | |
$cards["page"] = $card_rows[0]["card_for_page"]; | |
return $cards; | |
} | |
return ''; | |
} | |
$item = parse_response($response,$http_response_header,1); | |
if ($item === "") { | |
return ''; | |
} | |
$ean = ''; | |
if (isset($item["EAN"])) { | |
$ean = 'EAN: '.$item["EAN"].'<br/>'; | |
} | |
$price = ''; | |
if (isset($item["Price"])) { | |
$price = 'Price: '.$item["Price"].'<br/>'; | |
} | |
if (!isset($item["Title"])) { | |
error_log("Error! keyword=".urlencode($kws),0); | |
return ''; | |
} | |
$feature_str = ""; | |
$feature_max_count = 4; | |
$feature_count = 0; | |
if (count($item["Feature"]) > 0) { | |
$feature_str .= '<div style="border-top-style: solid;border-color: #1E3E8A;margin-top:4px;border-width:1px;padding-top:4px;text-align:left;">'; | |
foreach ($item["Feature"] as $feature) { | |
if ($feature_count < $feature_max_count) { | |
$feature_str .= $feature."<br/>"; | |
} | |
$feature_count++; | |
} | |
$feature_str .= '<br/><a href="'.$item["DetailPageURL"].'"><span style="color: #1E3E8A;font-size:85%;">Read more>></span></a>'; | |
$feature_str .= '</div>'; | |
} | |
$cards["index"] = '<div style="width:305px;text-align:center;margin: 0 auto;"> | |
<a href="'.$item["DetailPageURL"].'"><img src="'.$item["ImageURL"].'" align="left" style="margin-right:10px;margin-bottom:5px;"/></a><div style="margin-bottom:5px;"><a href="'.$item["DetailPageURL"].'"><span style="color:#1E3E8A;font-weight:bold;font-size:110%;">'.$item["Title"].'</span></a></div><br/>'.$item["Publisher"].'<br/>'.$ean.$price.$feature_str.' | |
<br clear="left"/> | |
</div> | |
<div class="clear"></div>'; | |
$cards["page"] = ""; | |
$wpdb->query("insert into link_cache(card_for_index,card_for_page) values('".$cards["index"]."','".$cards["page"]."')"); | |
return $cards; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment