FatSecret API - food.get method invalid signature - api

Hi I am new to FatSecret Platform API and i developed a PHP script to access food details using foods.search method Here is the foods.search method Api call example,used Curl and works perfect. <?php $consumer_key = "xxxxxxx"; $secret_key = "xxxxxxx"; //Signature Base String //<HTTP Method>&<Request URL>&<Normalized Parameters> $base = rawurlencode("GET")."&"; $base .= "http%3A%2F%2Fplatform.fatsecret.com%2Frest%2Fserver. api&"; //sort params by abc....necessary to build a correct unique signature $params = "method=foods.search&"; $params .= "oauth_consumer_key=$consumer_key&"; // ur consumer key $params .= "oauth_nonce=123&"; $params .= "oauth_signature_method=HMAC-SHA1&"; $params .= "oauth_timestamp=".time()."&"; $params .= "oauth_version=1.0&"; $params .= "search_expression=".urlencode($_GET['pasVar']); $params2 = rawurlencode($params); $base .= $params2; //encrypt it! $sig= base64_encode(hash_hmac('sha1', $base, "$secret_key&", true)); // replace xxx with Consumer Secret //now get the search results and write them down $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); } ?> the above script working perfect and retrieves food details using search method.But when i use food.get method to retrieve data using food_id it says invalid signature error,Here's the food.get method api call example,I have given correct keys and passed food_id parameter.Can someone help me to solve the issue,I am really struck on this code.It says invalid signature error. <?php $consumer_key = "xxxxxxxxx"; $secret_key = "xxxxxxxxxx"; //Signature Base String //<HTTP Method>&<Request URL>&<Normalized Parameters> $base = rawurlencode("GET")."&"; $base .= "http%3A%2F%2Fplatform.fatsecret.com%2Frest%2Fserver.api&"; //sort params by abc....necessary to build a correct unique signature $params = "method=food.get&"; $params .= "oauth_consumer_key=$consumer_key&"; // ur consumer key $params .= "oauth_nonce=".rand()."&"; $params .= "oauth_signature_method=HMAC-SHA1&"; $params .= "oauth_timestamp=".time()."&"; $params .= "oauth_version=1.0&"; $params .= "food_id=".urlencode($_GET['pasVar']); $params2 = rawurlencode($params); $base .= $params2; //encrypt it! $sig= base64_encode(hash_hmac('sha1', $base, "$secret_key&", true)); // replace xxx with Consumer Secret //now get the search results and write them down $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); } ?> Help me what's the error in the code and help me to solve the issue as i have to use this API in my project Thanks waiting for your replies....

You should order you params by alpha.
So you should do it in this order:
$params = "food_id=".urlencode($_GET['pasVar'])."&";
$params .= "method=food.get&";
$params .= "oauth_consumer_key=$consumer_key&"; // ur consumer key
$params .= "oauth_nonce=".rand()."&";
$params .= "oauth_signature_method=HMAC-SHA1&";
$params .= "oauth_timestamp=".time()."&";
$params .= "oauth_version=1.0";

Related

Hello am trying to make an API post request using php curl error code 32601

am new in api trying to see if my Api works once I execute the code am geting Error code 32601 'Method not found' I have gone through the code and though am not sure I think the error is syntax related any guidance will be appreciated
<?php
$key = '';
$secret = '';
$path = 'https://api.cloudtrax.com/voucher/network_id=254281';
$data = array(
"code"=> "b3c34test",
"duration"=> 1,
"max_users"=> 1,
"up_limit"=> 10,
"down_limit"=> 20,
"comment"=> "Free access for guests",
"purge_days"=> 2);
$headers = array(
'nonce' => 'ThisIsANonce',
'authorization' => "key=" . $key . ",timestamp=" . time() . ",nonce=" . $nonce,
'authorization_header' => "Authorization: " . $authorization,
'signature' => hash_hmac('sha256', $authorization . $path . $data, $secret),
);
$ch = curl_init($path);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$result = curl_exec($ch);
if ($result == FALSE) {
if (curl_errno($ch) == 0)
echo "#### NOTE ####: nil HTTP return: This API call appears to be broken" . "\n";
else
throw new Exception(curl_error($ch), curl_errno($ch)); }
else
echo "RESULT: \n" . $result . "\n";
?>

return error code : 401, No license found for the given deviceId

