I have to use following API URL to fetch Books information (found here)-
http://webservices.amazon.com/onca/xml?
Service=AWSECommerceService
&Operation=ItemLookup
&ResponseGroup=Large
&SearchIndex=All
&IdType=ISBN
&ItemId=076243631X
&AWSAccessKeyId=[Your_AWSAccessKeyID]
&AssociateTag=[Your_AssociateTag]
&Timestamp=[YYYY-MM-DDThh:mm:ssZ]
&Signature=[Request_Signature]
I can use PHP SDK for this, I could not find any doc on how to achieve this using SDK.
EDIT
Following this & this links, I have written following code-
<?php
date_default_timezone_set('UTC');
$ItemId = 1603843698;
$ResponseGroup = 'Offers';
//$Timestamp = gmdate("Y-M-DTh:m:sZ");
$Timestamp = gmdate("Y-m-d\TH:i:s\Z");
$AWSAccessKeyId = "EXAMPLEEXAMPLE";
$associateTag = "something-10";
echo $Timestamp;
echo "<br />";
$str = "GET\n
webservices.amazon.com\n
/onca/xml\n
AWSAccessKeyId=".$AWSAccessKeyId."&AssociateTag=".$associateTag."&ItemId=".$ItemId."&Operation=ItemLookup&ResponseGroup=".$ResponseGroup."&Service=AWSECommerceService&Timestamp=".urlencode($Timestamp);
$str = urlencode(base64_encode(hash_hmac("sha256",$str,'my secrete',true)));
$url = "http://webservices.amazon.com/onca/xml?Service=AWSECommerceService&Operation=ItemLookup&ResponseGroup=Offers&IdType=ASIN&ItemId=".$ItemId."&AssociateTag=ebooksprices-20&AWSAccessKeyId=".$AWSAccessKeyId."&Timestamp=".urlencode($Timestamp)."&Signature=".$str;
echo "<br />";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
var_dump($result);
But with no success, I get this output-
2016-07-14T09:50:06Z string(427) " SignatureDoesNotMatchThe request
signature we calculated does not match the signature you provided.
Check your AWS Secret Access Key and signing method. Consult the
service documentation for
details.34b23224-4750-46c7-8f75-929239f955de"
Any help will be appreciated.
Thanks
Finally I got time to post my working code-
$ItemId = $_GET['isbn'];
$ResponseGroup = 'Offers';
//$Timestamp = gmdate("Y-M-DTh:m:sZ");
//date_default_timezone_set('America/Los_Angeles');
$Timestamp = gmdate("Y-m-d\TH:i:s\Z");
$AWSAccessKeyId = "/your key/";
$AssociateTag = "/your-tag/";
$Version = "2013-08-01";
//echo $Timestamp;
//echo "<br />";
$str = "Service=AWSECommerceService&Operation=ItemLookup&ResponseGroup=".$ResponseGroup."&IdType=ASIN&ItemId=".urlencode($ItemId)."&AssociateTag=".$AssociateTag."&AWSAccessKeyId=".$AWSAccessKeyId."&Timestamp=".urlencode($Timestamp);
$ar = explode("&", $str);
//var_dump($ar);
natsort($ar);
//var_dump($ar);
$str = "GET
webservices.amazon.com
/onca/xml
";
$str .= implode("&", $ar);
//echo $str;
//echo "<br />";
$str = urlencode(base64_encode(hash_hmac("sha256",$str,'/your secret/',true)));
$url = "http://webservices.amazon.com/onca/xml?Service=AWSECommerceService&Operation=ItemLookup&ResponseGroup=Offers&IdType=ASIN&ItemId=".$ItemId."&AssociateTag=your-tag&AWSAccessKeyId=".$AWSAccessKeyId."&Timestamp=".urlencode($Timestamp)."&Signature=".$str;
//echo "<br />";
//echo $url;
//echo "<br />";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
//var_dump($result);
$xml=simplexml_load_string($result) or die("Error: Cannot create object");
echo "<h1>AMAZON API</h1><pre>";
print_r($xml);
This code returns the response in XML format.
Thanks
The AWS SDK's does currently not support the Amazon Product Advertising API.
For implementation there's a PHP code example provided by Amazon on this page: Implementing a Product Advertising API Request
For the request signature, follow this documentation: http://docs.aws.amazon.com/AWSECommerceService/latest/DG/rest-signature.html. More specific details on a PHP implementation of the request signing has been answer here before: Amazon Product API returns “SignatureDoesNotMatch”
Related
I want to develop a bridging application to web service. I Tried using the encrypted TIMESTAMP, SIGNATURE, AND AUTHORIZATION code with ARC (google add on for web service) to test if my encryption codes are correct and it worked. In my php script All requirements (parameters) are already provided but I always get Unauthorized access even though the password and username are correct. Please help. i'm using php curl. Thank for your help.
this is my php script :
<?php
$data = "xxx";
$secretKey = "xxx";
$url = "http://someurl";
$nik = "xxx";
date_default_timezone_set('UTC');
$tStamp = strval(time()-strtotime('1970-01-01 00:00:00'));
$signature = hash_hmac('sha256', $data."&".$tStamp, $secretKey, true);
$encodedSignature = base64_encode($signature);
$urlencodedSignature = urlencode($encodedSignature);
$pcareUname = "zzz";
$pcarePWD = "zzz";
$kdAplikasi = "zzz";
$encodedAuthorization = base64_encode($pcareUname.":".$pcarePWD.":".$kdAplikasi);
//showing result from encode
echo "X-cons-id: " .$data;
echo "X-timestamp:" .$tStamp;
echo "X-signature: " .$encodedSignature;
echo "X-authorization: " .$encodedAuthorization";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url.$nik);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"X-cons-id: $data",
"X-timestamp: $tStamp",
"X-signature: $signature",
"X-authorization: Basic $encodedAuthorization"
));
$result = curl_exec($ch);
curl_close($ch);
echo($result);
?>
I am using Fat Secret API in my project and want to find the food names on search so I hard coded the food name say : banana and it is giving me error
8 Invalid signature: oauth_signature 'NECnoAOp6D2qLCg7YQ84fYyJYRE='
Below is my code
$consumer_key = "bcd69xxxxxxxxxxxxxxxxxxxxxxx52";
$secret_key = "62fe9xxxxxxxxxxxxxxxxxxxxxxxx54d";
$base = rawurlencode("GET")."&";
$base .= "http%3A%2F%2Fplatform.fatsecret.com%2Frest%2Fserver.api&";
$params = "format=json&";
$params = "method=foods.search&";
$params .= "oauth_consumer_key=$consumer_key&";
$params .= "oauth_nonce=".uniqid()."&";
$params .= "oauth_signature_method=HMAC-SHA1&";
$params .= "oauth_timestamp=".time()."&";
$params .= "oauth_version=1.0&";
$params .= "search_expression=banana";
$params .= "oauth_callback=oob";
$params2 = rawurlencode($params);
$base .= $params2;
//encrypt it!
$sig= base64_encode(hash_hmac('sha1', $base, "62fe9d66898545a0b48d497a4394054d&", true));
$url = "http://platform.fatsecret.com/rest/server.api?".$params."&oauth_signature=".rawurlencode($sig);
//$food_feed = file_get_contents($url);
list($output,$error,$info) = loadFoods($url);
echo '<pre>';
if($error == 0){
if($info['http_code'] == '200'){
echo $output;
} else {
die('Status INFO : '.$info['http_code']);
}
}else{
die('Status ERROR : '.$error);
}
function loadFoods($url)
{
// create curl resource
$ch = curl_init();
// set url
curl_setopt($ch, CURLOPT_URL, $url);
//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// $output contains the output string
$output = curl_exec($ch);
$error = curl_error($ch);
$info = curl_getinfo($ch);
// close curl resource to free up system resources
curl_close($ch);
return array($output,$error,$info);
}
Please Help me in this. I am new in OAuth and Fat Secret API, Please do share the necessary information if you know.
Thanks
I am trying to get Product Reviews from Amazon but getting this error ,
The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.
Below is my code ,
define('AMAZON_URL','http://webservices.amazon.com/onca/xml?');
define('AMAZON_ACCESS_KEY',--access_key--);
define('AMAZON_SECRET_KEY',--secret_key--);
define('AMAZON_ASSOCIATE_TAG',--tag--);
$dr['model_no'] = --model_no--;
$dr['manufacturer'] = --manufacturer--;
//get amazon data
$timestamp = gmdate("Y-m-d\TH:i:s\Z");//rawurlencode(gmdate("Y-m-d\TH:i:s\Z"));
$url = "AWSAccessKeyId=".AMAZON_ACCESS_KEY;
$url .= "&AssociateTag=".AMAZON_ASSOCIATE_TAG;
$url .= "&IncludeReviewsSummary=True";
$url .= '&Keywords='.$dr['model_no'];
$url .= "&Manufacturer=".$dr['manufacturer'];
$url .= "&Operation=ItemSearch";
$url .= "&ResponseGroup=Reviews";
$url .= "&ReviewSort=HelpfulVotes";
$url .= "&SearchIndex=Electronics";
$url .= "&Service=AWSECommerceService";
$url .= "&Timestamp=".$timestamp;
$url .= "&Version=2013-05-31";
$prepend = "GET\nwebservices.amazon.com\n/onca/xml\n";
$prepend_string = $prepend . $url;
$signature = base64_encode(hash_hmac("sha256", $prepend_string, AMAZON_SECRET_KEY, True));
$signature = str_replace("+", "%2B", $signature);
$signature = str_replace("=", "%3D", $signature);
// $signature = base64_encode(hash_hmac("sha256", $prepend_string, AMAZON_SECRET_KEY, True));
$url = $url.'&Signature=' .$signature;
// $url = $url.'&Signature=' .rawurlencode($signature);
echo "$url\n";
$result = $this->data_api->call_amazon($url);
My call_amazon function is
public function call_amazon($url)
{
$url = AMAZON_URL.$url;
//initialize curl
echo "Caalling url: \n" . $url . "\n";
$ch = curl_init();
//initilize url to set which servvice to call
curl_setopt($ch, CURLOPT_URL, $url);
//to tell curl that post method is used
//tell that retrun value as string
curl_setopt($ch, CURLOPT_RETURNTRANSFER , 1);
//execute service now
$result = curl_exec($ch);
if(empty($result) || $result===FALSE){
return '<customError>
<status>400</status>
<response>false</response>
</customError>';
} else {
echo "$result \n";
//return response
return $result;
}
}
I had checked the docs and examples and signature looks ok to me. Any suggestions?
I'm trying to retrieve data from Twitter by connecting to twitter API and make some requests the my code below but I get nothing in return... I just requested the bearer token and successfully received it.
This is the code in PHP:
$url = "https://api.twitter.com/1.1/statuses/user_timeline.json?
count=10&screen_name=twitterapi";
$headers = array(
"GET".$url." HTTP/1.1",
"Host: api.twitter.com",
"User-Agent: My Twitter App v1.0.23",
"Authorization: Bearer ".$bearer_token."",
"Content-Type: application/x-www-form-urlencoded;charset=UTF-8",
);
$ch = curl_init(); // setup a curl
curl_setopt($ch, CURLOPT_URL,$url); // set url to send to
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); // set custom headers
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // return output
$retrievedhtml = curl_exec ($ch); // execute the curl
print_r($retrievedhtml);
when using the print_r nothing is shown at all and when using the var_dump i find "bool(false)"
Any idea with what could be wrong with this?
Regards,
Try outputting any potential cURL errors with
curl_error($ch);
after the curl_exec command. That might give you a clue about what's going wrong. Completely empty responses usually point to something going wrong with the cURL operation itself.
Your headers are wrong... do not include
"GET".$url." HTTP/1.1"
in your headers.
Further, you may print out the HTTP return code by
$info = curl_getinfo($ch);
echo $info["http_code"];
200 is success, anything in the 4xx or 5xx range means something went wrong.
I built based on comments I found in a Twitter dev discussion by #kiers. Hope this helps!
<?php
// Get Token
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, 'https://api.twitter.com/oauth2/token');
curl_setopt($ch,CURLOPT_POST, true);
$data = array();
$data['grant_type'] = "client_credentials";
curl_setopt($ch,CURLOPT_POSTFIELDS, $data);
$screen_name = 'ScreenName'; // add screen name here
$count = 'HowManyTweets'; // add number of tweets here
$consumerKey = 'EnterYourTwitterAppKey'; //add your app key
$consumerSecret = 'EnterYourTwitterAppSecret'; //add your app secret
curl_setopt($ch,CURLOPT_USERPWD, $consumerKey . ':' . $consumerSecret);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
$bearer_token = json_decode($result);
$bearer = $bearer_token->{'access_token'}; // this is your app token
// Get Tweets
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, 'https://api.twitter.com/1.1/statuses/user_timeline.json?count='.$count.'&screen_name='.$screen_name);
curl_setopt($ch,CURLOPT_HTTPHEADER,array('Authorization: Bearer ' . $bearer));
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
$cleanresults = json_decode($result);
// Release the Kraken!
echo '<ul id="twitter_update_list">';
foreach ( $cleanresults as $tweet ) {
// Set up some variables
$tweet_url = 'http://twitter.com/'.$screen_name.'/statuses/'.$tweet->id_str; // tweet url
$urls = $tweet->entities->urls; // links
$retweet = $tweet->retweeted_status->user->screen_name; // there is a retweeted user
$time = new DateTime($tweet->created_at); // lets grab the date
$date = date_format($time, 'M j, g:ia'); // and format it accordingly
$url_find = array();
$url_links = array();
if ( $urls ) {
if ( !is_array( $urls ) ) {
$urls = array();
}
foreach ( $urls as $url ) {
$theurl = $url->url;
if ( $theurl ) {
$url_block = ''.$theurl.'';
$url_find[] = $theurl; // make array of urls
$url_links[] = $url_block; // make array of replacement link blocks for urls in text
}
}
}
if ( $retweet ) { // add a class for retweets
$link_class = ' class="retweet"';
} else {
$link_class = '';
}
echo '<li'.$link_class.'>';
$new_text = preg_replace('##([\\d\\w]+)#', '$0', $tweet->text); // replace all #mentions with actual links
$newer_text = preg_replace('/#([\\d\\w]+)/', '$0', $new_text); // replace all #tags with actual links
$text = str_replace( $url_find, $url_links, $newer_text); // replace all links with actual links
echo $text;
echo '<br /><a class="twt-date" href="'.$tweet_url.'" target="_blank">'.$date.'</a>'; // format the date above
echo '</li>';
}
echo '</ul>';
I put together some files on github, named "Flip the Bird." Hope this helps...
I created PHP library supporting application-only authentication and single-user OAuth. https://github.com/vojant/Twitter-php.
Usage
$twitter = new \TwitterPhp\RestApi($consumerKey,$consumerSecret);
$connection = $twitter->connectAsApplication();
$data = $connection->get('/statuses/user_timeline',array('screen_name' => 'TechCrunch'));
I have a twitter api php script successfully spits out the last 100 of my followers
$flwrs_url = "http://api.twitter.com/1/statuses/followers/exampleuser.json";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $flwrs_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$curlout = curl_exec($ch);
curl_close($ch);
$response = json_decode($curlout, true);
foreach($response as $friends){
$id = $friends['id'];
$screen_name = $friends['screen_name'];
....
(I used exampleuser instead of my own account)
How do I extend this to include more or all of my followers?
Thank you
According to the Twitter API Documentation for GET followers/ids the request should return up to 5000 followers.
However, if not all followers are returned by the API, there should be a next_cursor element in the response which can be used to retrieve the next batch of followers. You only have to append the value of next_cursor as cursor to the request (see also the API documentation).
Please note that you are using Version 1 of the Twitter API which has been deprecated recently. That is, it will stop working probably early next year. You should upgrade to Version 1.1 as soon as possible. There are new guidelines in place, one of them is that all requests must be authenticated with oAuth.
Thanks for the answer Florian. BTW stumbing around I think I found the correct way to do what I was looking for. Correct me if I'm wrong.
after using the:
$code=$tmhOAuth->request('GET', $tmhOAuth->url('1/followers/ids'),
array('screen_name' => $user, 'cursor' => $cursor));
technique to grab all 5000 followers (user ids). I use the following code to grab batches of 100 (user details) at a time:
$status_url = "http://api.twitter.com/1/users/lookup.json?user_id=";
$lastNum=$last; // $lastNum=100;
$i=$first; // $i=0;
while($i<$lastNum){
if ($i==($lastNum-1)){
$status_url = $status_url . "$followers[$i]";
}else{
$status_url = $status_url . "$followers[$i],";
}
$i++;
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $status_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$curlout = curl_exec($ch);
curl_close($ch);
$response = json_decode($curlout, true);
$i = 0;
foreach($response as $friends){
$id = $friends['id'];
$screen_name = $friends['screen_name'];
$name = $friends['name'];
$thumb = $friends['profile_image_url'];
$url = $friends['screen_name'];
$location = $friends['location'];
$description = $friends['description'];
echo "$i) $id $screen_name $name $location $description<br />";
$i++;
}
I realize I need to put "sleep" in between each of these "batches of 100", but I'm not quite sure how much to use.