Send header and post in curl to localbitcoins - php

I had tried to send info in a post and a header throw localbitcoins and get one error:
HMAC authentication key and signature was given, but they are invalid
From what i learn with localbitcoins api is this just a code u get when u mess with the header can someone help me to solve why I get this error because don't know whats wrong in my code:
function localbitcoins_query2($path, array $req = Array()) {
$key='mycode';
$secret='mycode';
$mt = explode(' ', microtime());
$nonce = $mt[1].substr($mt[0], 2, 6);
if ($req) {
$get=httpbuildquery($req);
$path=$path.'?'.$get;
}
$postdata=$nonce.$key.$path;
$sign = strtoupper(hash_hmac('sha256', $postdata, $secret));
$headers = array(
'Apiauth-Signature:'.$sign,
'Apiauth-Key:'.$key,
'Apiauth-Nonce:'.$nonce
);
$ch = null;
$ch = curl_init();
$data = array("lat" => "Hagrid", "price_equation" => "36");
$data_string = json_encode($data);
curl_setopt($ch, CURLOPT_URL,"https://localbitcoins.com".$path);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20);
$res = curl_exec($ch);
if ($res === false) throw new Exception('Curl error: '.curl_error($ch));
$dec = json_decode($res, true);
if (!$dec) throw new Exception('Invalid data: '.$res);
curl_close($ch);
return $dec;
}

Try this solution:
function localbitcoins_query2($path, array $req = Array()) {
$key='mycode';
$secret='mycode';
$mt = explode(' ', microtime());
$nonce = $mt[1].substr($mt[0], 2, 6);
$get = "";
if ($req) {
$get=httpbuildquery($req);
}
$postdata=$nonce.$key.$path.$get; // NOTE: $postdata 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();
$data = array("lat" => "Hagrid", "price_equation" => "36");
$data_string = json_encode($data);
curl_setopt($ch, CURLOPT_URL,"https://localbitcoins.com".$path.( $get=="" ? "" : "?".$get)); // NOTE: here it's necesary '?' char before the parameters!);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20);
$res = curl_exec($ch);
if ($res === false) throw new Exception('Curl error: '.curl_error($ch));
$dec = json_decode($res, true);
if (!$dec) throw new Exception('Invalid data: '.$res);
curl_close($ch);
return $dec;
}

Related

Php curl Jira issue creation not working with custom field

All , I am using PHP to create jira issues , below code is working fine , only issue if I sends custom fields value it sending error. please let me know if I am doing it in wrong way.
function createJiraServiceDeskRequestWithAttachment($serviceDeskId,$requestTypeId,$summary,$description = '', array $files = [],
$url,$user, $token, $primaryCustomerRepId=10202, $isAttachmentPublic = true
): array {
$returnValue = ['ticket' => [], 'temporaryAttachmentIds' => [], 'attachments' => [], 'error' => null];
// make sure to remove additional forward slashes /
$url = rtrim($url, '/');
$endPoint = $url . '/rest/servicedeskapi/request';
$data = [
"serviceDeskId" => $serviceDeskId,
"requestTypeId" => $requestTypeId,
"requestFieldValues" => [
"summary" => $summary,
"description" => $description,
// "customfield_10100" => $primaryCustomerRepId
],
];
try {
$ch = curl_init($endPoint);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
$jsonData = json_encode($data);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_setopt($ch, CURLOPT_USERPWD, $user . ":" . $token);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
$issueResult = curl_exec($ch);
$issueResult = json_decode($issueResult, true);
if (curl_errno($ch) || empty($issueResult))
return $returnValue;
curl_close($ch);
$returnValue['ticket'] = $issueResult;
// here add temporary attachment
if (! empty ($files)):
$uploadedAttachments = [];
$endPoint = $url . "/rest/servicedeskapi/servicedesk/{$serviceDeskId}/attachTemporaryFile";
foreach ($files as $index => $file) {
$ch = curl_init($endPoint);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, ['file' => curl_file_create(
realpath($file),
mime_content_type($file),
basename($file)
)]);
curl_setopt($ch, CURLOPT_USERPWD, $user . ":" . $token);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: multipart/form-data', 'X-Atlassian-Token: no-check']);
$tmpResult = curl_exec($ch);
if (! curl_errno($ch) && ! empty($tmpResult = json_decode($tmpResult, true))) {
if (isset($tmpResult['temporaryAttachments']) && isset($tmpResult['temporaryAttachments'][0]['temporaryAttachmentId']))
$uploadedAttachments[] = $tmpResult['temporaryAttachments'][0]['temporaryAttachmentId'];
}
curl_close($ch);
}
else:
return $returnValue;
endif;
// check if there are temporary attachments uploaded, then link them with the request
if (! empty($uploadedAttachments)):
$returnValue['temporaryAttachmentIds'] = $uploadedAttachments;
$endPoint = $url . "/rest/servicedeskapi/request/{$issueResult['issueId']}/attachment";
$ch = curl_init($endPoint);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
$jsonData = json_encode(["temporaryAttachmentIds" => $uploadedAttachments, 'public' => $isAttachmentPublic]);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_setopt($ch, CURLOPT_USERPWD, $user . ":" . $token);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
$attachresult = curl_exec($ch);
$attachresult = json_decode($attachresult, true);
if (! curl_errno($ch) && ! empty($attachresult))
$returnValue['attachments'] = $attachresult;
curl_close($ch);
return $returnValue;
else:
return $returnValue;
endif;
} catch (\Exception $e) {
$returnValue['error'] = $e->getMessage();
return $returnValue;
}
}
If I uncomment this code customfield_10100, it doesn't work
I also tried to place it outside of requested values array
"fields" =>[
"customfield_10100" => $primaryCustomerRepId
]

