Gate.io APIv4 AUTH request signature error - cryptocurrency

I struggle with Authentication request to gate.io apiv4
Reference:
https://www.gate.io/docs/apiv4/en/#api-signature-string-generation
I'm getting this response:
{"label":"INVALID_SIGNATURE","message":"Signature mismatch"}"
My code:
function signature($method, $url, $body, $timestamp) {
$body = is_array($body) ? json_encode($body) : $body;
$fullPath = parse_url($this->host, PHP_URL_PATH) . $url;
$fmt = "%s\n%s\n%s\n%s\n%s";
$hashedPayload = hash("sha512", $body);
$signatureString = sprintf(
$fmt,
$method,
$fullPath,
"",
$hashedPayload,
$timestamp
);
$signature = hash_hmac("sha512", $signatureString, $this->SECRET_KEY);
return $signature;
}
not sure where the error is, does anyone have similar issues?
Thank you

Related

Unexpected end of input error in react native

I get an error prompt SyntaxError: Unexpected end of input when I try to the message from API.
Here is my code:
.then((response) =>response.json())
.then((response)=>{
alert(response[0].Message);
})
.catch((error) => {
alert("Error"+error);
});
If I change to the code below, it runs well with no errors, but it will not prompt any successful message.
try{
((response) =>response.json()),
((response)=>{
alert(response[0].Message);
})
}
catch{
((error) => {
alert("Error"+error);
})
}
Here is the api script:
<?php
$CN = mysqli_connect('localhost', 'root', '');
$DB = mysqli_select_db($CN, 'iostest');
$EncodedData = file_get_contents('php://input');
$DecodedData = json_decode($EncodedData, true);
$userid = $DecodedData['userid'];
$jid=$DecodedData['jid'];
$job=$DecodedData['job'];
$mcode=$DecodedData['mcode'];
$insertuserid = "insert into scan(user,job,jobid,machinecode) values ('$userid','$job','$jid','$mcode')";
$register = mysqli_query($CN, $insertuserid);
if ($register)
$Message = "Member has been registered successfully";
else
$Message = "Server Error... please try latter";
$Response[] = array("Message" => $Message);
echo json_encode($Response);
?>

Sending JSON HTTP request using Guzzle HTTP: Result parameters are not as expected

I want to send a JSON request to an endpoint but the results that I get don't match the parameters requested.
This is the array
$datas = [
"institutionCode" => $institutionCode,
"brivaNo" => $brivaNo,
"custCode" => $custCode
];
This is the response using Guzzle HTTP
try {
$response = $client->request($verb, $endpoint,
[
"headers" =>
[
"Authorization" => "Bearer " . $token,
"BRI-Timestamp" => $timestamp,
"BRI-Signature" => $signature,
],
"json" => $datas
]
);
return $response;
}
catch (\GuzzleHttp\Exception\RequestException $e) {
return $e->getResponse();
}
This is the response from the endpoint
{
"status": false,
"errDesc": "Institution Code Tidak Boleh Kosong",
"responseCode": "03",
"data": {
"{\"institutionCode\":\"J104408\",\"brivaNo\":\"77777\",\"custCode\":\"7878787878\"}": ""
}
}
Why does the "data" not match the data array I have given above and instead creates a new pattern with a backslash in it?
This is the native way using cURL PHP
if there is someone can turn it into a Guzzle Http, it will help me,
after I tried this code, it also didn't help at all
$institutionCode = "J104408";
$brivaNo = "77777";
$custCode = "123456789115";
$payload = "institutionCode=".$institutionCode."&brivaNo=".$brivaNo."&custCode=".$custCode;
$path = "/v1/briva";
$verb = "DELETE";
$base64sign = generateSignature($path,$verb,$token,$timestamp,$payload,$secret);
$request_headers = array(
"Authorization:Bearer " . $token,
"BRI-Timestamp:" . $timestamp,
"BRI-Signature:" . $base64sign,
);
$urlPost ="https://sandbox.partner.api.bri.co.id/v1/briva";
$chPost = curl_init();
curl_setopt($chPost, CURLOPT_URL,$urlPost);
curl_setopt($chPost, CURLOPT_HTTPHEADER, $request_headers);
curl_setopt($chPost, CURLOPT_POSTFIELDS, $payload);
curl_setopt($chPost, CURLINFO_HEADER_OUT, true);
curl_setopt($chPost, CURLOPT_RETURNTRANSFER, true);
$resultPost = curl_exec($chPost);
$httpCodePost = curl_getinfo($chPost, CURLINFO_HTTP_CODE);
curl_close($chPost);
$jsonPost = json_decode($resultPost, true);
return $jsonPost;