i have use this api
curl -X POST
https://tracking.api.here.com/v2/token
-H 'Authorization: Bearer {signedRequest}'
my php code is
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://tracking.api.here.com/v2/timestamp');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
$result = json_decode($result);
curl_close($ch);
$timestamp = ($result->timestamp);
$accessKey = $deviceId;
$secret = $deviceSecret;
$url = "https://account.api.here.com/oauth2/token";
$nonce = mt_rand(100000,999999);
$timestamp = $timestamp;
$baseString = "grant_type=client_credentials&oauth_consumer_key=".$accessKey."&oauth_nonce=".$nonce."&oauth_signature_method=HMAC-SHA256&oauth_timestamp=".$timestamp."&oauth_version=1.0";
$workingString = array();
foreach (explode('&', $baseString) as $parameter) {
$parameter = explode('=', $parameter);
$workingString[] = urlencode($parameter[0]).'='.trim(urlencode($parameter[1]));
}
$urlEncodeParamaterString = implode('&', $workingString);
$fullBaseString = "POST&".urlencode($url)."&".urlencode($urlEncodeParamaterString);
$hashKey = $secret.'&';
function encode($data) {
return str_replace(['+', '/'], ['-', '_'], base64_encode($data));
}
function decode($data) {
return base64_decode(str_replace(['-', '_'], ['+', '/'], $data));
}
$binaryKey = decode($hashKey);
$signature = encode(hash_hmac("sha256", $fullBaseString, $binaryKey, true));
$authHeader = "OAuth oauth_consumer_key=".$accessKey.",oauth_signature_method='HMAC-SHA256',oauth_timestamp='".$timestamp."',oauth_nonce=".$nonce.",oauth_version='1.0',oauth_signature=".$signature."";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://tracking.api.here.com/v2/token');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
$headers = array();
$headers[] = 'Content-Type: application/x-www-form-urlencoded';
$headers[] = 'Authorization: '.$authHeader;
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close($ch);
echo '';
print_r($result);
output
{
code: 401,
id: "312f56e5-db4f-40f5-807f-c5a0413dd668",
message: "No license found for the given deviceId.",
error: "Timestamp wrong When the request timestamp has a more than 10 second difference from the server time, the x-here-timestamp header with the current server timestamp is added to the response. Incorrect Signature If the OAuth signature is incorrect, the response will be a 401 but without the x-here-timestamp field. "
}
In order to tracking a Device using HERE Tracking Service all you'll need to login and Create your Device ID First.
Please see below getting start documentation.
https://developer.here.com/documentation/tracking/dev_guide/topics/getting-started-1-creating-a-device-licence.html

How to use pagination at api localbitcoin

I'm developing with localbitcoin API and i am using path “/api/dashboard/closed/” and this is my code:
<?php
function localbitcoinsquery($path, $nonce,array $req = Array()) {
global $random;
$key='mykey';
$secret='secretkey';
if ($req) {
$get=httpbuildquery($req);
$path=$path.'?'.$get;
}
$postdata=$nonce.$key.$path;
$sign = strtoupper(hashhmac('sha256', $postdata, $secret));
$headers = array(
'Apiauth-Signature:'.$sign,
'Apiauth-Key:'.$key,
'Apiauth-Nonce:'.$nonce
);
$ch = null;
$ch = curlinit('https://localbitcoins.com'.$path);
curlsetopt($ch, CURLOPTRETURNTRANSFER, true);
curlsetopt($ch, CURLOPTHTTPHEADER, $headers);
curlsetopt($ch, CURLOPTSSLVERIFYPEER, TRUE);
curlsetopt($ch, CURLOPTCONNECTTIMEOUT, 20);
$res = curlexec($ch);
if ($res === false) throw new Exception('Curl error: '.curlerror($ch));
$dec = jsondecode($res, true);
if (!$dec) throw new Exception('Invalid data: '.$res);
curl_close($ch);
return $dec;
}
$getinfo = array();
$url='/api/dashboard/closed/';
$mt = explode(' ', microtime());
$random = $mt[1].substr($mt[0], 2, 6);
$getinfo = localbitcoinsquery($url,$random);
echo "<pre>";
printr($getinfo);
echo "</pre>";
?>
This works OK, but show only 50 trades,
Also I get this at result:
[pagination] => Array
(
[next] => https://localbitcoins.com/api/dashboard/closed/?order_by=-closed_at&start_at=2017-10-26+17%3U50%3A49%2B00%9A00
)
But I don't know how to use pagination, when I try to use this link at my code I get error:
[message] => HMAC authentication key and signature was given, but they
are invalid. Error 41
I already investigated at google large time but the information is scarce.
I'm using the python library and had the same issue. When I spoke to technical support they said the issue was in the way I was calculating the authentication.
Basically you have to include the pagination url as part of the signature.
On the python library at least, you do not have to change the api endpoint since arguments are being delivered as part of the form data.
So you still access for example "/api/dashboard/closed/" when getting the second page and the "?order_by=-closed_at&start_at=2017-10-26+17%3U50%3A49%2B00%9A00" stuff goes in the form somehow.
The python API does all this for you, you just have to copy the example from the github page.
I fixed error no. 41. I modified your example to show that works, (read my NOTE: comments to understand better where is the problem) Read my NOTE: comments.
<?php
function localbitcoins_query($path, array $req = Array()) {
$key='yourkey';
$secret='yoursecret';
$array_mt = explode(' ', microtime());
$nonce = $array_mt[1].substr($array_mt[0], 2, 6);
$get = "";
if ($req) {
$get=http_build_query($req);
}
$postdata=$nonce.$key.$path.$get; // NOTE: here $postdata goes without '?' char before the parameters!
$sign = strtoupper(hash_hmac('sha256', $postdata, $secret));
$headers = array(
'Apiauth-Signature:'.$sign,
'Apiauth-Key:'.$key,
'Apiauth-Nonce:'.$nonce
);
$ch = null;
$ch = curl_init('https://localbitcoins.com'.$path.( $get=="" ? "" : "?".$get)); // NOTE: here it's necesary '?' char before the parameters!
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, TRUE);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20);
$res = curl_exec($ch);
if ($res === false) throw new Exception('Curl error: '.curlerror($ch));
$dec = json_decode($res, true);
if (!$dec) throw new Exception('Invalid data: '.$res);
curl_close($ch);
return $dec;
}
$getinfo = array();
$api_endpoint = '/api/dashboard/closed/';
$array_params = array( "order_by" => "-closed_at"
, "start_at" => "2019-08-14 18:00:26+00:00"
);
$getinfo = localbitcoins_query($api_endpoint,$array_params);
echo "<pre>"; print_r($getinfo); echo "</pre>";
?

