I need to get a highcharts image, and I found a code to resolve my problem, obtaining the name of the image via ajax, and then I paste before the url of the Highcharts API, and I can download the image in PHP, now, I want to do this process in PHP, since the name, until the download; I have this code to get the name of highcharts image:
var optionsStr = JSON.stringify({
"xAxis": {
"categories": [
"PRUEBA",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"
]
},
"series": [
{
"data": [1, 3, 2, 4],
"type": "line"
},
{
"data": [5, 3, 4, 2],
"type": "line"
}
]
}),
exportUrl ='https://export.highcharts.com/';
dataString = encodeURI('async=true&type=image/jpeg&width=800&options=' + optionsStr);
$.ajax(
{
type: 'POST',
data: dataString,
url: exportUrl,
success: function(data)
{
console.log('get the file from relative url: ', data);
grafica=exportUrl+data;
},
error: function(err)
{
console.log('error', err.statusText)
}
});
I get the name of the graphic: charts/chart.9973ffbcf0d748d6aae04ef6ec01979c.jpeg
I want to know how get the same in PHP, I have this code:
$DataEncoded = json_encode(
array(
'xAxis'=>
array(
'categories'=> ['Ene','Feb', 'Mar', 'Abr']
),
'series'=>
array(
array(
'data'=>[1,2,3,4],
'type'=>'line'
),
array(
'data'=>[5,6,7,8],
'type'=>'line'
)
)
)
);
$DataExtra = 'async=true&type=image/jpeg&width=800&options=';
$dataString = urlencode('async=true&type=image/jpeg&width=800&options='.$DataEncoded);
$url ='https://export.highcharts.com/';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
$json=curl_exec($ch);
if(curl_errno($ch)){
echo "Entro al curl Error";
throw new Exception(curl_error($ch));
}
var_dump(json_decode($json));
curl_close($ch);
But I receive a fantastic: NULL. Someone made this before?
I tried making this process via Angular 5, but, I must to program a cron job to delegate the process, so, I decided to use PHP. I tried with file_get_contents() but the webservice give me: "No data chart found".
I suspect your issue is here:
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
I believe this is expecting a String or an Array.
This parameter can either be passed as a urlencoded string like 'para1=val1¶2=val2&...' or as an array with the field name as key and field data as value. If value is an array, the Content-Type header will be set to multipart/form-data. As of PHP 5.2.0, value must be an array if files are passed to this option with the # prefix. As of PHP 5.5.0, the # prefix is deprecated and files can be sent using CURLFile.
Consider trying the following:
$dataArray = array(
"async" => true,
"type" => "image/jpeg",
"width" => 800,
"options" => $DataEncoded
);
And...
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataArray);
Credit to #Patrick Q for catching the Encoding Type. You're not exactly sending it JSON encoded data, but Form data essentially.
I used the recommendations of Twisty and finally I obtain the name of the image, thank you so much.
$dataString = ('async=true&type=image/jpeg&width=800&options='.$DataEncoded);
$url ='https://export.highcharts.com/?';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$dataString);
curl_setopt($ch, CURLOPT_POST, 1);
$headers = array();
$headers[] = "Accept: application/json";
$headers[] = "Content-Type: application/x-www-form-urlencoded";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
Related
For few days I am trying to use the ClickUp API. The goal is:
We have a form, and when the form is submitted, it creates a task on a space on ClickUp.
It is a PHP form, and even with the API Doc here, I am not able to understand how it is working.
I found this: https://jsapi.apiary.io/apis/clickup20/reference/0/tasks/create-task.html
But it requires some access token, from the user, but normally, It's not supposed to work like that.
Here the script that I have taken from the doc:
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.clickup.com/api/v2/list/17229593/task");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, "{
\"name\": \"New Task Name\",
\"content\": \"New Task Content\",
\"assignees\": [
183
],
\"tags\": [
\"tag name 1\"
],
\"status\": \"Open\",
\"priority\": 3,
\"due_date\": 1508369194377,
\"due_date_time\": false,
\"time_estimate\": 8640000,
\"start_date\": 1567780450202,
\"start_date_time\": false,
\"notify_all\": true,
\"parent\": null,
\"custom_fields\": [
{
\"id\": \"0a52c486-5f05-403b-b4fd-c512ff05131c\",
\"value\": 23
},
{
\"id\": \"03efda77-c7a0-42d3-8afd-fd546353c2f5\",
\"value\": \"Text field input\"
}
]
}");
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Authorization: "access_token"",
"Content-Type: application/json"
));
$response = curl_exec($ch);
curl_close($ch);
var_dump($response);
When I try that, I get the error 500, and when I go to the API's link, I get an Auth problem.
Is someone know something about this API?
still trying to get my head around API's and connections.
I am trying to do a buy order to Binance but keep getting a 400 response. I know it's been an issue for some others but I just can't seem to suss out where I am going wrong. So hoping someone can help me out.
It's only issues with POST's, all the GET requests are working fine, and so to the signature and timestamp... or at least I am getting responses for my account so I assume so.
The first CURL is just for the serverTime, but the second CURL is for a buy/sell order.
This is the response I am getting now...
"Object ( [code] => -1102 [msg] => Mandatory parameter 'side' was not
sent, was empty/null, or malformed. )"
If I type the in the string manually it works just fine, but for one reason or another when I pass $qs it presents the above fault. I echoed $qs to the screen and copied that instead of passing $qs and it worked when I put in the new timestamp. I am stumped...
"symbol=TRXUSDC&side=SELL&type=LIMIT&timeInForce=GTC&quantity=63000.00000000&price=0.02550000&recvWindow=1000000×tamp=1550922237310"
any advice?
$header = array('X-MBX-APIKEY:' . KEY);
$url = BINANCE . 'api/v1/time';
$curl = curl_init();
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($curl, CURLOPT_TIMEOUT, 60);
curl_setopt($curl, CURLOPT_ENCODING, "");
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($curl, CURLOPT_URL,$url);
$response = curl_exec($curl);
if (FALSE === $response){
echo curl_error($curl), curl_errno($curl);
}
$serverTime = json_decode($response);
curl_close($curl);
$url = BINANCE . "api/v3/order";
$signature = NULL;
$queryString = NULL;
$query = array(
"symbol" => "TRXUSDC",
"side" => "SELL",
"type" => "LIMIT",
"timeInForce" => "GTC",
"quantity" => number_format(63000.00000000,8,'.',''),
"price" => number_format(0.02550000,8,'.',''),
"recvWindow" => 1000000,
"timestamp" => $serverTime->serverTime);
$qs = htmlentities(http_build_query(array_unique($query)));
$query['signature'] = hash_hmac('SHA256', $qs, SECRET );
$curl = curl_init();
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($curl, CURLOPT_TIMEOUT, 60);
curl_setopt($curl, CURLOPT_ENCODING, "application/x-www-form-urlencoded");
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl,CURLOPT_FAILONERROR,FALSE);
curl_setopt($curl, CURLOPT_VERBOSE, TRUE);
curl_setopt($curl, CURLOPT_POST, TRUE);
curl_setopt($curl, CURLOPT_POSTFIELDS,$qs);
curl_setopt($curl, CURLOPT_URL, $url);
$response = curl_exec($curl);
if (FALSE === $response){
echo curl_error($curl).':'.curl_errno($curl);
}
$obj = json_decode($response);
curl_close($curl);
I tried this code and var_dump $qs
symbol=BTCUSDT&side=BUY&...
so I think you must remove amp;
Based on Binance spot api docs:
It is recommended to use a small recvWindow of 5000 or less! The max cannot go beyond 60,000!
so edit your query params with:
"symbol=TRXUSDC&side=SELL&type=LIMIT&timeInForce=GTC&quantity=63000.00000000&price=0.02550000&recvWindow=60000×tamp=1550922237310"
Also you can check your other query params with exchange info that you can get with https://api.binance.com/api/v3/exchangeInfo that we have for your symbol:
{
"symbol": "TRXUSDC",
"status": "TRADING",
"baseAsset": "TRX",
"baseAssetPrecision": 8,
"quoteAsset": "USDC",
"quotePrecision": 8,
"quoteAssetPrecision": 8,
"baseCommissionPrecision": 8,
"quoteCommissionPrecision": 8,
"orderTypes": [
"LIMIT",
"LIMIT_MAKER",
"MARKET",
"STOP_LOSS_LIMIT",
"TAKE_PROFIT_LIMIT"
],
"icebergAllowed": true,
"ocoAllowed": true,
"quoteOrderQtyMarketAllowed": true,
"isSpotTradingAllowed": true,
"isMarginTradingAllowed": false,
"filters": [
{
"filterType": "PRICE_FILTER",
"minPrice": "0.00001000",
"maxPrice": "1000.00000000",
"tickSize": "0.00001000"
},
{
"filterType": "PERCENT_PRICE",
"multiplierUp": "5",
"multiplierDown": "0.2",
"avgPriceMins": 5
},
{
"filterType": "LOT_SIZE",
"minQty": "0.10000000",
"maxQty": "9000000.00000000",
"stepSize": "0.10000000"
},
{
"filterType": "MIN_NOTIONAL",
"minNotional": "10.00000000",
"applyToMarket": true,
"avgPriceMins": 5
},
{
"filterType": "ICEBERG_PARTS",
"limit": 10
},
{
"filterType": "MARKET_LOT_SIZE",
"minQty": "0.00000000",
"maxQty": "659177.02430556",
"stepSize": "0.00000000"
},
{
"filterType": "MAX_NUM_ORDERS",
"maxNumOrders": 200
},
{
"filterType": "MAX_NUM_ALGO_ORDERS",
"maxNumAlgoOrders": 5
}
],
"permissions": [
"SPOT"
]
}
for other possible reasons check spot api docs in the link https://github.com/binance/binance-spot-api-docs/blob/master/rest-api.md
I tested the code and saw a few glitches in it :
$qs = htmlentities(http_build_query(array_unique($query)));
gave me an error ({"code":-1102,"msg":"Mandatory parameter 'side' was not sent, was empty/null, or malformed."}), so i replaced it with:
$qs = http_build_query(array_unique($query));
After that you created your signature, but never added it to you request. So do the following :
$signature = hash_hmac('sha256', $qs, $apiSecret);
$qs .= "&signature=" . $signature;
Also update your 'recvWindow' to a max of 60000 (I suggest 50000 or less (see the answer of #Tofiq Samali)) and you are ready to go!
The instructions I have for using an api gives two options.
One requires a zipCode input and one does not.
Using PHP I have successfully built a curl resource using curl_setop for the case that uses the zipCode but not the case that omits the zipCode. The case without the zipCode is supposed to have an extra option after the URL.
All I have been given for instructions is that the curl should be like:
curl -i -X POST -H "Content-Type:application/json" -H "authToken:12345" https://connect.apisite.com/api/v1/users -d'
[{
"firstName": "John",
"lastName": "Smith",
"emailAddress": {
"address": "johnsmith#test.com"
}
}]'
for the case without the zipCode
and with the zipCode
curl -i -X POST -H "Content-Type:application/json" -H
"authToken:12345" https://connect.apisite.com/api/v1/users '
[{
"firstName": "John",
"lastName": "Smith",
"emailAddress": { "address": "johnsmith#test.com" },
"homeAddress" : { "postalCode" : "48124" }
}
}]'
My problem is that I do not know how to add the -d to the curl resource that appears in the first case just after the URL
This works for me:
$url = "https://connect.apisite.com/api/v1/users";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
$request_headers = array();
$request_headers[] = 'authToken: ' . $authResponse;
$request_headers[] = 'Content-Type: application/json';
curl_setopt($ch, CURLOPT_HTTPHEADER, $request_headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
$response = curl_exec($ch);
I tried just appending the -d to the URL as
$url = "https://connect.apisite.com/api/v1/users -d";
That did not work.
My guess is there is a constant I need to use like
curl_setop($ch, CURLOPT_XXXXX, '-d');
but I do not know what CURLOPT_XXXX should be.
Any help would be appreciated.
I'm not sure why you use curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST'); as your call structure seems could be done by a regular POST call which could be handled by:
curl_setopt(CURLOPT_POST, true);
which in turn will call the -d flag of cURL as per PHP document:
CURLOPT_POST: TRUE to do a regular HTTP POST. This POST is the normal application/x-www-form-urlencoded kind, most commonly used by HTML forms.
Also, you need to change curl_setopt($ch, CURLOPT_POSTFIELDS, $postData); because doing this will make cURL to pass the data as multipart/form-data. Instead, structure your data as a URL-encoded string, something like
curl_setopt($ch, CURLOPT_POSTFIELDS, urlencode(json_encode($postData)));
(note: I haven't tested the latter line above but you can test it and adjust as per your requirements), as per PHP documentation note:
Note:
Passing an array to CURLOPT_POSTFIELDS will encode the data as multipart/form-data, while passing a URL-encoded string will encode the data as application/x-www-form-urlencoded.
Thanks everyone for your help and suggestions.
As was mentioned I did not need to do anything to add the -d
I got the response I need using the following for postData
$postData = json_encode(array(array('emailAddress' => $emailObj, 'firstName' => $firstName, 'lastName' => $lastName)));
or
$postData = json_encode(array(array('emailAddress' => $emailObj, 'firstName' => $firstName, 'lastName' => $lastName, 'homePostalAddress' => $homePostalObj)));
In both request the method is POST, as the previous answer you can set CURLOPT_POST option. I see the only different is about the data you are sending, in one without zipCode and another with. So, you can just prepare the data before including the zipCode or not in your array of data. You can try something like below.
$dataRequest = [
'firstName' => "John",
'lastName' => "Smith",
'emailAddress' => [
'address' => 'johnsmith#test.com'
],
'homeAddress' => [ //dont send this key in the case you dont want zipCode in the request.
'postalCode'=> '48124'
],
];
$url = "https://connect.apisite.com/api/v1/users";
$authToken = '12345';
$ch = curl_init();
/**
the idea with urldecode is because some api does not accept the
encoded urls in your case is not important due your data does not
contains any url but if tomorrow you want to include smth like
'customerUrl'=>'https://myhomepage.com' the result of http_build_query
will be like 'https%3A%2F%2Fmyhomepage.com'
*/
$data = urldecode(http_build_query($dataRequest));
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_USERPWD, "{$authToken}:");
$headers = [];
$headers[] = 'Content-Type: application/x-www-form-urlencoded';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
if (!curl_errno($ch)) {
/**
HANDLE RESPONSE, CHECK FOR PROPER HTTP CODE DEPENDING OF THE API RESPONSE,
IN YOUR CASE I GUESS IS CREATE USER YOUR GOAL, SO MAYBE RESPONSE IS 'HTTP_CREATED'
BUT IF THIS FUNCTION WILL BE GENERIC BETTER SWITCH LIKE THIS:
switch ($http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE)) {
case Response::HTTP_OK:
case Response::HTTP_CREATED:
case Response::HTTP_ACCEPTED:
$response = json_decode($response, true);
break;
default:
$response = [];
}
*/
}
curl_close($ch);
return $response;
This example is with content-type not in json format, you can change it if is requirement of api.
This always throws the error that none of those params are valid. For example: Undefined index: dataNL
Receiving Code:
$ajax_arrayBTF = $_POST['dataBTF'];
$ajax_arrayLI = $_POST['dataLI'];
$ajax_arrayLS = $_POST['dataLS'];
$ajax_arrayNL = $_POST['dataNL'];
$agent_id = $_POST['agent'];
Here is the calling code I am using:
$data = array(
"dataBTF" => "0",
"dataNL" => "0",
"dataLS" => "0",
"dataLI" => "0",
"agent" => "53"
);
$data_string = json_encode($data);
echo $data_string;
$ch = curl_init('http://localhost/site1/backend/scripts/oppCAL.php');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
curl_setopt($ch, CURLOPT_HTTPHEADERS, array('Content-Type: application/json'));
echo curl_exec($ch);
I don't get why this is happening, because I am MANUALLY assigning it. So it is valid. echo $data_string; displays
{"dataBTF":"0","dataNL":"0","dataLS":"0","dataLI":"0","agent":"53"}
Just like it should.. I decided to go with JSON, but even that is not working. CURL is enabled. What am I missing here?
EDIT:
When ajax was calling there was no issue. My ajax was:
$.ajax(
{
type: 'post',
url: 'scripts/oppCAL.php',
data:
{
dataBTF: $array_jsBTF,
dataLI: $array_jsLI,
dataLS: $array_jsLS,
dataNL: $array_jsNL,
agent: $agent_id
},
success: function(e)
{
console.log("done:");
} //success
}); // ajax
PHP doesn't parse JSON body data, only form encoded, like your jQuery ajax call sends. It looks something like this:
dataBTF=0&dataLI=0&dataLS=0&dataNL=0&agent=0
When receiving JSON, you can use something like this to get the data:
$body = file_get_contents('php://input');
$data = json_decode($body, true);
hi i have a problem with cURL and php. I use an API and i want to display only the results.
Here is my php + curl script
<?php
$file = "http://api.openkvk.nl/php/".rawurlencode("SELECT * FROM kvk WHERE kvks='20147376'");
$ch = curl_init();
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_URL, $file);
curl_setopt($ch, CURLOPT_HEADER, 0);
// grab URL and pass it to the browser
curl_exec($ch);
// close cURL resource, and free up system resources
curl_close($ch);
?>
and the result what i get is this:
array(
array("RESULT" => array(
"TYPES"=>
array(
"int", "bigint", "varchar", "varchar", "varchar", "varchar", "varchar", "int", "int", "smallint", "smallint", "int"
),
"HEADER"=>
array("id", "kvk", "bedrijfsnaam", "adres", "postcode", "plaats", "type", "kvks", "sub", "bedrijfsnaam_size", "adres_size", "verhuisd"),
"ROWS"=>
array(
array("1008714", "20147376", "Stichting OpenGeo", "Spinellihof 44", "4463GP", "Goes", "Rechtspersoon", "20147376", NULL, "17", "14", "0")
)
)));
Your script outputs data, instead of returning it. Add this line:
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
And then assign curl_exec to some variable:
$result = curl_exec($ch);
It seems that API returns some META information, such as field types. If you don't need it, the just work with 'ROWS' element
print_r($result['ROWS']);
It will look like this:
array(
"1008714","20147376","Stichting OpenGeo","Spinellihof 44","4463GP","Goes","Rechtspersoon","20147376",NULL,"17","14","0"
)
You can iterate through it:
for($i=0; $i<count($result['ROWS']); $i++)
{
echo $result['HEADER'][$i].': '.$result['ROWS'][$i].'<br />';
}