PHP - HMAC Authentication

I'm getting that error code (I'm using a public API so it's certainly working on their side ;)):
HMAC authentication key and signature was given, but they are invalid.
function get_myself($request){
$public_key = "MY_PUBLIC_KEY";
$secret = "MY_PRIVATE_KEY";
$parameters = array(
"client_id" => $public_key,
"client_secret" => $secret
);
$data = http_build_query($parameters);
$ch = curl_init("https://localbitcoins.com".$request);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_USERAGENT, "curl");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$nonce = time();
$sig = base64_encode ( hash_hmac("sha256", $nonce.$public_key.$request, $secret ) );
$options = array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTPHEADER => array(
"Apiauth-Key:".$public_key,
"Apiauth-Nonce:".$nonce,
"Apiauth-Signature:".$sig
),
);
curl_setopt_array($ch, $options);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
$getinfo = array();
$getinfo = get_myself("/api/myself/");
echo "<pre>"; print_r($getinfo); echo "</pre>";
After 3 days, I found the 'solution'... here's a working example:
function localbitcoins_query($path, array $req = Array()) {
$key='MY_KEY';
$secret='MY_SECRET';
$mt = explode(' ', microtime());
$nonce = $mt[1].substr($mt[0], 2, 6);
if ($req) {
$get=httpbuildquery($req);
$path=$path.'?'.$get;
}
$postdata=$nonce.$key.$path;
$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);
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();
$devise = "EUR";
$url = "/buy-bitcoins-online/".$devise."/western-union/.json";
$getinfo = localbitcoins_query($url);
echo "<pre>"; print_r($getinfo); echo "</pre>";
It's working on my side, I suppose the POST / GET notion wasn't previously handle properly whereas it is in that version.
Enjoy :p

php json_decode is not working Properly

When i am Decoding using commented "$jsonString" String it is working very well.
But after using curl it is not working, showing Null.
Please Help Me in this.
if (isset($_POST['dkno'])) {
$dcktNo = $_POST['dkno'];
$url = 'http://ExampleStatus.php?dkno=' . $dcktNo;
$myvars = '';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $myvars);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$jsonString = curl_exec($ch);
// $jsonString = '[{"branchname":"BHUBNESHWAR","consignee":"ICICI BANK LTD","currentstatus":"Delivered by : BHUBNESHWAR On - 25/07/2015 01:00","dlyflag":"Y","PODuploaded":"Not Uploaded"}]';
if ($jsonString != '') {
$json = str_replace(array('[', ']'), '', $jsonString);
echo $json;
$obj = json_decode($json);
if (is_null($obj)) {
die("<br/>Invalid JSON, don't need to keep on working on it");
} else {
$podStatus = $obj->PODuploaded;
}
}
}
}
After curl I used following concept to get only JSON data from HTML Page.
1) fetchData.php
$url = 'http://DocketStatusApp.aspx?dkno=' . $dcktNo;
$myvars = '';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $myvars);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$jsonString = curl_exec($ch);
// now get only value
$dom = new DOMDocument();
$dom->loadHTML($jsonString);
$thediv = $dom->getElementById('Label1');
echo $thediv->textContent;
2) JSONprocess.php
if (isset($_POST['dkno'])) {
$dcktNo = $_POST['dkno'];
ob_start(); // begin collecting output
include_once 'fetchData.php';
$result = ob_get_clean(); // Completed collecting output
// Now it will show & take only JSON Data from Div Tag
$json = str_replace(array('[', ']'), '', $result);
$obj = json_decode($json);
if (is_null($obj)) {
die("<br/>Invalid JSON, don't need to keep on working on it");
} else {
$podStatus = $obj->PODuploaded;
}
}