How to generate QuickBlox authentication signature in PHP?

I want to access the APIs in QuickBlox, but before that we need to authenticate our apps and get a session token, and using session token we can access the other APIs.
But the problem is, when I send the authentication request using the required specification given on the QuickBloxwebsite, I am getting the error message:
{"errors":{"base":["Unexpected signature"]}}
The parameters to generate the signature is:
application_id=22&auth_key=wJHd4cQSxpQGWx5&nonce=33432&timestamp=1326966962
And then we convert it in HMAC-SHA format:
hash_hmac( 'sha1', $signatureStr , $authSecret);
Please help me to resolve this problem.
I wrote code snippet on php, it generates signature. It works good
this is my test application's credentials:
$application_id = 92;
$auth_key = "wJHdOcQSxXQGWx5";
$authSecret = "BTFsj7Rtt27DAmT";
$nonce = rand();
echo "<br>nonce: " . $nonce;
$timestamp = time();
echo "<br>timestamp: " . $timestamp ."<br>";
$stringForSignature = "application_id=".$application_id."&auth_key=".$auth_key."&nonce=".$nonce."&timestamp=".$timestamp;
echo $stringForSignature."<br>";
$signature = hash_hmac( 'sha1', $stringForSignature , $authSecret);
echo $signature;
hope this help
Problem solved
There was a problem in my request parameters.
$params = "application_id=$application_id&auth_key=$auth_key&timestamp=$timestamp&nonce=$nonce&signature=$signature&**auth_secret=$authSecret**";
In this parameter I was passing an extra parameter, my auth secret key which should not be there. I removed this parameter and now its working.
Here is full example how to create QuickBlox session:
<?php
// Application credentials
DEFINE('APPLICATION_ID', 92);
DEFINE('AUTH_KEY', "wJHdOcQSxXQGWx5");
DEFINE('AUTH_SECRET', "BTFsj7Rtt27DAmT");
// User credentials
DEFINE('USER_LOGIN', "emma");
DEFINE('USER_PASSWORD', "emma");
// Quickblox endpoints
DEFINE('QB_API_ENDPOINT', "https://api.quickblox.com");
DEFINE('QB_PATH_SESSION', "session.json");
// Generate signature
$nonce = rand();
$timestamp = time(); // time() method must return current timestamp in UTC but seems like hi is return timestamp in current time zone
$signature_string = "application_id=".APPLICATION_ID."&auth_key=".AUTH_KEY."&nonce=".$nonce."&timestamp=".$timestamp."&user[login]=".USER_LOGIN."&user[password]=".USER_PASSWORD;
echo "stringForSignature: " . $signature_string . "<br><br>";
$signature = hash_hmac('sha1', $signature_string , AUTH_SECRET);
// Build post body
$post_body = http_build_query(array(
'application_id' => APPLICATION_ID,
'auth_key' => AUTH_KEY,
'timestamp' => $timestamp,
'nonce' => $nonce,
'signature' => $signature,
'user[login]' => USER_LOGIN,
'user[password]' => USER_PASSWORD
));
// $post_body = "application_id=" . APPLICATION_ID . "&auth_key=" . AUTH_KEY . "&timestamp=" . $timestamp . "&nonce=" . $nonce . "&signature=" . $signature . "&user[login]=" . USER_LOGIN . "&user[password]=" . USER_PASSWORD;
echo "postBody: " . $post_body . "<br><br>";
// Configure cURL
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, QB_API_ENDPOINT . '/' . QB_PATH_SESSION); // Full path is - https://api.quickblox.com/session.json
curl_setopt($curl, CURLOPT_POST, true); // Use POST
curl_setopt($curl, CURLOPT_POSTFIELDS, $post_body); // Setup post body
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // Receive server response
// Execute request and read responce
$responce = curl_exec($curl);
// Check errors
if ($responce) {
echo $responce . "\n";
} else {
$error = curl_error($curl). '(' .curl_errno($curl). ')';
echo $error . "\n";
}
// Close connection
curl_close($curl);
?>
You have to use your own application parameters:
application_id
auth_key
and random 'nonce' and current timestamp (not from example, you can get current timestamp on this site http://www.unixtimestamp.com/index.php)
Your code is right, but you must set proper parameters
1) You should send request to correct url.
to
https://api.quickblox.com/auth.json
instead
https://api.quickblox.com/session.json
2) You should fix SSL problem using this.
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false)
We use php, and next code works well for us:
<?php
$userLogin = '{YOUR_QB_USER}';
$userPassword = '{YOUR_QB_PASSWORD}';
$body = [
'application_id' => '{YOUR_QB_APPLICATION_ID}',
'auth_key' => '{YOUR_QB_AUTH_KEY}',
'nonce' => time(),
'timestamp' => time(),
'user' => ['login' => $userLogin, 'password' => $userPassword]
];
$built_query = urldecode(http_build_query($body));
$signature = hash_hmac('sha1', $built_query , '{YOUR_QB_APP_SECRET}');
$body['signature'] = $signature;
$post_body = http_build_query($body);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'https://{YOUR_QB_HOST}/session.json');
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $post_body);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($curl);
$token = json_decode($response, true)['session']['token'];
printf('Your token is: %s %s', $token, PHP_EOL);

