OFF-SOFT.net

This site is support & information site of WEB,and Software. This site might help you that create software or Web Site…perhaps?

Use Amazon Product Advertising API with PHP

Published on| October 7th, 2009 | 10 Comments.
Summary:

This time, Amazon's Product Advertising API using, I simply want to display the search results.
Product Advertising API is to access, URL in the code, the user's Access Key ID (access key) and Secret Access Key (secret access key) embedded to authenticate based on that information, such as approval of the search perform the work.
OK with that approval, if no parameter is incorrect, the requested operation (for example, search) the results of the XML output format.

By analyzing the output of XML information, retrieve the information you want to see yourself, HTML conversion information can be output.
For example, Amazon is not one that can also be created for things like the widgets that are provided by the affiliate.

Does, immediately, PHP let's try to create the sample code.

See page: Http://Docs.amazonwebservices.com/Awsecommerceservice/Latest/Dg/
sample source :


First, let's prepare.

Amazon Product Advertising API to use, you first need to get under your ID. Also, if you also do affiliate, the affiliate ID is also required.


Access Key ID (access keys), Secret Access Key (access key secret) get the check.

  1. http://aws.amazon.com/ access to.

  2. The right "Sign Up Now" and then click the sign.
    If you do not have to sign the ID, "I am a new user." Click, create a new user ID.

  3. After you sign and return to the main screen first.

    From the right [Your Account] - [Access Identifiers] Click.
    Following the transition to the screen.

  4. The lower screen, displays the following table.

    If you have already created, Access Key ID is displayed. The Secret Access Key "Show" will be displayed by clicking.

    If you have not created yet, it's the "Create Key" and then click Create.


Afirieitoki can be created from the pages of Japan.
https://affiliate.amazon.co.jp/have access to, "create free account" and click Create.

The new account will Afirieitoki.


Access key and secret access key, direct, let's search.

Amazon's Product Advertising API is, URL parameters to manipulate, and access to information in XML makes reply.
So, WEB browser, you can see if the direct URL address.

However, using the access key and secret access key, Amazon does, and authentication, and spam protection.
Thus, URL address information, the access key and secret access key embedded obtained earlier, Amazon needs to access.

The URL embedded software access key and secret access key codes, Amazon offers the following website.
http://associates-amazon.s3.amazonaws.com/signed-requests/helper/index.html
Does using this page, URL let's create the code.

  1. To the top of the screen and enter the access key and secret access key.

  2. Unsigned URL in the code specifies the original URL. Here, enter the following as just a sample.
    
    http://ecs.amazonaws.com/onca/xml?Service=AWSECommerceService
    
    &Version=2009-03-31
    &Operation=ItemSearch
    &SearchIndex=Books
    &Keywords=harry+potter
  3. After the input, move downward, "Dispaly Signed URL" and click on the column on the "Signed URL" code to the URL will be displayed.


  4. "Signed URL" the URL and copy the code, WEB paste into your browser address.
    Then reply the following information (XML information) think it will be displayed.

    If this screen appears OK.

Check the operating environment for PHP.

Make sure that PHP can work.
The following is, Windows is an example of the command prompt confirmation.
Enter the UNIX command can be found as well.

1
2
3
4
C:\> php -v
PHP 5.1.2 (cli) (built: Jan 11 2006 16:40:00)
Copyright (c) 1997-2006 The PHP Group
Zend Engine v2.1.0, Copyright (c) 1998-2006 Zend Technologies

In this article, the version must be at least PHP5.

Now you are ready. Next, PHP code to the original sample, let's try.
PHP using the sample source, try this.

The following is a simple software to search for PHP is the sample source.

[sample.php]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
 
//-------------------------------------------------------------------
// Define your id.
//-------------------------------------------------------------------
// user id information
define("ACCESS_KEY_ID"     , 'Your Access id.     '                    );
define("SECRET_ACCESS_KEY" , 'Your Secret Access id.                  ');
define("ASSOCIATE_TAG"     , 'Your Associate id.'                      );
 