CoinBase "invalid signature" PHP Buy API Request

I have looked over the code many times but whenever I send request to API it returns "message":"invalid signature"
I am thinking it has to do with hashing the body, possibly. I'm new to PHP and its my first project. :)
Anyone see an error? Thanks.
<?php
$arr = array('size' => ".01", 'price' => '240', 'side' => 'sell',
'product_id' => 'BTC-USD');
$output = json_encode($arr);
echo json_encode($arr)."<br/>";
$key = "f23612b06cb4d020cda7e04b1ae6ef9a";
$secret = "RENqodtuTCn4v7g7Pn/FFdQAIKReVXGayNPrNN/Zb7AjATI0hP4R0MCDD5RqnDu60qTZ5Qry329fFu7kcObGBw==";
$passphrase = "tradebot";
$time = time();
$url = "https://api.gdax.com/orders";
$data = $time."POST"."/orders";
echo $data . "<br/>";
$hashinput = "$output"."$data";
$sign = base64_encode(hash_hmac("sha256", $hashinput, base64_decode($secret), true));
echo $sign . "<br/>";
$headers = array(
'CB-ACCESS-KEY: '.$key,
'CB-ACCESS-SIGN: '.$sign,
'CB-ACCESS-TIMESTAMP: '.$time,
'CB-ACCESS-PASSPHRASE: '.$passphrase,
'Content-Type: application/json'
);
var_dump($headers);
echo $url;
static $ch = null;
if (is_null($ch)) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, 'local server');
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, $output);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$res = curl_exec($ch);
echo $res;
}
replace
$hashinput = "$output"."$data";
with
$hashinput = "$data"."$output";
and replace
curl_setopt($ch, CURLOPT_POST, $output);
with
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $output);
(from Coinbase Community forum)

Google Calendar API - PHP - set event's color

