Binance api php - php

I'm trying to integrate a binance api with php.
I want to spend my spot wallets and earnings.
I can't find the url I need for it and I can't get the endpoint either.
Additional question: For what do I need the timestamp?
$secret = "mySecretKey";
$key = "myApiKey";
$s_time = "timestamp=".time()*1000;
$sign=hash_hmac('SHA256', $s_time, $secret);
$url = "https://api.binance.com/api/v1/balances?".$s_time.'&signature='.$sign;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-MBX-APIKEY:'.$key));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_URL, $url);
$result = curl_exec($ch);
$result = json_decode($result, true);
echo '<pre>';
var_dump($result);
echo '</pre>';
curl_close($ch);
I've tried many urls and looked at the binance documentation for a long time but I just can't find it.
Thanks for your help!

The only link I found in their API documentation is
Query Sub-account Assets (For Master Account)
GET /sapi/v3/sub-account/assets (HMAC SHA256)
Response:
{
"balances":[
{
"asset":"ADA",
"free":10000,
"locked":0
},
{
"asset":"BNB",
"free":10003,
"locked":0
},
{
"asset":"BTC",
"free":11467.6399,
"locked":0
},
{
"asset":"ETH",
"free":10004.995,
"locked":0
},
{
"asset":"USDT",
"free":11652.14213,
"locked":0
}
]
}

I do not know exactly what you want to do but if you want an overview of your spot balances the right endpoint is :
GET /api/v3/account (HMAC SHA256), link to more info : https://binance-docs.github.io/apidocs/spot/en/#account-information-user_data
response:
{
"makerCommission": 15,
"takerCommission": 15,
"buyerCommission": 0,
"sellerCommission": 0,
"commissionRates": {
"maker": "0.00150000",
"taker": "0.00150000",
"buyer": "0.00000000",
"seller": "0.00000000"
},
"canTrade": true,
"canWithdraw": true,
"canDeposit": true,
"brokered": false,
"requireSelfTradePrevention": false,
"updateTime": 123456789,
"accountType": "SPOT",
"balances": [
{
"asset": "BTC",
"free": "4723846.89208129",
"locked": "0.00000000"
},
{
"asset": "LTC",
"free": "4763368.68006011",
"locked": "0.00000000"
}
],
"permissions": [
"SPOT"
]
}
more about the timestamp you can find here: https://binance-docs.github.io/apidocs/spot/en/#signed-trade-user_data-and-margin-endpoint-security

Related

Curl and FedEx API responding with gibberish in PHP

I've been trying to implement the FedEx rates and transit times API in a PHP script.
I successfully connected with it to get the bearer token.
But when I try to get rates for a simple shipment, it responds with random gibberish.
I don't even get any errors. That's what frustrating.
Here is my code:
ini_set('display_errors', 1);
error_reporting(-1);
$access_url = 'https://apis-sandbox.fedex.com/oauth/token';
$access_headers = ['Content-Type' => 'application/x-www-form-urlencoded'];
$access_fields = "grant_type=client_credentials&client_id=...&client_secret=...";
$resp = curl_me($access_url, $access_headers, $access_fields);
$access_token = json_decode($resp)->access_token;
$rate_url = 'https://apis-sandbox.fedex.com/rate/v1/rates/quotes';
$rate_hdrs = [
'Authorization' => 'Bearer '.$access_token,
'X-locale' => 'en_US',
'Content-Type' => 'application/json'
];
$rate_flds = '{
"accountNumber": {
"value": "..."
},
"requestedShipment": {
"shipper": {
"address": {
"streetLines": [
"..."
],
"city": "...",
"stateOrProvinceCode": "...",
"postalCode": "...",
"countryCode": "US",
"residential": false
}
},
"recipient": {
"address": {
"postalCode": "...",
"countryCode": "US"
}
},
"shipDateStamp": "2022-12-06",
"pickupType": "DROPOFF_AT_FEDEX_LOCATION",
"requestedPackageLineItems": [{
"declaredValue": {
"amount": 123,
"currency": "USD"
},
"weight": {
"units": "LB",
"value": 12
},
"dimensions": {
"length": 12,
"width": 12,
"height": 12,
"units": "IN"
}
}],
"documentShipment": false,
"packagingType": "YOUR_PACKAGING",
"groupShipment": true
},
"carrierCodes": [
"FDXE"
]
}';
$field = build_post_fields($rate_flds);
$resp = curl_me($rate_url, $rate_hdrs, $field);
var_dump($resp);
Here are the two functions I'm using:
function curl_me($url, $headers, $postfields){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
$response = curl_exec($ch);
echo curl_error($ch);
curl_close($ch);
return $response;
}
function build_post_fields( $data,$existingKeys='',&$returnArray=[]){
if(($data instanceof CURLFile) or !(is_array($data) or is_object($data))){
$returnArray[$existingKeys]=$data;
return $returnArray;
}
else{
foreach ($data as $key => $item) {
build_post_fields($item,$existingKeys?$existingKeys."[$key]":$key,$returnArray);
}
return $returnArray;
}
}
The second function is from Yisrael Dov's answer to this question.
When I used the first function to get the access token, it worked flawlessly. But I can't figure out why the second time I used it responded with: string(176) "��� �#��W朢%jނ��d�]���(R������I���oFgHY�ת��r҆IH/"�Eq�zi����MJ{��6� �..."
I tried all kinds of different was of encoding and decoding the JSON string. But I get gibberish every time.
I've tried running that gibberish through various decoders, but of course they all returned NULL.
I was expecting at least some kind of error or warning.
Any ideas would be appreciated.
$rate_hdrs = [
'Authorization: Bearer '.$access_token,
'X-locale: en_US',
'Content-Type: application/json',
];
look this: PHP cURL custom headers
Thanks to everyone for the awesome input!
I'm new to CURL, so pardon my not recognizing these mistakes.
I combined Sammitch's comments with Walter KT's answer.
Sammitch was right: the response was gzip encoded. I added curl_setopt($ch, CURLOPT_ENCODING, "gzip"); to my function, and finally got the response (with some handy errors to work through).
I also got rid of the build_post_fields() function.