// access url(Jpanan)
define("ACCESS_URL"        , 'http://ecs.amazonaws.jp/onca/xml'        );
//	define("ACCESS_URL", 'https://aws.amazonaws.jp/onca/xml');
//-------------------------------------------------------------------
 
 
//-------------------------------------------------------------------
// this function is encode with RFC3986 format.
//-------------------------------------------------------------------
function urlencode_RFC3986($str)
{
    return str_replace('%7E', '~', rawurlencode($str));
}
 
 
//-------------------------------------------------------------------
// Main routine.
//-------------------------------------------------------------------
$base_param = 'AWSAccessKeyId='.ACCESS_KEY_ID;
 
$params = array();
 
$params['Service']        = 'AWSECommerceService';
$params['Version']        = '2009-10-01';
$params['Operation']      = 'ItemSearch';
 
$params['SearchIndex']    = 'Software';  
$params['Sort']           = 'salesrank';  
 
$params['Keywords']       = 'Windows';        // search key ( UTF-8 )
$params['AssociateTag']   = ASSOCIATE_TAG;
 
$params['ResponseGroup']  = 'ItemAttributes,Offers, Images ,Reviews ';
 
$params['SignatureMethod']  = 'HmacSHA256';   // signature format name.
$params['SignatureVersion'] = 2;              // signature version.
 
  // time zone (ISO8601 format)
$params['Timestamp']      = gmdate('Y-m-d\TH:i:s\Z'); 
 
// sort $param by asc.
ksort($params);
 
// create canonical string.
$canonical_string = $base_param;
foreach ($params as $k => $v) {
    $canonical_string .= '&'.urlencode_RFC3986($k).'='.urlencode_RFC3986($v);
}
 
// create signature strings.( HMAC-SHA256 & BASE64 )
$parsed_url = parse_url(ACCESS_URL);
$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)
				);
 
// create URL strings.
$url = ACCESS_URL.'?'.$canonical_string.'&Signature='.urlencode_RFC3986($signature);
 
// request to amazon !!
$response = file_get_contents($url);
 
// response to strings.
$parsed_xml = null;
if(isset($response)){
	$parsed_xml = simplexml_load_string($response);
}
 
$err_count=0;
 
