Amazon get item details by searching ASIN using API PHP/jQuery - php

I need to get Amazon product details(Item name, Brand, Price etc..) by searching ASIN.
I look at Amazon's API and not able to find the exact code to do it.
https://docs.aws.amazon.com/AWSECommerceService/latest/DG/ItemLookup.html
I want to integrate with PHP or Javascript. Any help? Thanks in Advance.

Here is a simple example. You have to replace $public_key, $private_key and $associate_tag with your own values.i have not tested this but go through this and let us know whether its useful.
<?php
include('aws_signed_request.php');
$public_key = '********';
$private_key = '********';
$associate_tag = '********';
// generate signed URL
$request = aws_signed_request('com', array(
'Operation' => 'ItemLookup',
'ItemId' => 'B008GG93YE',
'ResponseGroup' => 'Small'), $public_key, $private_key, $associate_tag);
// do request (you could also use curl etc.)
$response = #file_get_contents($request);
if ($response === FALSE) {
echo "Request failed.\n";
} else {
// parse XML
$pxml = simplexml_load_string($response);
if ($pxml === FALSE) {
echo "Response could not be parsed.\n";
} else {
if (isset($pxml->Items->Item->ItemAttributes->Title)) {
echo $pxml->Items->Item->ItemAttributes->Title, "\n";
}
}
}
?>
aws_signed_request.php code
<?php
function aws_signed_request($region, $params, $public_key, $private_key, $associate_tag=NULL, $version='2011-08-01')
{
// some paramters
$method = 'GET';
$host = 'webservices.amazon.'.$region;
$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'] = $version;
if ($associate_tag !== NULL) {
$params['AssociateTag'] = $associate_tag;
}
// 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;
return $request;
}
?>

Related

ecs.amazonaws.com Api We encountered an internal error

I recently face problem with amazon lookupitem search api . It was working before In a script I have been successfully executing hundreds requests but now i don't know what is the problem Here is my Amazon.php
class Amazon
{
// public key
var $publicKey = "[public key]";
// private key
var $privateKey = "[private key]";
// affiliate tag
var $affiliateTag = 'affiliateTag';
/**
* #param $param
* #return mixed
*/
public function generateSignature($param)
{
// url basics
$signature['method'] = 'GET';
$signature['host'] = 'ecs.amazonaws.' . $param['region'];
$signature['uri'] = '/onca/xml';
// necessary parameters
$param['Service'] = "AWSECommerceService";
$param['AWSAccessKeyId'] = $this->publicKey;
$param['Timestamp'] = gmdate("Y-m-d\TH:i:s\Z");
$param['Version'] = '2009-10-01';
ksort($param);
foreach ($param as $key => $value) {
$key = str_replace("%7E", "~", rawurlencode($key));
$value = str_replace("%7E", "~", rawurlencode($value));
$queryParamsUrl[] = $key . "=" . $value;
}
// glue all the "params=value"'s with an ampersand
$signature['queryUrl'] = implode("&", $queryParamsUrl);
// we'll use this string to make the signature
$StringToSign = $signature['method'] . "\n" . $signature['host'] . "\n" . $signature['uri'] . "\n" . $signature['queryUrl'];
// make signature
$signature['string'] = str_replace("%7E", "~",
rawurlencode(
base64_encode(
hash_hmac("sha256", $StringToSign, $this->privateKey, True
)
)
)
);
return $signature;
}
/**
* #param $params
* #return string
*
*/
public function getSignedUrl($params)
{
$signature = $this->generateSignature($params);
return $signedUrl = "http://" . $signature['host'] . $signature['uri'] . '?' . $signature['queryUrl'] . '&Signature=' . $signature['string'];
}
}
and here is where i call it return a response
error 500 We 'encountered an internal error. Please try again.'
$Amazon = new Amazon();
$parameters = array(
"region" => "com",
"AssociateTag" => 'affiliateTag',
'ResponseGroup' => 'Medium',
"Operation" => "ItemLookup",
"SearchIndex" => "Books",
"IdType" => "ISBN",
"ItemId" => $isbn,
);
$queryUrl = $Amazon->getSignedUrl($parameters);
$response = simplexml_load_file($queryUrl);

Only text on the website when i put the api