Error getting a json response from http request

I am trying to get the response from an http request from the Hunter API.
The url is something like this :
https://api.hunter.io/v2/email-finder?domain=mydomain&api_key=myapikey&first_name=myfirstname&last_name=myname
And the response is something like this :
{
"data": {
"email": "emailfound#domain.tld",
"score": 68,
"domain": "domain.tld",
"sources": [
{
"domain": "domain.tld",
"uri": "http://somedomain.tld/",
"extracted_on": "2017-04-04"
}
]
},
"meta": {
"params": {
"first_name": "myfirstname",
"last_name": "mylastname",
"full_name": null,
"domain": "domain.tld",
"company": null
}
}
}
Here is what I am doing in my controller :
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($curl);
curl_close($curl);
// return response
$json = new JsonResponse();
$datas = $json->setData($response);
return json_encode($datas);
And here is what json_encode($datas) returns :
{"headers":{}}
I precise that I am working with Symfony3 and testing on my OVH serveur (Performance offer).
Any idea where does come from this response ? and why I am not getting the real response ? Thanks !
As per my comment,
Instead of using CURL (Which is a much harder system to deal with IMO), you should use file_get_contents() like so:
$json = file_get_contents($url);
$obj = json_decode($json,true);
Try this:
$json = file_get_contents('https://api.hunter.io/v2/email-finder?domain=mydomain&api_key=myapikey&first_name=myfirstname&last_name=myname');
$data = json_encode($json,true)
var_dump($data);

What would be the correct JSON argument to update roll and connections in street view publish API

I am trying to update pose.roll and connections along with other UpdateMasks but only updates heading and pitch, pose.roll remain NULL.
Here is php code
<?php
$ch_a = curl_init();
curl_setopt($ch_a, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch_a, CURLOPT_HTTPHEADER, array('Authorization: Bearer '.$_SESSION['access_token'], 'Content-Type: application/json'));
curl_setopt($ch_a, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch_a, CURLOPT_URL, 'https://streetviewpublish.googleapis.com/v1/photo/'.$photoId.'?key='.$config['apikey'].'&updateMask=pose.heading,pose.pitch,pose.roll,connections');
curl_setopt($ch_a, CURLOPT_POSTFIELDS, '{"pose":{"heading": 145.9086485977801, "pitch":3.219209274200196, "roll":"0"}}');
$url = curl_exec($ch_a);
curl_close($ch_a);
echo $url;
?>
I think this is an expected behavior.
I've tried this sample request using the Try It! in the documentation.
{
"pose": {
"roll": 0,
"latLngPair": {
"longitude": 118.04944440000001,
"latitude": 12.5343694
},
"heading": 90,
"pitch": 5.0999984741210938
}
}
Then I received this 200 response:
{
"photoId": {
"id": "ID"
},
"pose": {
"latLngPair": {
"latitude": 12.5343694,
"longitude": 118.04944440000001
},
"heading": 90,
"pitch": 5.0999984741210938
}
}
If you updated roll to 0, then the value will be null. When the value of roll is >0, it will appear in the response. Example:
{
"photoId": {
"id": "ID"
},
"pose": {
"latLngPair": {
"latitude": 12.5343694,
"longitude": 118.04944440000001
},
"heading": 90,
"pitch": 5.0999984741210938,
"roll": 5
}
}

Facebook Messenger Chatbot - I can't answer to a postback

