I'm not an expert in API development or using signed messages in PHP.
I have however tried to get the GATE.IO v4 API working in my PHP implementation but keep getting "Signature mismatch". I have followed the API documentation for CREATE ORDER available at Gate.io's website here: https://www.gate.tv/docs/developers/apiv4/#create-an-order
I have managed to get the /spot/accounts working, so I know that the key and secret are correct.
Based on the code below I seem to missing something. Probably a tiny error but those are the hardest, right?
Does anyone have any idea what could be the cause of this issue? Would really appreciate your help after having spent 8+ hours trying to get this to work.
<?php
$accessToken = ''; // Access token for OAuth/Bearer authentication
$key = "XXXXXXXXXXXXXXXXXXXXXXX";
$secret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
$username = ''; // Username for HTTP basic authentication
$password = ''; // Password for HTTP basic authentication
$host = 'https://api.gateio.ws/api/v4'; // The host
$userAgent = 'OpenAPI-Generator/5.26.0/PHP'; // User agent of the HTTP request, set to "OpenAPI-Generator/{version}/PHP" by default
$sResourcePath = "/spot/orders";
$sMethod = "POST"; // POST or GET
$aPayload['currency_pair'] = "DOT_USDT";
$aPayload['price'] = "6.330033";
$aPayload['account'] = "spot";
$aPayload['side'] = "buy";
$aPayload['amount'] = "1";
$aPayload['time_in_force'] = "gtc";
$sBody = json_encode($aPayload);
$aQueryParams = $aPayload;
$aFullPath = parse_url($host . $sResourcePath);
$fullPath = $aFullPath['path'];
$timestamp = time();
$hashedPayload = hash("sha512", ($payload !== null) ? $payload : "");
$fmt = "%s\n%s\n%s\n%s\n%s";
$sQuery = http_build_query($aQueryParams, false);
$signatureString = sprintf($fmt, $sMethod, $fullPath, $sQuery, $hashedPayload, $timestamp);
$signature = hash_hmac("sha512", $signatureString, $secret);
$aSignHeaders = array(
"KEY" => $key,
"SIGN" => $signature,
"Timestamp" => $timestamp);
$aHeaders[] = "KEY: " . $aSignHeaders['KEY'];
$aHeaders[] = "SIGN: " . $aSignHeaders['SIGN'];
$aHeaders[] = "Timestamp: " . $aSignHeaders['Timestamp'];
$aExtraParams['sHttpHeaders'] = $aHeaders;
if ($sMethod == "POST")
{
$sParams = "?" . http_build_query($aQueryParams, false);
}
else
{
$sQuery = "";
}
$sSubmitUrl = $host . $sResourcePath . $sParams;
$sPage = CURL::doRequest($sMethod, $sSubmitUrl, $sParams, $aExtraParams);
$aPage = json_decode($sPage, true);
if ($aPage)
{
$iPage = count($aPage);
}
echo "<pre>";
print_r($aPage);
echo "</pre>";
?>
based on that example request, you should be doing something like this
//path & urls
$host = 'https://api.gateio.ws';
$prefix = '/api/v4';
$path = '/spot/orders';
$fullPath = "$prefix$path";
$method = 'POST';
//your API keys
$api = [
'secret' => 'xxxx'
];
// Your actual data you can easily modify
$payload = [
'currency_pair' => 'DOT_USDT',
'price' => '6.330033',
'account' => 'spot',
'side' => 'buy',
'amount' => '1',
'time_in_force' => 'gtc'
];
//Convert your data to JSON FORMAT
$jsonPayload = json_encode( $payload );
//Hash your JSON DATA
$hashJsonPayload = hash('sha512', $jsonPayload);
$timeStamp = time();
// dunno if this is required
$queryParam = '';
//Create your signature string
$signString="$method\n$fullPath\n$queryParam\n$hashJsonPayload\n$timeStamp";
//Generate the signature
$signHash = hash_hmac('sha512', $signString, $api['secret']);
// Your Actual headers
$headers = [
'Content-Type: application/json',
'Timestamp: '.$timeStamp,
'Key: '.$api['secret'],
'SIGN: '.$signHash
];
Example request using php curl
$ch = curl_init( "$host$fullPath" ); // URL to POST https://api.gateio.ws/api/v4/spot/orders
curl_setopt( $ch, CURLOPT_POSTFIELDS, $jsonPayload ); // set json payload as body here
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers ); //define header here
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
$result = curl_exec($ch);
curl_close($ch)
echo '<pre>', print_r($result, 1), '</pre>';
Related
I'm calling the API to get a list of shipments but I can't seem to page through the results.
The API call is successful with only one query parameter but when I call it with two query parameters, I get the error "The signature is invalid. Verify and try again". I'm including my test code below.
<?php
function sign($method, $url, $data, $consumerSecret, $tokenSecret)
{
$url = urlEncodeAsZend($url);
$data = urlEncodeAsZend(http_build_query($data, '', '&'));
$data = implode('&', [$method, $url, $data]);
$secret = implode('&', [$consumerSecret, $tokenSecret]);
return base64_encode(hash_hmac('sha1', $data, $secret, true));
}
function urlEncodeAsZend($value)
{
$encoded = rawurlencode($value);
$encoded = str_replace('%7E', '~', $encoded);
return $encoded;
}
// REPLACE WITH YOUR ACTUAL DATA OBTAINED WHILE CREATING NEW INTEGRATION
$consumerKey = 'htj8ze6ntr0mz1s4hjxrqeicia8rxgt4';
$consumerSecret = 'djjzdwfgbbr7ganlkv01qr6p3l7ptvfe';
$accessToken = '60o0mfrvqnjvin7tjuqsv37arijrqe9e';
$accessTokenSecret = 'caq9wfdx99zaygwgbhw91i9imj89p4zb';
$method = 'GET';
/* test 1 PASS */
//$url = 'http://localhost/rest/V1/shipments/';
//$qs = ['searchCriteria'=>'all'];
/* test 2 PASS */
//$url = 'http://localhost/rest/V1/shipments/';
//$qs = ['searchCriteria[pageSize]'=>'10'];
/* test 3 FAIL "The signature is invalid. Verify and try again" */
$url = 'http://localhost/rest/V1/shipments/';
$qs = ['searchCriteria[pageSize]'=>'10', 'searchCriteria[currentPage]'=>'1'];
$data = [
'oauth_consumer_key' => $consumerKey,
'oauth_nonce' => md5(uniqid(rand(), true)),
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_timestamp' => time(),
'oauth_token' => $accessToken,
'oauth_version' => '1.0',
];
$data = array_merge($data, $qs);
$data['oauth_signature'] = sign($method, $url, $data, $consumerSecret, $accessTokenSecret);
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $url .'?' .http_build_query($qs),
CURLOPT_HTTPHEADER => [
'Authorization: OAuth ' . http_build_query($data, '', ',')
]
]);
$result = curl_exec($curl);
curl_close($curl);
echo($result);
The code includes three tests.
If I uncomment test 1 and comment test 2 and 3, the code works properly and I get a list of shipments.
If I uncomment test 2 and comment test 1 and 3, the code works properly and I get a list of shipments.
If I run the code as is, I get the the message "The signature is invalid. Verify and try again."
I'm running Magento ver. 2.3.2
The trick is to sort the parameters. I have some client code anyone is interested.
<?php
function sign($method, $url, $data, $consumerSecret, $tokenSecret)
{
$url = urlEncodeAsZend($url);
$data = urlEncodeAsZend(http_build_query($data, '', '&'));
$data = implode('&', [$method, $url, $data]);
$secret = implode('&', [$consumerSecret, $tokenSecret]);
return base64_encode(hash_hmac('sha1', $data, $secret, true));
}
function urlEncodeAsZend($value)
{
$encoded = rawurlencode($value);
$encoded = str_replace('%7E', '~', $encoded);
return $encoded;
}
function recursive_sort(&$array) {
foreach ($array as &$value) {
if (is_array($value)) recursive_sort($value);
}
return ksort($array);
}
// REPLACE WITH YOUR ACTUAL DATA OBTAINED WHILE CREATING NEW INTEGRATION
$consumerKey = 'htj8ze6ntr0mz1s4hjxrqeicia8rxgt4';
$consumerSecret = 'djjzdwfgbbr7ganlkv01qr6p3l7ptvfe';
$accessToken = '60o0mfrvqnjvin7tjuqsv37arijrqe9e';
$accessTokenSecret = 'caq9wfdx99zaygwgbhw91i9imj89p4zb';
$method = 'GET';
/* test 1 PASS */
//$url = 'http://localhost/rest/V1/shipments/';
//$qs = ['searchCriteria'=>'all'];
/* test 2 PASS */
//$url = 'http://localhost/rest/V1/shipments/';
//$qs = ['searchCriteria[pageSize]'=>'10'];
/* test 3 FAIL "The signature is invalid. Verify and try again" */
$url = 'http://localhost/rest/V1/shipments/';
$qs = ['searchCriteria'=>['pageSize'=>10,'currentPage'=>1]];
$data = [
'oauth_consumer_key' => $consumerKey,
'oauth_nonce' => md5(uniqid(rand(), true)),
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_timestamp' => time(),
'oauth_token' => $accessToken,
'oauth_version' => '1.0',
];
$data = array_merge($data, $qs);
recursive_sort($data);
$data['oauth_signature'] = sign($method, $url, $data, $consumerSecret, $accessTokenSecret);
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $url .'?' .http_build_query($qs),
CURLOPT_HTTPHEADER => [
'Authorization: OAuth ' . http_build_query($data, '', ',')
]
]);
$result = curl_exec($curl);
curl_close($curl);
echo($result);
Though this question is old, I want to post the answer for future cases.
The code in the question is good, and it helped me a lot.
It is needed to sort parameters by key. Also, please consider that the searchCriteria is a multidimensional array. So, the array must be sorted by key recursively.
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>";
?
Is it possible to build url to user's page, knowing his id?
I tried something like https://plus.google.com/u/0/ but it didn't work.
It's just https://plus.google.com/userId. With +Google for example: https://plus.google.com/116899029375914044550.
$userid = "116899029375914044550";
$url = "https://www.googleapis.com/plus/v1/people/".$userid."/";
$params = array(
'key' => 'YOURKEY'
);
$param_string = array();
foreach( $params as $key => $param ){
$param_string[] = $key.'='.urlencode(trim($param));
}
$url = $url.'?'.implode('&',$param_string);
$ch = curl_init( $url );
curl_setopt ( $ch , CURLOPT_RETURNTRANSFER , true );
$response = curl_exec($ch);
curl_close($ch);
$data = json_decode($response);
$url = $data->url;
echo $url;
After the update from API 1 to 1.1 my code doesn't show any results anymore.
On this forum I found a new code (below) for user_timeline results.
Change te link to https://api.twitter.com/1.1/search/tweets.json?q=test, results in the message: Could not authenticate you. What do I wrong?
function buildBaseString($baseURI, $method, $params) {
$r = array();
ksort($params);
foreach($params as $key=>$value){
$r[] = "$key=" . rawurlencode($value);
}
return $method."&" . rawurlencode($baseURI) . '&' . rawurlencode(implode('&', $r));
}
function buildAuthorizationHeader($oauth) {
$r = 'Authorization: OAuth ';
$values = array();
foreach($oauth as $key=>$value)
$values[] = "$key=\"" . rawurlencode($value) . "\"";
$r .= implode(', ', $values);
return $r;
}
$url = "https://api.twitter.com/1.1/statuses/user_timeline.json";
$oauth_access_token = "YOURVALUE";
$oauth_access_token_secret = "YOURVALUE";
$consumer_key = "YOURVALUE";
$consumer_secret = "YOURVALUE";
$oauth = array( 'oauth_consumer_key' => $consumer_key,
'oauth_nonce' => time(),
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_token' => $oauth_access_token,
'oauth_timestamp' => time(),
'oauth_version' => '1.0');
$base_info = buildBaseString($url, 'GET', $oauth);
$composite_key = rawurlencode($consumer_secret) . '&' . rawurlencode($oauth_access_token_secret);
$oauth_signature = base64_encode(hash_hmac('sha1', $base_info, $composite_key, true));
$oauth['oauth_signature'] = $oauth_signature;
// Make Requests
$header = array(buildAuthorizationHeader($oauth), 'Expect:');
$options = array( CURLOPT_HTTPHEADER => $header,
//CURLOPT_POSTFIELDS => $postfields,
CURLOPT_HEADER => false,
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false);
$feed = curl_init();
curl_setopt_array($feed, $options);
$json = curl_exec($feed);
curl_close($feed);
$twitter_data = json_decode($json);
You need to provide auth data. look at this page page. it says Authentication required. Using the OAuth tool, select your app and generate signature to properly call the resource.
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×tamp=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."×tamp=".$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×tamp=$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."×tamp=".$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 . "×tamp=" . $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);