Release of source code for my ASIN to EAN, and EAN to ASIN converter!
Following this post, you were many to ask me for the source code of my ASIN to EAN and EAN to ASIN converter, I have decided to make it publicly available. I only dare ask you to do the same if you improve it or add new functionalities, such as a mass conversion (which is still on my roadmap, but if you do it before I’ll be glad not having to do it).
There are basically 4 files that are doing the job: 1 for the processing (+1 to send the requests), 1 for the UI structure, and 1 for CSS styles.
1. processing.php. There are two functions that make REST requests to Amazon’s servers. For this you’ll need to put your own KeyID (or subscription ID) and Secret Access Key at the beginning of this file.
<?php
include("aws_signed_request.php");
/* CUSTOM VARIABLES */
define('AWS_ACCESS_KEY_ID','0KWABHXFYEKBE4692D02'); // Put your own KeyID (or Subscription ID) instead of "MyKeyID". You need an Amazon developer account for that.
define('AWS_SECRET_ACCESS_KEY','YourSecretKeyHere');
/* END CUSTOM VARIABLES */
$tag_fr = "fondation-21";
$tag_uk = "key0c-21";
$tag_de = "fondation01-21";
$tag_it = "key21-21";
$tag_es = "key06-21";
$tag_com = "key0c-20";
extract($_POST);
$items = explode(";",$ItemId);
if (count((array) $items) > 1) {
echo "<em>Batch request</em><br />";
}
foreach ((array) $items as $key => $item) {
if (count((array) $items) > 1) echo $item . "\t";
switch($locale) {
case 'fr':
$assoc_tag = $tag_fr;
break;
case 'co.uk':
$assoc_tag = $tag_uk;
break;
case 'de':
$assoc_tag = $tag_de;
break;
case 'it':
$assoc_tag = $tag_it;
break;
case 'com':
$assoc_tag = $tag_com;
break;
case 'es':
$assoc_tag = $tag_es;
break;
default:
$assoc_tag = $tag_com;
break;
}
switch ($mode) {
case "ASIN2EAN":
ASINItemLookup($item, $locale, '', $assoc_tag);
break;
case "EAN2ASIN":
EANItemLookup($item, $locale, $SearchIndex, $assoc_tag);
break;
}
if ($key < count((array) $items)-1) {
echo "\n<br />";
}
ob_flush();
flush();
}
function ASINItemLookup($ItemId, $locale, $SearchIndex, $assoc_tag){
$parsed_xml = aws_signed_request($locale, array("AssociateTag"=>$assoc_tag, "Operation"=>"ItemLookup", "ItemId"=>$ItemId, "IdType"=>"ASIN", "ResponseGroup"=>"ItemAttributes"), AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, $assoc_tag);
if ($parsed_xml === False)
{
echo "Did not work.\n";
}
else
{
if(isset($parsed_xml->Items->Request->Errors->Error->Code)) {
echo "<em>Warning</em><br />";
echo "<b>Error code</b>: ".$parsed_xml->Items->Request->Errors->Error->Code."<br />";
echo "<b>Description</b>: ".$parsed_xml->Items->Request->Errors->Error->Message;
}
else {
print($parsed_xml->Items->Item->ItemAttributes->EAN);
}
}
}
function EANItemLookup($ItemId, $locale, $SearchIndex, $assoc_tag){
$parsed_xml = aws_signed_request($locale, array("AssociateTag"=>$assoc_tag,"Operation"=>"ItemLookup","ItemId"=>$ItemId,"IdType"=>"EAN","ResponseGroup"=>"ItemAttributes","SearchIndex"=>$SearchIndex), AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, $assoc_tag);
if ($parsed_xml === False)
{
echo "Did not work.\n";
}
else
{
if(isset($parsed_xml->Items->Request->Errors->Error->Code)) {
echo "<em>Warning</em><br />";
echo "<b>Error code</b>: ".$parsed_xml->Items->Request->Errors->Error->Code."<br />";
echo "<b>Description</b>: ".$parsed_xml->Items->Request->Errors->Error->Message;
}
else {
print($parsed_xml->Items->Item->ASIN);
}
}
}
?>
2. Here is the content of the file aws_signed_request.php that is used to create and sign requests with the secret key, following Amazon requirements since the 15th of August 2009. The original version can also be found here.
<?php
function aws_signed_request ( $locale, $params, $public_key, $private_key, $associate_tag ) {
/*
Copyright (c) 2009 Ulrich Mierendorff
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
/*
Parameters:
$locale - the Amazon(r) locale (ca,com,co.uk,de,fr,jp)
$params - an array of parameters, eg. array("Operation"=>"ItemLookup",
"ItemId"=>"B000X9FLKM", "ResponseGroup"=>"Small")
$public_key - your "Access Key ID"
$private_key - your "Secret Access Key"
$associate_tag - your Associate Tag i.e. myamazontag-20
*/
// Some paramters
$method = 'GET';
$host = 'webservices.amazon.' . $locale;
$uri = '/onca/xml';
// Additional parameters
$params[ 'Service' ] = 'AWSECommerceService';
$params[ 'AWSAccessKeyId' ] = $public_key;
// GMT timestamp
$params[ 'Timestamp' ] = gmdate( "Y-m-d\TH:i:s\Z" );
// API version
$params[ 'Version' ] = '2011-08-01';
$params[ 'AssociateTag' ] = $associate_tag;
$params[ 'XMLEscaping' ] = 'Double';
// Sort the parameters
ksort( $params );
// Create the canonicalized query
$canonicalized_query = array();
foreach ( $params as $param => $value ) {
$param = str_replace( '%7E', '~', rawurlencode( $param ) );
$value = str_replace( '%7E', '~', rawurlencode( $value ) );
$canonicalized_query[] = $param . '=' . $value;
}
$canonicalized_query = implode( '&', $canonicalized_query );
// Create the string to sign
$string_to_sign = $method . "\n" . $host . "\n" . $uri . "\n" . $canonicalized_query;
// Calculate HMAC with SHA256 and base64-encoding
$signature = base64_encode( hash_hmac( 'sha256', $string_to_sign, $private_key, TRUE ) );
// Encode the signature for the request
$signature = str_replace( '%7E', '~', rawurlencode( $signature ) );
// Create request
$request = 'http://' . $host . $uri . '?' . $canonicalized_query . '&Signature=' . $signature;
// Do request
// Choose depending on availability of curl
//$response = @file_get_contents($request);
$response = file_get_content_curl($request);
if ( FALSE === $response ) {
return FALSE;
} else {
// Parse XML
$xml = simplexml_load_string( $response );
if ( FALSE === $xml )
return FALSE; // no xml
else
return $xml;
}
}
function file_get_content_curl($request)
{
$session = curl_init($request);
curl_setopt($session, CURLOPT_HEADER, false);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($session);
curl_close($session);
return $response;
}
?>
2. Here is the index.php file with the UI using AJAX.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>ASIN to EAN converter</title>
<link href="styles.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
var xhr_processing = null;
String.prototype.stripSpaces = function( ){
//return this.replace( /\s/g, "" );
return this.replace(/[^a-zA-Z0-9;]/g,'');
};
function createObject_xhr_processing() {
if(window.XMLHttpRequest) // Firefox
xhr_processing = new XMLHttpRequest();
else if(window.ActiveXObject) // Internet Explorer
xhr_processing = new ActiveXObject("Microsoft.XMLHTTP");
else { // XMLHttpRequest non support par le navigateur
alert("Votre navigateur ne supporte pas les objets XMLHTTPRequest...");
}
}
//B000PMGQTM
function convertFunction(mode) {
xhr_processing.open("POST", "processing.php", true);
xhr_processing.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ItemId = encodeURIComponent(document.getElementById("ItemIdInput"+mode).value.stripSpaces());
locale = encodeURIComponent(document.getElementById("localeInput"+mode).value);
SearchIndex = encodeURIComponent(document.getElementById("SearchIndexInput").value);
Datagram = "ItemId="+ItemId+"&locale="+locale+"&SearchIndex="+SearchIndex+"&mode="+mode;
xhr_processing.send(Datagram);
document.getElementById("ItemIdOutput"+mode).value = "Please wait..."
xhr_processing.onreadystatechange = function() {
if(xhr_processing.readyState == 4) {
var RegExp1 = /.*Warning.*/;
var RegExp2 = /.*Batch.*/;
if (RegExp1.test(xhr_processing.responseText)) {
document.getElementById("ItemIdOutput"+mode).value = "An error occurred."
document.getElementById("debug"+mode).innerHTML = xhr_processing.responseText;
}
else if (RegExp2.test(xhr_processing.responseText)) {
document.getElementById("ItemIdOutput"+mode).value = "Batch request. Results below."
document.getElementById("debug"+mode).innerHTML = xhr_processing.responseText;
}
else {
element = document.getElementById("ItemIdOutput"+mode);
element.value = xhr_processing.responseText;
document.getElementById("debug"+mode).innerHTML = "";
//Si DIV : element.innerHTML = xhr_processing.responseText;
//innerHTML est compatible mais ne respecte pas les spécifications DOM
}
}
}
}
function retournepressepapier() {
return window.clipboardData.getData("Text").stripSpaces();
}
function copiedanspressepapier(mode) {
window.clipboardData.setData("Text",document.getElementById("ItemIdOutput"+mode).value);
}
function dispOnglet(onglet) {
document.getElementById(onglet).style.display = "block";
if (onglet == "ASIN2EAN") {
document.getElementById("EAN2ASIN").style.display = "none";
}
if (onglet == "EAN2ASIN") {
document.getElementById("ASIN2EAN").style.display = "none";
}
}
function changeSearchIndexes(locale) {
document.getElementById("SearchIndexInput").options.length = 0;
var SearchIndexes = new Array();
switch (locale) {
case "cn":
SearchIndexes = ["All","Apparel","Appliance","Automotive","Baby","Beauty","Books","Electronics","Grocery","HealthPersonalCare","Home","HomeImprovement","Jewelry","Misc","Music","OfficeProducts","Photo","Shoes","Software","SportingGoods","Toys","Video","VideoGames","Watches"];
break;
case "fr":
SearchIndexes = ["All","Apparel","Baby","Beauty","Blended","Books","Classical","DVD","Electronics","ForeignBooks","HealthPersonalCare","Jewelry","Kitchen","Lighting","MP3Downloads","Music","MusicalInstruments","MusicTracks","OfficeProducts","Outlet","Shoes","Software","SoftwareVideoGames","VHS","Video","VideoGames","Watches"];
break;
case "de":
SearchIndexes = ["All","Apparel","Automotive","Baby","Blended","Beauty","Books","Classical","DVD","Electronics","ForeignBooks","Grocery","HealthPersonalCare","HomeGarden","Jewelry","KindleStore","Kitchen","Lighting","Magazines","MP3Downloads","Music","MusicalInstruments","MusicTracks","OfficeProducts","OutdoorLiving","Outlet","PCHardware","Photo","Software","SoftwareVideoGames","SportingGoods","Tools","Toys","VHS","Video","VideoGames","Watches"];
break;
case "co.uk":
SearchIndexes = ["All","Apparel","Automotive","Baby","Beauty","Blended","Books","Classical","DVD","Electronics","Grocery","HealthPersonalCare","HomeGarden","Jewelry","Kitchen","Lighting","MP3Downloads","Music","MusicalInstruments","MusicTracks","OfficeProducts","OutdoorLiving","Outlet","Shoes","Software","SoftwareVideoGames","Toys","VHS","Video","VideoGames","Watches"];
break;
case "ca":
SearchIndexes = ["All","Blended","Books","Classical","DVD","Electronics","ForeignBooks","Kitchen","Music","Software","SoftwareVideoGames","VHS","Video","VideoGames"];
break;
case "it":
SearchIndexes = ["All","Books","DVD","Electronics","ForeignBooks","Garden","Kitchen","Music","Shoes","Software","Toys","VideoGames","Watches"];
break;
case "co.jp":
SearchIndexes = ["All","Apparel","Automotive","Baby","Beauty","Blended","Books","Classical","DVD","Electronics","ForeignBooks","Grocery","HealthPersonalCare","Hobbies","HomeImprovement","Jewelry","Kitchen","MP3Downloads","Music","MusicalInstruments","MusicTracks","OfficeProducts","Shoes","Software","SportingGoods","Toys","VHS","Video","VideoGames","Watches"];
break;
case "com":
SearchIndexes = ["All","Apparel","Appliances","ArtsAndCrafts","Automotive","Baby","Beauty","Blended","Books","Classical","DigitalMusic","DVD","Electronics","HealthPersonalCare","HomeGarden","Industrial","Jewelry","KindleStore","Kitchen","Magazines","Merchants","Miscellaneous","MobileApps","Music","MusicalInstruments","MusicTracks","OfficeProducts","OutdoorLiving","PCHardware","PetSupplies","Photo","Shoes","Software","SportingGoods","Tools","Toys","UnboxVideo","VHS","Video","VideoGames","Watches","Wireless","WirelessAccessories"];
break;
default:
SearchIndexes = ["All"];
break;
}
for (i=0; i<SearchIndexes.length; i++) {
document.getElementById('SearchIndexInput').options[i]=new Option(SearchIndexes[i],SearchIndexes[i]);
}
}
</script>
</head>
<body onload='createObject_xhr_processing(); dispOnglet("ASIN2EAN"); changeSearchIndexes("fr");'>
<div class="ongletButton" onMouseOver="this.style.background='#CCC'" onMouseOut="this.style.background='#DDD'" onClick='dispOnglet("ASIN2EAN");'><a>ASIN to EAN</a></div><div class="ongletButton" onMouseOver="this.style.background='#CCC'" onMouseOut="this.style.background='#DDD'" onClick='dispOnglet("EAN2ASIN");'><a>EAN to ASIN</a></div>
<div class="onglet" id="ASIN2EAN">
<h1>ASIN to EAN converter</h1>
<form name='converterForm'>
<b>ASIN code</b><br />
<input type='text' id='ItemIdInputASIN2EAN' size='40' onblur="this.value = this.value.stripSpaces()"/><input type="button" value="Paste" onclick="document.getElementById('ItemIdInputASIN2EAN').value = retournepressepapier();"><br />
<input type='button' name='convertButton' value='Convert to EAN' onclick='convertFunction("ASIN2EAN");' />
<select name='localeInput' id='localeInputASIN2EAN'>
<option value='ca'>Canada</option>
<option value='cn'>China</option>
<option selected value='fr'>France</option>
<option value='de'>Germany</option>
<option value='it'>Italy</option>
<option value='co.jp'>Japan</option>
<option value='co.uk'>United Kingdom</option>
<option value='com'>USA</option>
</select>
<br />
<b>EAN code</b><br />
<input style="background-color:#DDD" type='text' name='ItemIdOutput' id='ItemIdOutputASIN2EAN' size='40' onFocus="select()" readonly /><input type="button" value="Copy" onclick="copiedanspressepapier('ASIN2EAN');"><br />
</form>
<div id="debugASIN2EAN" width="200px"></div>
</div>
<div class="onglet" id="EAN2ASIN" style="display:none;">
<h1>EAN to ASIN converter</h1>
<form name='converterForm'>
<b>EAN code</b><br />
<input type='text' id='ItemIdInputEAN2ASIN' size='40' onblur="this.value = this.value.stripSpaces()"/><input type="button" value="Paste" onclick="document.getElementById('ItemIdInputEAN2ASIN').value = retournepressepapier();"><br />
<input type='button' name='convertButton' value='Convert to ASIN' onclick='convertFunction("EAN2ASIN");' />
<select name='localeInput' id='localeInputEAN2ASIN' onChange="changeSearchIndexes(this.value)">
<option value='ca'>Canada</option>
<option value='cn'>China</option>
<option selected value='fr'>France</option>
<option value='de'>Germany</option>
<option value='it'>Italy</option>
<option value='co.jp'>Japan</option>
<option value='co.uk'>United Kingdom</option>
<option value='com'>USA</option>
</select>
<br />
<select name='SearchIndexInput' id='SearchIndexInput' style="width: 150px;">
</select>
<br />
<b>ASIN code</b><br />
<input style="background-color:#DDD" type='text' name='ItemIdOutput' id='ItemIdOutputEAN2ASIN' size='40' onFocus="select()" readonly /><input type="button" value="Copy" onclick="copiedanspressepapier('EAN2ASIN');"><br />
</form>
<div id="debugEAN2ASIN" width="200px"></div>
</div>
<a id="apigo" href="http://www.amazon.fr/#?_encoding=UTF8&tag=fondation-21&linkCode=ur2&camp=1642&creative=19458" style="color: #CCC; font-size: 8pt;" target="_blank">Go to Amazon</a>
<div id="debugAll"></div>
</body>
</html>
3. And finally, our beloved styles.css:
/* standard elements */
html {min-height: 100%;}
* {
margin: 0;
padding: 0;
}
a {color: #048;}
a:hover {color: #06C;}
body {
background-color: #E7E7E2;
color: #444;
font: normal 62.5% Tahoma,sans-serif;
padding-top: 20px;
padding-left: 20px;
}
p,code,ul {padding-bottom: 1.2em;}
li {list-style: none;}
h1 {font: normal 1.8em Tahoma,sans-serif;}
h2 {font: bold 1.4em sans-serif;}
h3 {font: bold 1em Tahoma,sans-serif;}
form,input {margin: 0; padding: 0; display: inline;}
code {
background: #FFF;
border: 1px solid #EEE;
border-left: 6px solid #CCC;
color: #666;
display: block;
font: normal 1em Tahoma,sans-serif;
line-height: 1.6em;
margin-bottom: 12px;
padding: 8px 10px;
white-space: pre;
}
blockquote {
display: block;
font-weight: bold;
padding-left: 28px;
}
h1,h2,h3 {padding-top: 6px; color: #553; margin-bottom: 4px;}
/*Custom design */
.ongletButton {
width: 175px;
float: left;
border-top: 0px;
border-right: 1px;
border-bottom: 1px;
border-left: 0px;
border-color: #555;
border-style: solid;
/* display: inline; */
cursor: pointer;
text-align: center;
background-color: #DDD;
}
.ongletButton a {
color: black;
font-weight: bold;
}
.onglet {
width: 350px;
float:none;
clear: both;
}
Feel free to make any suggestions to improve it! Here again is the final output, brought to you by erwinmayer.com labs:
Update (21/09/2009): This code is now compliant with Amazon Web Services new signature requirements.
Update (27/08/2011): This code has been updated to support IT (Italy) and CN (China) locales, and the version dated 2011-08-01 of the Amazon Product Advertising API.
Update (02/10/2011): This code has been updated to support ES (Spain) locale.






3 commentaires
FYI I added today UK, Japan and Canada support. I updated the source code as well.
[...] Related Posts Release of source code for my ASIN to EAN, and EAN to ASIN converter! [...]
Greetings,
Thanks for releasing this code! I have to convert a large number of ASIN as Amazon canceled my account (since the account is based in Colorado).
–RayJH