I'm writing a bot for Facebook in PHP. I'm able to send text and send and answer to quickreplies. However is impossible to me to answer to a postback. I use ngrok for localhost testing purposes but I know that it's not that the problem since 1. it doesn't work on my vps neither 2. All the other functionalities work as expected.
My code for sending the post-back :
$jsonData = '{
"recipient":{
"id":"'.$sender.'"
},
"message":{
"attachment":{
"type":"template",
"payload":{
"template_type":"button",
"text":"What do you want to do next?",
"buttons":[
{
"type":"postback",
"title":"Start Chatting",
"payload":"USER_DEFINED_PAYLOAD"
}
]
}
}
}
}';
$url = 'https://graph.facebook.com/v2.6/me/messages?access_token='.$access_token;
$ch = curl_init($url);
//Tell cURL that we want to send a POST request.
curl_setopt($ch, CURLOPT_POST, 1);
//Attach our encoded JSON string to the POST fields.
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
//Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
//Execute the request
if(!empty($message_body['message'])){
$result = curl_exec($ch);
}
Then, when I receive the post-back I get this from FB messenger :
{
"object": "page",
"entry": [
{
"id": "590445400970275",
"time": 1494251031827,
"messaging": [
{
"recipient": {
"id": "590445400970275"
},
"timestamp": 1494251031827,
"sender": {
"id": "1075794782546272"
},
"postback": {
"payload": "USER_DEFINED_PAYLOAD"
}
}
]
}
]
}
and my code to parse it :
$input = json_decode(file_get_contents('php://input'), true);
$message_body = $input['entry'][0]['messaging'][0];
$sender = $message_body['sender']['id'];
if (isset($message_body['postback'])){
//Reception d'un postback
$postback = $message_body['postback']['payload'];
if ($postback == "USER_DEFINED_PAYLOAD"){
// The JSON data.
$jsonData = '{
"recipient":{
"id":"'.$sender.'"
},
"message":{
"text":"messagetoreply"
}
}';
}
}
This is sent by the curl function as the message before.
However the messenger never receives an answer :
Could anyone help me finding out where's the problem ?
Thank you very much
There was a mistake in my code at this part :
if(!empty($message_body['message'])){
$result = curl_exec($ch);
}
since the $message_body var is not 'message' but a 'postback', the curl was not sending the response.

Illegal string offset 'name', code worked with example json response

I'm currently working on a website to control my SmartBulbs at home via a webpage. To do so I use the provided API.
I tried my code with an example json response from the manufacturers website. Everything worked fine and all the lights listed in the example response where represented by divs with the names of the lights.
When I tried my code at home (called the API like in the code) I got a valid response but I also got an error which stated Illegal string offset 'label'. What am I doing wrong?
Everything worked fine when I used the example response. The response when I use the API looks the same for me. Shouldn't it also work then?
You can find everything down below. If you need some mor information just ask :)
php code
function get_lights(){
$link = "https://api.lifx.com/v1/lights/all";
$authToken = "I inserted my token here and got a valid response";
$ch = curl_init($link);
$headers = array('Authorization: Bearer ' . $authToken);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, $headers);
$response = curl_exec($ch);
$json = json_decode($response, true);
$html = null;
foreach($json as $object)
{
$html.= '<div class="element" onclick="get_info();">' . $object['label'] . '</div>';
}
return $html;
}
example response
[
{
"id": "d3b2f2d97452",
"uuid": "8fa5f072-af97-44ed-ae54-e70fd7bd9d20",
"label": "Left Lamp",
"connected": true,
"power": "on",
"color": {
"hue": 250.0,
"saturation": 0.5,
"kelvin": 3500
},
"infrared": "1.0",
"brightness": 0.5,
"group": {
"id": "1c8de82b81f445e7cfaafae49b259c71",
"name": "Lounge"
},
"location": {
"id": "1d6fe8ef0fde4c6d77b0012dc736662c",
"name": "Home"
},
"last_seen": "2015-03-02T08:53:02.867+00:00",
"seconds_since_seen": 0.002869418,
"product": {
"name": "LIFX+ A19",
"company": "LIFX",
"identifier": "lifx_plus_a19",
"capabilities": {
"has_color": true,
"has_variable_color_temp": true,
"has_ir": true,
"has_multizone": false
}
}
}
]
my API response
[
{
"id":"d073d513bfd6",
"uuid":"02ea5835-9dc2-4323-84f3-3b825419008d",
"label":"MainLight",
"connected":true,
"power":"on",
"color":{
"hue":27.581597619592586,
"saturation":0.0,
"kelvin":2500
},
"zones":null,
"brightness":0.49999237048905165,
"group":{
"id":"d5aa0e1180293e0af56607cbe47f4940",
"name":"MyRoom"
},
"location":{
"id":"451e4b376a38062cdd10c54ab2698975",
"name":"My Home"
},
"product":{
"name":"Color 1000",
"identifier":"lifx_color_a19",
"company":"LIFX",
"capabilities":{
"has_color":true,
"has_variable_color_temp":true,
"has_ir":false,
"has_multizone":false
}
},
"infrared":null,
"last_seen":"2017-02-18T21:40:58.164+00:00",
"seconds_since_seen":0.001675218
}
]
You're setting the wrong option for your cURL handle:
$ch = curl_init($link);
$headers = array('Authorization: Bearer ' . $authToken);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);

Categories