How do we set a color when inserting an event with Google Calendar API (PHP)?
Here is a PHP function I wrote and the portions of the PHP client library I extracted to allow me to create events in my calendar, delete events and so forth but the code is just to show you where the colorId needs to be set and the syntax to make it work.
The colors Google will show for each of the first 11 integers you can set colorId to.
1 blue
2 green
3 purple
4 red
5 yellow
6 orange
7 turquoise
8 gray
9 bold blue
10 bold green
11 bold red
function calendar_update($heading,$details,$address,$calendar_name,$start_time,$end_time,$event_id = "")
{
$client = get_google_client($calendar_name); // ID of your Google calendar
$capi = new GoogleCalendarApi($client);
$event['event_time']['start_time'] = $start_time; // Start time of event
$event['event_time']['end_time'] = $end_time; // End time of the event
$event['summary'] = $heading; // The title of the event
$event['location'] = $address; // Address field of event
$event['description'] = $details; // Body of the event
$event['colorId'] = 3; // colorId of event (see above)
$event['attendees'] = $calendar_name;
try
{
$event_id = $capi->CreateCalendarEvent($calendar_name, $event, 0,
$event['event_time'], "Australia/Sydney", $_SESSION['access_token']);
}
catch(Exception $e)
{
$result = $e->getMessage();
return("ERROR\t$e");
}
return($event_id);
}
class GoogleCalendarApi
{
public function GetAccessToken($client_id, $redirect_uri, $client_secret, $code) {
$url = 'https://accounts.google.com/o/oauth2/token';
$curlPost = 'client_id=' . $client_id . '&redirect_uri=' . $redirect_uri . '&client_secret=' . $client_secret . '&code='. $code . '&grant_type=authorization_code';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
$data = json_decode(curl_exec($ch), true);
$http_code = curl_getinfo($ch,CURLINFO_HTTP_CODE);
if($http_code != 200)
throw new Exception('Error : Failed to receieve access token');
return $data;
}
public function GetUserCalendarTimezone($access_token) {
$url_settings = 'https://www.googleapis.com/calendar/v3/users/me/settings/timezone';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url_settings);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer '. $access_token));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$data = json_decode(curl_exec($ch), true); //echo '<pre>';print_r($data);echo '</pre>';
$http_code = curl_getinfo($ch,CURLINFO_HTTP_CODE);
if($http_code != 200)
throw new Exception('Error : Failed to get timezone');
return $data['value'];
}
public function GetCalendarsList($access_token) {
$url_parameters = array();
$url_parameters['fields'] = 'items(id,summary,timeZone)';
$url_parameters['minAccessRole'] = 'owner';
$url_calendars = 'https://www.googleapis.com/calendar/v3/users/me/calendarList?'. http_build_query($url_parameters);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url_calendars);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer '. $access_token));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$data = json_decode(curl_exec($ch), true); //echo '<pre>';print_r($data);echo '</pre>';
$http_code = curl_getinfo($ch,CURLINFO_HTTP_CODE);
if($http_code != 200)
throw new Exception('Error : Failed to get calendars list');
return $data['items'];
}
public function CreateCalendarEvent($calendar_id, $summary, $all_day, $event_time, $event_timezone, $access_token) {
$url_events = 'https://www.googleapis.com/calendar/v3/calendars/' . $calendar_id . '/events';
$curlPost = $summary;
// $curlPost = array('summary' => $summary);
if($all_day == 1) {
$curlPost['start'] = array('date' => $event_time['event_date']);
$curlPost['end'] = array('date' => $event_time['event_date']);
}
else {
$curlPost['start'] = array('dateTime' => $event_time['start_time'], 'timeZone' => $event_timezone);
$curlPost['end'] = array('dateTime' => $event_time['end_time'], 'timeZone' => $event_timezone);
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url_events);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer '. $access_token, 'Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($curlPost));
$data = json_decode(curl_exec($ch), true);
$http_code = curl_getinfo($ch,CURLINFO_HTTP_CODE);
if($http_code != 200)
throw new Exception('Error : Failed to create event');
return $data['id'];
}
public function UpdateCalendarEvent($event_id, $calendar_id, $summary, $all_day, $event_time, $event_timezone, $access_token) {
$url_events = 'https://www.googleapis.com/calendar/v3/calendars/' . $calendar_id . '/events/' . $event_id;
$curlPost = $summary;
// $curlPost = array('summary' => $summary);
if($all_day == 1) {
$curlPost['start'] = array('date' => $event_time['event_date']);
$curlPost['end'] = array('date' => $event_time['event_date']);
}
else {
$curlPost['start'] = array('dateTime' => $event_time['start_time'], 'timeZone' => $event_timezone);
$curlPost['end'] = array('dateTime' => $event_time['end_time'], 'timeZone' => $event_timezone);
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url_events);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer '. $access_token, 'Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($curlPost));
$data = json_decode(curl_exec($ch), true);
$http_code = curl_getinfo($ch,CURLINFO_HTTP_CODE);
if($http_code != 200)
throw new Exception('Error : Failed to update event Code: ' . $http_code);
}
public function DeleteCalendarEvent($event_id, $calendar_id, $access_token) {
$url_events = 'https://www.googleapis.com/calendar/v3/calendars/' . $calendar_id . '/events/' . $event_id;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url_events);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer '. $access_token, 'Content-Type: application/json'));
$data = json_decode(curl_exec($ch), true);
$http_code = curl_getinfo($ch,CURLINFO_HTTP_CODE);
if($http_code != 204)
throw new Exception('Error : Failed to delete event');
}
}
You can set the optional colorId property when creating an event. You can retrieve the list of colours from the colors endpoint.
Here you can find each idColor for your color that you want to insert for events
Google Calendar id Color for events

Categories