// print out of response.
if( $response && 
    isset($parsed_xml) && 
    !$parsed_xml-->faultstring &&
    !$parsed_xml-->Items-->Request-->Errors  ){
 
	// total results num.
	$total_results = $parsed_xml-->Items-->TotalResults;
	// total results pages.
	$total_pages = $parsed_xml-->Items-->TotalPages;
 
	print("All Result Count:".$total_results."  | Pages :".$total_pages );
 
	print("
<table>");
	foreach($parsed_xml-->Items-->Item as $current){
		$nerr=0;
 
		print("
<tr>
<td><font size='-1'>");
 
		print('<a href="'.$current-->DetailPageURL.'"><img src="'.$current-->SmallImage-->URL.'" border=0></a>
');
		print('<a href="'.$current-->DetailPageURL.'">'.$current-->ItemAttributes-->Title.'</a>
');
		print($current-->ItemAttributes-->Manufacturer.'
');
 
		if(isset($current-->Offers) && isset($current-->Offers-->Offer)){
			print( $current-->Offers-->Offer-->OfferListing-->Price-->FormattedPrice.'
');
		} else {
			print($current-->ItemAttributes-->ListPrice-->FormattedPrice.'
');
		}
		if(isset($current-->CustomerReviews-->TotalReviews) && $current-->CustomerReviews-->TotalReviews>0){
			print('Rate:<a href="'.$current-->ItemLinks-->ItemLink[2]-->URL.'">');
			print($current-->CustomerReviews-->AverageRating.'('. $current-->CustomerReviews-->TotalReviews .')'.'
');
			print('</a><hr />');
		}
 
 
 
		print("</td>
</tr>
");
	}
	print("</table>
");
}

If you just use the following three items you can set, Windows software that gets the most popular search by keyword. Line 6: Sets the access key for you.
Line 7: Set your secret access key.
Line 8: Set your Asoshieitoki.


Set in your php file I uploaded to the WEB can be accessed on the server.
WEB browser, please upload it to access php.
For example, WEB server from the current, amazon If you upload to the directory under the following URL to access.

http://www.example.com/amazon/sample.php


You should see the following screen appears.




Php code where the parameters, let me explain briefly.
Where necessary changes, I think the following lines.

Line 34: 'Operation' is to specify the operation. Here, "ItemSearch" = specifies the product search.
Line 36: 'SearchIndex' is to specify a product category to be searched. Here, 'Software' = is specified software.
Line 37: 'Sort' specifies the order of search results. Here, 'salesrank' = specifies the order of popularity.
Operation, the order of search results, you can also specify a lot. For more information, please see the following pages.
http://docs.amazonwebservices.com/AWSECommerceService/latest/DG/JPSortValuesArticle.html

Line 39: 'Keywords' specifies the search key. Here, 'Windows' and the search string with the string.
The string can be specified. '+' Symbol or '' set to continue using the space.

Line 42: 'ResponseGroup' specifies the search result information. Here, 'ItemAttributes' = attribute information item, 'Offers' = Price Information, 'Images' = image information products, 'Reviews' = is specified the information on this product.
Information search results, you can also specify a lot. For more information, please see the following pages.
http://docs.amazonwebservices.com/AWSECommerceService/latest/DG/CHAP_ResponseGroupsList.html

Line 76: The output information is converted to the XML parser information between strings.


The explanation was simple, like this you can do a search of Amazon.
If you have little knowledge of PHP, you can create a widget for your Amazon.

In this way access to Amazon's Product Advertising API library for PHP, you already.
For example, Tarzan and Services_Amazon reference would also be good.

This is so easy to understand, I tried to create a solid.
Yourself, and try to touch it and everything, I think better understanding. Once it is tested invite you.



Add to your favorites(bookmarks): はてなブックマークへ追加するdel.icio.usLivedoor ClipYahoo!FC2Nifty ClipPOOKMARK. AirlinesBuzzurl(バザール)Choixnewsing

Trackback URL

After Admin approves this comment, it will be shown.


Comments

10 Responses to “Use Amazon Product Advertising API with PHP”

  1. Vinay
    February 4th, 2011 @ 16:10:46

    In Amazon web services sorting by price doesn’t work or we can say useless!!! :(

  2. ken
    July 19th, 2011 @ 16:37:39

    はじめまして。

    紹介されてるsample.phpについての質問です。
    商品の情報を取得するために、
    このページのsample.phpのサンプルを動かそうとしたのですが、ローカル環境では「Parseerror: syntax error, unexpected ‘;’ in /Applications/…../amazon_sample.php on line89」というエラーが表示されている状況です。

    私の設定の仕方に問題があるのかもしれませんが、表示させるための方法をご存知でしたら、アドバイス頂けたら嬉しいです。

    ちなみに、アクセスキー、秘密アクセスキー、アソシエイトキーの3つのキーは、自分のものを入れて試してみました。
    (webサーバに上げた場合は、ページが空白になってエラーなどの表記はありませんでした。)

    また、ページ上部に書かれていました「アクセスキーと秘密アクセスキーで、直接、検索してみましょう。」の部分のXMLの表示は成功しました。このXMLのURLについて、sample.phpのファイル上に記述する必要があるのかどうかについても、教えて頂けたらと思います。ちなみに、いまのところ私がsample.phpに修正をしたのは、上記の3つの自分のキーのみです。

    自分でもいろいろ調べているのですが、Amazon Product Advertising APIが変更になった際に『署名入り』の仕様に変わったことなども、一因なのでしょうか。
    http://www.allinthemind.biz/markup/php/amazon_product_advertising_api.html

    お忙しいなかと思いますが、sample.phpを動かすための方法について、アドバイス頂けたら幸いです。
    どうぞよろしくお願い致します。

  3. master
    July 19th, 2011 @ 22:55:42

    kenさん
    こんにちわ、管理人です。

    「Parseerror: syntax error, unexpected ‘;’ in /Applications/…../amazon_sample.php on line89」
    これは、単純にphpの文法エラーなので、まだ、amazonへのアクセスの段階ではないような感じだと思います。

    89行目あたりに ‘;’ が抜けてないですか?間違って削除したりしてないですか?

    そんな感じのエラーだと思います。今一度、ご確認されると良いかなぁと思います。
    まずは、このエラーをとることだと思います。

  4. ken
    July 20th, 2011 @ 16:01:04

    管理人さま

    返答いただき大変ありがとうございます。
    無事表示されました。

    ささいな注意ミスでした。

    有難うございました!!

  5. ゲーム失速
    August 1st, 2011 @ 13:09:34

    管理人さん…
    いちおアクセスキーなどは記入したんですが…
    サーバーにあげてみると画面が真っ白になってしまい全然使えません…

    サーバーもphp5のものを使っています。
    やっと見つけた超参考になりそうなサンプルだったのでとても使ってみたいんですが、動かなくて困ってます。

  6. master
    August 1st, 2011 @ 18:30:57

    ゲーム失速さん

    こんにちわ、管理人です。
    真っ白になってしまうのであれば、何かしらエラーになっていると思います。
    まずは、そのエラー内容を画面表示するようにしてはいかがでしょうか?
    phpのエラー表示は、php.iniで設定できるのであれば、以下のような記述を行えば良いでしょう。
    また、詳しくはGoogleで検索してみてください。いっぱいありますから。 :D

    display_errors = On
    error_reporting = E_ALL & ~E_NOTICE

  7. ゲーム失速
    August 1st, 2011 @ 18:47:00

    即座の回答ありがとうございます!!
    まだphp初心者なので頑張ってみます。

    あと、少し気になったのですが

    define(“ACCESS_KEY_ID” , ‘Your Access id. ‘ );
    define(“SECRET_ACCESS_KEY” , ‘Your Secret Access id. ‘);
    define(“ASSOCIATE_TAG” , ‘Your Associate id.’ );

    ACCESS_KEY_IDとSECRET_ACCESS_KEYとASSOCIATE_TAGの所を書き換えるんですよね?

  8. master
    August 2nd, 2011 @ 00:42:15

    ゲーム失速さん

    こんにちわ、管理人です。

    そうです。 :)

    ゲーム失速さん

    define(“ACCESS_KEY_ID” , ‘Your Access id. ‘ );
    define(“SECRET_ACCESS_KEY” , ‘Your Secret Access id. ‘);
    define(“ASSOCIATE_TAG” , ‘Your Associate id.’ );

    ‘Your Access id. ‘ ← ここにあなたのアクセスキーを設定します。
    ‘Your Secret Access id. ‘ ←  ここにあなたの秘密アクセスキーを設定します。
    ‘Your Associate id.’  ←  ここにあなたのアソシエイトキーを設定します。

    です。

  9. ゲーム失速
    August 2nd, 2011 @ 19:57:52

    今日もすみませんm(_ _)m

    結局
    Parse error: syntax error, unexpected T_DEC in /home/a9684409/public_html/amazon.php on line 85

    2つのサーバーで二つともこのメッセージが出てきました。管理人さんに教えていただいた所だけ書き換えたのですが、T_DECってたしか–のことですよね??

    別に間違ってるようには見えないんですが…
    ほんとにど素人ですみません…なにかわかることがあれば教えていただけると幸いです

  10. master
    August 3rd, 2011 @ 04:08:29

    ゲーム失速さん

    こんにちわ、管理人です。
    エラー内容は、
    85行目あたりに +,- の演算子で構文エラー(PHPの文法エラー(記述誤り))がありますよ・・・という意味です。

    原因は様々です。
    書き換えたときに全角文字列や +,- の記号が間違って入力されてしまったり、逆に削除してしまったり・・・・などなど。

    そんな感じのエラーだと思います。今一度、ご確認されると良いかなぁと思います。
    まずは、このエラーをとることだと思います。

Leave a Reply





*





Tag Cloud

Links

Site Description

This site is support & information site of WEB,and Software. This site might help you that create software or Web Site…perhaps?

Add to your favorites(bookmarks)

はてなブックマークへ追加するdel.icio.usLivedoor ClipYahoo!FC2Nifty ClipPOOKMARK. AirlinesBuzzurl(バザール)Choixnewsing