Facebook API call- "This API version is deprecated"

I'm trying to call to Photo.upload on the the Facebook API server. As far as I can tell the code to construct the call is good but I can't understand the responce I'm getting back from the server. As far as I can see, this call is ment to work and other people don't get this problem. I can only reason that something is wrong with the code. The commented stuff is an artifact of me trying different things to get a different responce from the server. The original code that I've changed was in part taken from an example of how to do this which I couldn't get to work either really:
http://www.jaisenmathai.com/blog/2008/11/27/using-the-facebook-api-to-upload-photos/
Server Responce:
12 This API version is deprecated method photos.upload api_key b92cee19a33c861275bfce4695896e44 call_id 1250194789.61 garden_jpg /var/www/vivaladan/pictureyourselfhull/garden.jpg v 0 sig 896ee95339cad24ce7e64a05ca764123
Code:
$key = b92cee19a33c861275bfce4695896e44;
$ver = 1.0;
$cid = microtime(true);
$uid = BIGINT;
$file= "garden.jpg";
$args = array(
//amethod => photos.upload,
v => $ver,
api_key => $key,
//uid => $uid,
call_id => $cid,
//format => XML
);
$args[basename($file)] = realpath($file);
signRequest($args,$sec);
$postString = "";
foreach($args as $index => $value) {
$postString .= $index ."=".$value."&";
}
$postString = trim($postString, '&');
$ch = curl_init();
$url = "http://api.facebook.com/restserver.php?method=photos.upload";
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postString);
$data = curl_exec($ch);
echo $data;
function signRequest(&$args, $secret){
ksort($args);
$sig = "";
foreach($args as $k => $v){
$sig .= $k . '=' . $v;
}
$sig .= $secret;
$args[sig] = md5($sig);
}
Rest API call is not working anymore.
Try GraphApi
I'm guessing it's because you're using $ver = 0.0; - there's no 0.0 version of the API.
try using api.new.facebook.com API URL instead