I have this API for redtube but when I put this in my .php file and show the site theres comes up this, why the site does not show the videos, its only text on the site when I preview the site. Nothing shows video.
Can someone help me or know what I am doing wrong ?
`
// Simple url builder function.
// You can use CURL for passing HTTP GET parameters and to call the RedTube API.
function RedTubeApiCall($http_server, $params = array())
{
$query_string = '?';
if(is_array($params) && count($params)){
foreach($params as $k=>$v){
$query_string .= $k.'='.$v.'&';
}
$query_string = rtrim($query_string,'&');
}
$content = file_get_contents($http_server.$query_string);
return $content;
}
$http = 'http://api.redtube.com/';
$call = 'redtube.Categories.getCategoriesList';
$params = array(
'output' => 'xml',
'data' => $call
);
$response = RedTubeApiCall($http , $params);
if ($response) {
// handle the response
}
// Simple url builder function.
// You can use CURL for passing HTTP GET parameters and to call RedTube API.
function RedTubeApiCall($http_server, $params = array())
{
$query_string = '?';
if(is_array($params) && count($params)){
foreach($params as $k=>$v){
$query_string .= $k.'='.$v.'&';
}
$query_string = rtrim($query_string,'&');
}
$content = file_get_contents($http_server.$query_string);
return $content;
}
$http = 'http://api.redtube.com/';
$call = 'redtube.Categories.getCategoriesList';
$params = array(
'output' => 'xml',
'data' => $call
);
$response = RedTubeApiCall($http , $params);
if ($response) {
// handle the response
}
?>``

Invalid Signature while Connecting to Instapaper's Xauth on PHP

I've been trying to get a PHP application to connect to Instapaper's Xauth services, but for the life of me I can't get it to work. I keep getting an "403: Invalid signature." error.
The error says that my signature base string wasn't what it expected, but when I compare the signature base string I construct with what they say they expect, they're exactly the same (sensitive information removed):
My signature base string:
POST&https%3A%2F%2Fwww.instapaper.com%2Fapi%2F1%2Foauth%2Faccess_token&oauth_callback%3DMy_URL%26oauth_consumer_key%3DCONSUMER_KEY%26oauth_nonce%3Dfe379af261aca07d890d2cfaa0f19ce0%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1461898452%26oauth_version%3D1.0%26x_auth_mode%3Dclient_auth%26x_auth_password%3DPASSWORD%26x_auth_username%3DEXAMPLE%2540gmail.com
What the error says it expects:
POST&https%3A%2F%2Fwww.instapaper.com%2Fapi%2F1%2Foauth%2Faccess_token&oauth_callback%3DMy_URL%26oauth_consumer_key%3DCONSUMER_KEY%26oauth_nonce%3Dfe379af261aca07d890d2cfaa0f19ce0%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1461898452%26oauth_version%3D1.0%26x_auth_mode%3Dclient_auth%26x_auth_password%3DPASSWORD%26x_auth_username%3DEXAMPLE%2540gmail.com
I pulled my php library from https://github.com/mheap/Instapaper-XAuth-PHP, but it's old so I've tried to modify it to work with the current Instapaper API. I believe I'm generating the signature string correctly and am following the instructions found here: https://dev.twitter.com/oauth/overview/creating-signatures and here: http://oauthbible.com/
I don't know what's wrong with the code, can someone please help?
class XAuth_Connection
{
private $_headers = array(
"oauth_signature_method" => "HMAC-SHA1",
"oauth_version" => "1.0",
"oauth_callback" => "MY_URL",
"oauth_consumer_key" => "",
"oauth_nonce" => "",
"oauth_timestamp" => ""
);
private $_params = array(
"x_auth_mode" => "client_auth",
"x_auth_username" => "",
"x_auth_password" => ""
);
private $_access_url = '';
public function __construct($key, $private, $access_url)
{
$this->_headers['oauth_consumer_key'] = $key;
$this->_headers['oauth_nonce'] = md5(uniqid(rand(), true));
$this->_headers['oauth_timestamp'] = time();
$this->_oauth_consumer_private = $private;
$this->_access_url = $access_url;
}
public function set_credentials($user, $password)
{
$this->_params['x_auth_username'] = $user;
$this->_params['x_auth_password'] = $password;
}
public function get_params_as_string()
{
ksort($this->_params);
$req = array();
foreach ($this->_params as $k => $v)
{
$req[] = $k ."=". $this->encode($v);
}
return implode("&", $req);
}
public function get_headers_as_string()
{
ksort($this->_headers);
$req = array();
foreach ($this->_headers as $k => $v)
{
$req[] = $k . "=" . $this->encode($v);
}
return implode("&", $req);
}
public function generate_signature()
{
//combine the parameters, encode, and sort them
$temp_params = array_merge($this->_params, $this->_headers);
$encoded_params = Array();
foreach($temp_params as $k => $v){
$encoded_params[$this->encode($k)] = $this->encode($v);
}
ksort($encoded_params);
//Build the param string
$param_base_string = "";
foreach($encoded_params as $k => $v){
$param_base_string .= $k .'='. $v . '&';
}
$param_base_string = rtrim($param_base_string, '&');
//create the signature base
$signature_base = 'POST&' . $this->encode($this->_access_url) .'&'. $this->encode($param_base_string);
$key = $this->encode($this->_oauth_consumer_private) . '&';
return base64_encode(hash_hmac("sha1",$signature_base, $key, true));
}
public function login()
{
$this->_headers['oauth_signature'] = $this->generate_signature();
ksort($this->_headers);
$header_str = 'OAuth ';
foreach ($this->_headers as $k => $v)
{
$header_str .= $k.'="'.$this->encode($v).'", ';
}
$header_str = rtrim($header_str, ', ');
$oauth_str = $this->get_params_as_string();
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->_access_url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $oauth_str);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Authorization: " . $header_str));
$exec = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($info['http_code'] != 200)
{
return false;
}
parse_str($exec, $r);
return $r;
}
private function encode($s)
{
return ($s === false ? $s : str_replace('%7E','~',rawurlencode($s)));
}
}

PHP array to get single valid XML

I use the following api to get product info from amazon.
It uses a single value for variable $asin to get the data and print it as xml. It works fine, but this is only for one product at a time…
I would like instead of a single variable $asin, to use an array with multiple values and print to one single xml.
I tried to use foreach, but I get en xml declaration for every loop.
Where do I need to use foreach in my code? Thanks for the help.
<?php
// Region code and Product ASIN
$response = getAmazonPrice("com", "B00KQPGRRE");
function getAmazonPrice($region, $asin) {
$xml = aws_signed_request($region, array(
"Operation" => "ItemLookup",
"ItemId" => $asin,
"IncludeReviewsSummary" => False,
"ResponseGroup" => "Medium,OfferSummary",
));
$item = $xml->Items->Item;
$title = htmlentities((string) $item->ItemAttributes->Title);
$url = htmlentities((string) $item->DetailPageURL);
$image = htmlentities((string) $item->MediumImage->URL);
$price = htmlentities((string) $item->OfferSummary->LowestNewPrice->Amount);
$code = htmlentities((string) $item->OfferSummary->LowestNewPrice->CurrencyCode);
$qty = htmlentities((string) $item->OfferSummary->TotalNew);
if ($qty !== "0") {
$response = array(
"code" => $code,
"price" => number_format((float) ($price / 100), 2, '.', ''),
"image" => $image,
"url" => $url,
"title" => $title
);
}
return $response;
}
function getPage($url) {
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_FAILONERROR, true);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$html = curl_exec($curl);
curl_close($curl);
return $html;
}
function aws_signed_request($region, $params) {
$public_key = "PUBLIC_KEY";
$private_key = "PRIVATE_KEY";
$method = "GET";
$host = "ecs.amazonaws." . $region;
$host = "webservices.amazon." . $region;
$uri = "/onca/xml";
$params["Service"] = "AWSECommerceService";
$params["AssociateTag"] = "affiliate-20"; // Put your Affiliate Code here
$params["AWSAccessKeyId"] = $public_key;
$params["Timestamp"] = gmdate("Y-m-d\TH:i:s\Z");
$params["Version"] = "2011-08-01";
ksort($params);
$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);
$string_to_sign = $method . "\n" . $host . "\n" . $uri . "\n" . $canonicalized_query;
$signature = base64_encode(hash_hmac("sha256", $string_to_sign, $private_key, True));
$signature = str_replace("%7E", "~", rawurlencode($signature));
$request = "http://" . $host . $uri . "?" . $canonicalized_query . "&Signature=" . $signature;
$response = getPage($request);
var_dump($response);
$pxml = #simplexml_load_string($response);
if ($pxml === False) {
return False;// no xml
} else {
return $pxml;
}
}
?>
I used the following code to have multiple values:
<?php
// Region code and Product ASIN
$array = array("B00PXRRB2U","B00F90P9R0","B005OJU3K4");
foreach ($array as $asin) {
$response = getAmazonPrice("com", $asin);
}
function getAmazonPrice($region, $asin) {
$xml = aws_signed_request($region, array(
"Operation" => "ItemLookup",
"ItemId" => $asin,
"IncludeReviewsSummary" => False,
"ResponseGroup" => "Medium,OfferSummary",
));
The result is:
Amazon allows the lookup of up to 10 items with a single request. Its service expects the ASINs to be passed as a string separated by commas.
So you could try the following code (please note I didn't actually try it because I don't have credentials but I used it like that before and it worked):
$array = array("B00PXRRB2U","B00F90P9R0","B005OJU3K4");
$xml = aws_signed_request('com', array(
"Operation" => "ItemLookup",
"ItemId" => join(', ', $array),
"IncludeReviewsSummary" => False,
"ResponseGroup" => "Medium,OfferSummary",
));
And then I think what you're looking for will be in $xml->Items but you'd better double check that.

Twitter usertimeline code not working

I have created this test script to get data from the twitter usertimeline which I'm sure was previously working however now it returns nothing. Is there something I am missing here? (To test simply amend the constants at the top)
define('CONSUMER_KEY', '');
define('CONSUMER_SECRET', '');
define('OAUTH_TOKEN','');
define('OAUTH_SECRET','');
define('USER_ID','');
function generateSignature($oauth,$fullurl,$http_method){
// Take params from url
$main_url = explode('?',$fullurl);
$urls = explode('&',$main_url[1]);
foreach ($urls as $param){
$bits = explode('=',$param);
if (strlen($bits[0])){
$oauth[$bits[0]] = rawurlencode($bits[1]);
}
}
ksort($oauth);
$string = http_build_query($oauth);
$new_string = strtoupper($http_method).'&'.urlencode($main_url[0]).'&'.urlencode(urldecode($string));
$sign_str = CONSUMER_SECRET.'&'.OAUTH_SECRET;
return urlencode(base64_encode(hash_hmac('sha1',$new_string,$sign_str,true)));
}
function random($len,$use_chars = false,$numU = false){
$num = range(0,9);
$letu = range('A','Z');
$letl = range('a','z');
$chars = array("!","*","£","$","^","(",")","_","+");
if ($use_chars){
$arr = array_merge($num,$letu,$letl,$chars);
} else {
$arr = array_merge($num,$letu,$letl);
}
// Shuffling - new addition 11/9 to make order actually random!
shuffle($arr);
// Create a number only random string
if ($numU){ $arr = $num; }
$rand = array_rand($arr,$len);
foreach ($rand as $num){
$out[] = $arr[$num];
}
return implode('',$out);
}
$method = 'GET';
// Twitter still uses Oauth1 (which is a pain)
$oauth = array(
'oauth_consumer_key'=>CONSUMER_KEY,
'oauth_nonce'=>random(32),
'oauth_signature_method'=>'HMAC-SHA1',
'oauth_timestamp'=>time(),
'oauth_token'=>OAUTH_TOKEN,
'oauth_version'=>'1.0',
);
$url = "https://api.twitter.com/1.1/statuses/user_timeline.json?user_id=".USER_ID;
$oauth['oauth_signature'] = generateSignature($oauth,$url,$method,'');
ksort($oauth);
foreach ($oauth as $k=>$v){
$auths[] = $k.'="'.$v.'"';
}
$stream = array('http' =>
array(
'method' => $method,
// ignore_errors should be true
'ignore_errors'=>true, // http://php.net/manual/en/context.http.php - otherwise browser returns error not error content
'follow_location'=>false,
'max_redirects'=>0,
'header'=> array(
'Authorization: OAuth '.implode(', ',$auths),
'Connection: close'
)
)
);
echo $url;
$response = file_get_contents($url, false, stream_context_create($stream));
print'<pre>';print_r($stream);print'</pre>';
print'<pre>[';print_r($reponse);print']</pre>';
I found this:
// Create a number only random string
if ($numU){ $arr = $num; }
$rand = array_rand($arr,$len);
foreach ($rand as $num){
$out[] = $arr[$num];
}
I am not completly sure, but i think there shouldn't be a } after if ($numU){ $arr = $num;
I think it should be a open bracket. {
I found one more thing:
print'<pre>[';print_r($reponse);print']</pre>';
Here at the bottom of the code, you wrote "$reponse" instead of "$response"
I hope it helped! If it did, give it a upvote and choose as best answer!

Categories