AJAX post request to third party REST api

. I am using laravel backend as API and angular as frontend which calls laravel api. Laravel api access the teamwork api through basic authentication using curl.
Now I am working with teamwork Api. Trying to create a comment using the API.
API documentation describes following.
{
"comment": {
"body": "Reply to earlier comment",
"notify": "",
"isprivate": false,
"pendingFileAttachments": "",
"content-type": "TEXT"
}
}
//ref : http://developer.teamwork.com/comments#creating_a_commen
in my ajax call i have used following
var data = $.param({
'body' : commentBodyValue, //variable
'notify': "",
'isPrivate':false,
"pendingFileAttachments": "",
"content-type": "TEXT"
});
My post does not give error, but it also do not create a new comment too. What am I missing? I think i failed to arrange data according to the format allowed in api. Can you kindly help me to fix it?
Edit:
Angular Controller:
//add new comment
$scope.addComment = function(taskId,commentAuthorId)
{
var commentBod = document.getElementById("commentBody");
var commentBodyValue = commentBod.value;
console.log("new comment : "+ taskId + commentBodyValue);
//submit the post request
//$http.post();
//using jquery function param to serialize
var data = $.param({
'body' : commentBodyValue,
'notify': "",
'isPrivate':false,
"pendingFileAttachments": "",
"content-type": "TEXT"
});
var config = {
headers : {
// 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;',
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
}
var url = "http://abounde.com/portal/api/post_comment/"+taskId;
$http.post(url,data,config)
.then(
function(response){
//success
console.log("response : Submitted :D " + response);
},
function(response){
//failure
console.log(response);
}
);
}
Edit 2
Laravel route and controller
Routes:
//post comment to resource
Route::post('post_comment/{task_id}',[
'uses'=>'PortalController#postComment',
'as'=>'portal.client.postComment'
]);
Controller:
//post comment at task
public function postComment(Request $request, $task_id)
{
$secretApiKey = $request->session()->get('secretApiKey');
if(!empty($secretApiKey)){
//post the msg
$this->callTeamworkApi($secretApiKey,"tasks/".$task_id."/comments.json");
}else{
return response()->json(['response'=>"Not Logged In"]);
}
}
//authentication method
public function callTeamworkApi($secretApiKey, $apiCallString)
{
//cURL
$password = "xxx";
$channel = curl_init();
//options
curl_setopt($channel, CURLOPT_URL, "http://projects.abounde.com/".$apiCallString); // projects.json?status=LATE gets all late projects
curl_setopt($channel, CURLOPT_HTTPHEADER,
array(
"Authorization: Basic " . base64_encode($secretApiKey . ":" . $password)
));
$msg = curl_exec($channel);
curl_close($channel);
return response()->json(['res'=>$msg]);
}
EDIT 3: Contacted with teamwork Api support.
After their advice i came up with following code
//post comment at task
public function postComment(Request $request, $task_id)
{
$secretApiKey = $request->session()->get('secretApiKey');
if(!empty($secretApiKey)){
//post the msg
$comment=array();
// $comment['body']=$request->input('body');
// $comment['notify']=$request->input('notify');
// $comment['isprivate']=$request->input('isprivate');
// $comment['pendingFileAttachments']=$request->input('pendingFileAttachments');
// $comment['content-type']=$request->input('content-type');
$comment['comment']['body']="test";
$comment['comment']['notify']="";
$comment['comment']['isprivate']=false;
$comment['comment']['pendingFileAttachments']="";
$comment['comment']['content-type']="text";
$this->callTeamworkPostApi($secretApiKey,"tasks/".$task_id."/comments.json",json_encode($comment));
//var_dump($comment);
//return response()->json(['response'=>"Trying"]);
}else{
return response()->json(['response'=>"Not Logged In"]);
}
}
}
///
public function callTeamworkPostApi($secretApiKey, $apiCallString,$comment)
{
//cURL
$password = "xxx";
$channel = curl_init();
//options
curl_setopt($channel, CURLOPT_URL, "http://projects.abounde.com/".$apiCallString); // projects.json?status=LATE gets all late projects
curl_setopt($channel, CURLOPT_HTTPHEADER,
array(
"Authorization: Basic " . base64_encode($secretApiKey . ":" . $password)
));
curl_setopt($channel, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($channel, CURLOPT_POSTFIELDS, $comment);
$msg = curl_exec($channel);
curl_close($channel);
var_dump($msg);
//return response()->json(['res'=>$msg]);
}
var_dump($comment) gives
string(107) "{"comment":{"body":"test","notify":"","isprivate":false,"pendingFileAttachments":"","content-type":"text"}}"
However the api still do not save the comment. It has to be a curl post method issue. Right?
Edit 4:
I have done a var_dump(curl_getinfo($channel));
this gave me following response.
array(26) { ["url"]=> string(55) "http://projects.abounde.com/tasks/8199861/comments.json" ["content_type"]=> NULL ["http_code"]=> int(500) ["header_size"]=> int(229) ["request_size"]=> int(311) ["filetime"]=> int(-1) ["ssl_verify_result"]=> int(0) ["redirect_count"]=> int(0) ["total_time"]=> float(0.5) ["namelookup_time"]=> float(0) ["connect_time"]=> float(0.109) ["pretransfer_time"]=> float(0.109) ["size_upload"]=> float(107) ["size_download"]=> float(0) ["speed_download"]=> float(0) ["speed_upload"]=> float(214) ["download_content_length"]=> float(0) ["upload_content_length"]=> float(107) ["starttransfer_time"]=> float(0.5) ["redirect_time"]=> float(0) ["redirect_url"]=> string(0) "" ["primary_ip"]=> string(13) "23.23.184.208" ["certinfo"]=> array(0) { } ["primary_port"]=> int(80) ["local_ip"]=> string(11) "192.168.0.6" ["local_port"]=> int(31657) }
The response code 500 may points to the fact that teamwork has some kind of internal issues.
The issue i found out is that you are not passing your comment data which you received from the frontend to the curl the request in callTeamworkApi().Try below code and see if you get your desired output or not
//post comment at task
public function postComment(Request $request, $task_id)
{
$secretApiKey = $request->session()->get('secretApiKey');
if(!empty($secretApiKey)){
//post the msg
$comment=array();
$comment['body']=$request->input('body');
$comment['notify']=$request->input('notify');
$comment['isPrivate']=$request->input('isprivate');
$comment['pendingFileAttachments']=$request->input('pendingFileAttachments');
$comment['content-type']=$request->input('content-type');
$this->callTeamworkApi($secretApiKey,"tasks/".$task_id."/comments.json",json_encode($comment));
}else{
return response()->json(['response'=>"Not Logged In"]);
}
}
//authentication method
public function callTeamworkApi($secretApiKey, $apiCallString,$comment)
{
//cURL
$password = "xxx";
$channel = curl_init();
//options
curl_setopt($channel, CURLOPT_URL, "http://projects.abounde.com/".$apiCallString); // projects.json?status=LATE gets all late projects
curl_setopt($channel, CURLOPT_HTTPHEADER,
array(
"Authorization: Basic " . base64_encode($secretApiKey . ":" . $password)
));
curl_setopt($channel, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($channel, CURLOPT_POSTFIELDS, $comment);
$msg = curl_exec($channel);
curl_close($channel);
return response()->json(['res'=>$msg]);
}
Solution Found:
While calling to the teamwork API, it is essential that the content-type is set to Json. and the information should be in header file. header variable should be a multi array which takes authentication and content type information.
$headers = array();
$headers[] = "Authorization: Basic " . base64_encode($secretApiKey . ":" . $password);
$headers[] = "Content-Type: application/json";
//pass it as variable
curl_setopt($channel, CURLOPT_HTTPHEADER, $headers);
And then it works like charm.
returns following after creation of the comment.
{"commentId":"4294639","STATUS":"OK"}

How to pass data into a Listener when using Guzzle?

I am using Guzzle 3.8.1 with CakePHP 2.5.6 and I am making a call to the Box API. I would like to be able to refresh my access token when it expires. The issue I am encountering is that I may be using any one of N possible access tokens and I want to be able to use the $account_id that is in scope for the function I am defining this in. I don't see how I can pass it into the Listener defined function, since I am not calling that myself. I do see that the expired access_token exists in the $event variable, but I would have to locate it and then parse it from the header that I am passing to Box. I think I could add a custom header containing the account_id, but that seems like a bad way to approach the problem. Can I somehow specify a variable in the request that wouldn't be added as part of the call to Box? Any suggestions are much appreciated, thanks!
`
public function get_folder_list ($account_id = null, $parent_folder_id = null) {
// Get account
$this->Account = ClassRegistry::init('Account');
$account = $this->Account->findById($account_id);
$this->Account->log($account);
// If account doesn't exist, throw error
if(empty($account)) {
throw new NotFoundException(__('Account id not found: ' . $account_id));
}
// Call Box for folder list
$box_url = "https://api.box.com/2.0/folders/";
if (empty($parent_folder_id)) {
$box_url .= "0";
} else {
$box_url .= $parent_folder_id;
}
$this->Account->log($box_url);
$bearer = 'Bearer ' . $account['Account']['access_token'];
$client = new Guzzle\Http\Client();
$client->getEventDispatcher()->addListener('request.error', function(Event $event) {
if ($event['response']->getStatusCode() == 401) {
$Account = new Account;
$Account->log($event);
$Box = new BoxLib;
$account = $Box->refresh_token($account_id);
$bearer = 'Bearer ' . $account['Account']['access_token'];
$request = $client->get($box_url, array('Authorization' => $bearer));
$event['response'] = $newResponse;
$event->stopPropagation();
}
});
$request = $client->get($box_url, array('Authorization' => $bearer));
try {
$response = $request->send();
} catch (Guzzle\Http\Exception\BadResponseException $e) {
// HTTP codes 4xx and 5xx throw BadResponseException
$this->Account->log('Service exception!');
$this->Account->log('Uh oh! ' . $e->getMessage());
$this->Account->log('HTTP request URL: ' . $e->getRequest()->getUrl() . "\n");
$this->Account->log('HTTP request: ' . $e->getRequest() . "\n");
$this->Account->log('HTTP response status: ' . $e->getResponse()->getStatusCode() . "\n");
$this->Account->log('HTTP response: ' . $e->getResponse() . "\n");
}
$this->Account->log($response->json());
$json = $response->json();
$folder_list = array();
foreach ($json['item_collection']['entries'] as $folder) {
$folder_list[$folder['id']] = $folder['name'];
}
//$this->Account->log($folder_list);
return $folder_list;
}
`

JRequest::getVar is keeping previous values even after refreshing

I am writing a mail function as a module in joomla 3. e mail works fine, but when i reload the page and insert a different email and send, but it seemed to return the previous email by JRequest::getVar function. Is there a way to solve this issue? thanks in advance..
this is the code i used:
<?php
defined('_JEXEC') or die('Direct Access to this location is not allowed.');
require_once(dirname(__FILE__) . DS . 'helper.php');
//declaration
$input = JFactory::getApplication()->input;
$form_send = $input->get('form_send', 'notsend');
$fanme = $input->get('firstName');
$lname = $input->get('lastinput');
$email = $input->get('email', 0 , 'STRING');
$mail=false;
$emailexist=false;
echo '<script>
var php_var = "chk is first:'.$email.'";
alert(php_var);
</script>';
switch ($form_send) {
case 'send':
if ((is_null($fanme) || is_null($lname) || is_null($email)) || (!filter_var($email, FILTER_VALIDATE_EMAIL))) {
echo '<div> Fields are empty or not valid. <br></div>';
} else {
$mail = ModLittleContactHelper::SendMail($email, $fanme, $lname);
echo '<script>
var php_var = "chk when mail sending:'.$email.'";
alert(php_var);
</script>';
$input = JFactory::getApplication();//i have tried $app also
$input ->setUserState('mod_mycontact.email', null);
}
//echo $respond
if (!$mail) {
echo 'Error sending email:';
require(JModuleHelper::getLayoutPath('mod_myecontact', 'default_tmpl'));
}else{
require(JModuleHelper::getLayoutPath('mod_mycontact', 'sendok_tmpl'));
break;
}
default:
require(JModuleHelper::getLayoutPath('mod_littlecontact', 'default_tmpl'));
unset($var);
}
?>
#Mario this is the helper code:
class ModLittleContactHelper{
public function SendMail($email, $fname, $lname) {
$body = "<p style='font-family:arial;font-size:20px;'>Hi " . $fname . " " . $lname . ",</p>";
$body.="<p style='font-family:arial;font-size:20px;'>Welcome to Crowd Logistics! Please verify your email address below.</p><br/><br/>";
$body.= "<hr><br/>";
$body.= "<p style='align:center;background-color:#40B3DF;font-family:arial;color:#FFFFFF;font-size:20px;'><a href='http://suriyaarachchi.com/crowdlogistics/index.php?option=com_content&view=article&id=192' target='_blank'>Verify " . $email . "</a></p>";
$body.= "<br/><hr><br/>";
$body.="<p style='text-align:right;font-family:arial;font-size:20px;'>Or, paste this link into your browser:<br/>";
$body.= "http://crowdlogistics/index.php?option=com_content&view=article&id=192<br/><br/>";
$body.= "Thanks.<br/>";
$body.= "CrowdLogistics</p><br/>";
$mailer = & JFactory::getMailer();
$mailer->setSender('info#crowdlogistics.com');
$mailer->addRecipient($email);
$mailer->setSubject('Mail from CrowdLogistics - Confirm your email');
$mailer->setBody($body);
$mailer->IsHTML(true);
$send = & $mailer->Send();
return $send;
}
Since you're trying to run your code on Joomla 3, there are a few things that are wrong. Below os your code, corrected where I was able to correct it. Now you have to test it in your module environment with the class being instantiated (in other words, test the below code in your module).
<?php
defined('_JEXEC') or die('Direct Access to this location is not allowed.');
require_once(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'helper.php');
//declaration
$doc = JFactory::getDocument();
$app = JFactory::getApplication();
$input = $app->input;
$form_send = $input->get('form_send', 'notsend');
$fanme = $input->get('firstName');
$lname = $input->get('lastinput');
$email = $input->get('email', 0 , 'STRING');
$mail=false;
$emailexist=false;
$doc->addScriptDeclaration('
var php_var = "chk is first:'.$email.'";
alert(php_var);
');
switch ($form_send) {
case 'send':
if ((is_null($fanme) || is_null($lname) || is_null($email)) || (!filter_var($email, FILTER_VALIDATE_EMAIL))) {
echo '<div> Fields are empty or not valid. <br></div>';
} else {
$mail = ModLittleContactHelper::SendMail($email, $fanme, $lname);
$doc->addScriptDeclaration('
var php_var = "chk when mail sending:'.$email.'";
alert(php_var);');
$app->setUserState('mod_littlecontact.email', null);
}
//echo $respond
if (!$mail) {
echo 'Error sending email:';
require(JModuleHelper::getLayoutPath('mod_littlecontact', 'default_tmpl'));
break;
}else{
require(JModuleHelper::getLayoutPath('mod_littlecontact', 'sendok_tmpl'));
break;
}
default:
require(JModuleHelper::getLayoutPath('mod_littlecontact', 'default_tmpl'));
unset($var);
}
?>
First, JRequest class is deprecated in J3. You should use JInput:
$input = JFactory::getApplication()->input;
$your_var = $input->get('your_var');
Then, regarding the email, you probably need to unset the session variables when the success is achieved (mail sent), or in other words, when you don't need them any longer.
$app = JFactory::getApplication();
// your_var is the variable you want to unset
$app->setUserState('mod_your_module.your_var', null);
Hope it helps
you can use this code
$email = $input->get('email', 0 , 'STRING','');
4th argument for the default value,

Resources