How do I get coordinates from twitter geo/search? There are four coordinates in the JSON tree, but the result is array. How to? Thanks.
API URL : https://api.twitter.com/1/geo/search.json?query=tokyo //での取得結果
json[result]['places']['0']['name']=Tokyo
json[result]['places']['0']['bounding_box']['type']=Polygon
json[result]['places']['0']['bounding_box']['coordinates'][0][0]=Array //Array data.
JSON tree
{
"result": {
"places": [
{
"name": "Tokyo",
"bounding_box": {
"type": "Polygon",
"coordinates": [
[
[
138.942806388889,
24.222885
],
[
142.248202222222,
24.222885
],
[
142.248202222222,
35.8986897222222
],
[
138.942806388889,
35.8986897222222
]
]
]
},
... // a long tree, something not important, hiden...
update
<?php
header('Content-type:text/html; charset=utf-8');
$url = "https://api.twitter.com/1/geo/search.json?query=tokyo";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Host: api.twitter.com'));
$body = curl_exec($ch);
curl_close ($ch);
$data = json_decode($body, true);
foreach ($data['result']['places'] as $data) {
echo $data['bounding_box']['coordinates']['0']['0'].'<br />'; //array
}
?>
If you have JSON contents, you can use json_decode() function - it'll return nice array you can read.
http://php.net/manual/en/function.json-decode.php
Related
Following a successful response from an API Request to M-PESA where the following JSON code is printed:
{ "MerchantRequestID":"2690XXXXXXX", "CheckoutRequestID":"xx_XX_2779308581984", "ResponseCode": "0", "ResponseDescription":"Success. Request accepted for processing", "CustomerMessage":"Success. Request accepted for processing" }
I would like to access the data sent to my callback url: https://xxxxxxxxxxxxxxxxx.ngrok.io/processL/transact.php . Despite expecting the code to change accordingly upon cancellation or payment, nothing happens although when I inspect the response on the ngrok local tunnel online interface, I see my expected results only that I do not know how to acquire and generate some action with them. Below is the code making the API Request and the results which I expect to be sent to my call back url but in vain.
<!-- transact.php -->
<?php
if (isset($_POST['submit'])) {
$Passkey = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$Amount= $_POST['amt'];
$BusinessShortCode = '174379';
$PartyA =$_POST['phone'];
$AccountReference =$_POST['name'];
$TransactionDesc = 'test';
$Timestamp =date('YmdHis');
$Password = base64_encode($BusinessShortCode.$Passkey.$Timestamp);
$headers=['Content-Type:application/json; charset=utf8'];
$initiate_url='https://sandbox.safaricom.co.ke/mpesa/stkpush/v1/processrequest';
$callBackURL ='https://xxxxxxxxxxxxxxxxx.ngrok.io/processL/transact.php';
function accessToken() {
$ConsumerKey = 'ubYsxxxxxxxxxxxxx';
$ConsumerSecret = 'xxxxxxxxxxxxx';
$credentials = base64_encode($ConsumerKey.":".$ConsumerSecret);
$url = "https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array("Authorization: Basic ".$credentials,"Content-Type:application/json"));
curl_setopt($curl, CURLOPT_HEADER, false);
// curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$curl_response = curl_exec($curl);
$access_token=json_decode($curl_response);
curl_close($curl);
return $access_token->access_token;
}
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $initiate_url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json','Authorization:Bearer '.accessToken()));
$curl_post_data = array(
'BusinessShortCode' =>$BusinessShortCode,
'Password' => $Password,
'Timestamp' => $Timestamp,
'TransactionType' => 'CustomerPayBillOnline',
'Amount' => $Amount,
'PartyA' => $PartyA,
'PartyB' => $BusinessShortCode,
'PhoneNumber' => $PartyA,
'CallBackURL' => $callBackURL,
'AccountReference' => $AccountReference,
'TransactionDesc' => $TransactionDesc
);
$data_string = json_encode($curl_post_data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data_string);
$curl_response = curl_exec($curl);
print_r($curl_response."<br>");
}
Upon acceptance of payment:
{
"Body": {
"stkCallback": {
"MerchantRequestID": "xxxxxxxxxxxxx",
"CheckoutRequestID": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"ResultCode": 0,
"ResultDesc": "The service request is processed successfully.",
"CallbackMetadata": {
"Item": [
{
"Name": "Amount",
"Value": 1
},
{
"Name": "MpesaReceiptNumber",
"Value": "xxxxxxxxxxxxx"
},
{
"Name": "Balance"
},
{
"Name": "TransactionDate",
"Value": 20210927101413
},
{
"Name": "PhoneNumber",
"Value": xxxxxxxxxxxxx
}
]
}
}
}
};
When payment is cancelled:
{
"Body": {
"stkCallback": {
"MerchantRequestID": "xxxxxxxxxxxxx",
"CheckoutRequestID": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"ResultCode": 1032,
"ResultDesc": "Request cancelled by user"
}
}
};
I need some guidance.
The documentation for json_decode() is your friend. If you pass true as the second argument then it returns your JSON data as associative arrays.
$access_token=json_decode($curl_response, true);
// Check the response value
$result = $access_token['Body']['stkCallback']['ResultCode'] ?? null;
if ($result == 0) {
// Success
}
I'm new to PHP and have some trouble trying to delete an item from some data returned by an API
function getData()
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_POSTFIELDS, "");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json',));
$data = curl_exec($ch);
echo $data;
exit();
}
Here is the JSON data, I want to remove the item with Id 11, how can I do this?
{
"Data": [
{
"Id": 11,
"Name": "Name1"
},
{
"Id": 12,
"Name": "Name2"
}
]
}
Decode the data.
Remove the item from the array.
Optionally encode it again as string if needed.
$dataArray = json_decode($data, true);
foreach ($dataArray['Data'] as $key => $item) {
if ($item['Id'] === 11) {
unset($dataArray['Data'][$key]);
}
}
$data = json_encode($dataArray);
it will work
$dataArray = json_decode($data, true);
$dataArray['Data'] = array_filter($dataArray['Data'], function($el){return $el["Id"]<>11;});
$data = json_encode($dataArray);
One way is to re-index by Id and unset it:
$array = array_column(json_decode($data, true)['Data'], null, 'Id'));
unset($array[11]);
Now $array is indexed by Id. If you want to reset it, then:
$array = array_values($array);
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 bot replies perfectly but stops working after displaying generic/list template. For other messages like quick replies, buttons, and text messages it works fine. My app was in development mode and I changed it to public but not working. I've attached my code and screenshot herewith.
What's wrong in my code?
API version: v2.10
Facebook Page: https://www.facebook.com/yesira.net
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class BotController extends Controller
{
public function bot(Request $request)
{
$data = $request->all();
//get the user’s id
$id = $data["entry"][0]["messaging"][0]["sender"]["id"];
$senderMessage = $data["entry"][0]["messaging"][0]["message"];
$messageText = $data["entry"][0]["messaging"][0]["message"]["text"];
if(!empty($senderMessage) && $messageText == "hi"){
$this->sendTextMessage($id, "Hi buddy");
}
else if($messageText == "blog") {
$answer = ["attachment"=>[
"type"=>"template",
"payload"=>[
"template_type"=>"generic",
"elements"=>[
[
"title"=>"Migrate your symfony application",
"item_url"=>"https://www.cloudways.com/blog/migrate-symfony-from-cpanel-to-cloud-hosting/",
"image_url"=>"https://www.cloudways.com/blog/wp-content/uploads/Migrating-Your-Symfony-Website-To-Cloudways-Banner.jpg",
"subtitle"=>"Migrate your symfony application from Cpanel to Cloud.",
"buttons"=>[
[
"type"=>"web_url",
"url"=>"www.cloudways.com",
"title"=>"View Website"
],
[
"type"=>"postback",
"title"=>"Start Chatting",
"payload"=>"Even want some more? say me!"
]
]
]
]
]
]];
$response = [
'recipient' => [ 'id' => $id ],
'message' => $answer
];
$this->reply($response);
}
else{
$this->sendTextMessage($id, "Hello world!");
}
}
private function reply($jsonData)
{
$ch = curl_init('https://graph.facebook.com/v2.6/me/messages?access_token=' . env("PAGE_ACCESS_TOKEN"));
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($jsonData));
curl_exec($ch);
curl_close($ch);
}
private function sendTextMessage($recepientId, $messageText)
{
$messageData = [
"recipient" => [
"id" => $recepientId,
],
"message" => [
"text" => $messageText,
]
];
$ch = curl_init('https://graph.facebook.com/v2.6/me/messages?access_token=' . env("PAGE_ACCESS_TOKEN"));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, ["Content-Type: application/json"]);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($messageData));
curl_exec($ch);
curl_close($ch);
}
}
Probably you aren't getting the new events because the Platform keeps retrying. You need to respond to the webhook event with a 200OK.
I am trying to post data using curl to a api, it has to be in JSON.
Now I have an multidimensional array that i need to pass along with the post. But i keep getting the same error all over, and i can not figure out why.
I've tried every possible way I could imagine.
This is the example that i need to send to the API:
POST /orders/ HTTP/1.1
Authorization: Basic aHVudGVyMjo=
Content-Type: application/json
{
"currency": "EUR",
"amount": 99,
"return_url": "http://www.example.com/",
"transactions": [
{
"payment_method": "ideal",
"payment_method_details": {
"issuer_id": "INGBNL2A"
}
}
]
}
So my array I made like this:
$post_fields = array();
$post_fields["currency"] = "EUR";
$post_fields["amount"] = 99;
$post_fields["return_url"] = "http://website_url.nl/return_page/";
$post_fields["transactions"]["payment_method"] = "ideal";
$post_fields["transactions"]["payment_method_details"]["issuer_id"] = "INGBNL2A";
Then the follinw i do is converting the array to a JSON string by this code:
$data_string = json_encode($post_fields);
So far is everything OK, but then i am going to post the data to the API by using the following code:
$url = "https://api.kassacompleet.nl/v1/orders/";
$curl_header = array();
$curl_header[] = "Authorization: Basic ".base64_encode("$auth_code:");
$curl_header[] = "Content-type: application/json";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $curl_header);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 180);
curl_setopt($ch, CURLOPT_TIMEOUT, 180);
$output = curl_exec($ch);
curl_close($ch);
print_r($output);
And this always results in an error that looks as the following:
{ "error": { "status": 400, "type": "", "value": "{u'payment_method': u'ideal', u'payment_method_details': {u'issuer_id': u'INGBNL2A'}} is not of type u'array'" } }
Could someone tell me where it comes from and what I am doing wrong?
Is it the format of the array or what is it?
From checking the API documentaion
It looks like transactions should be an array.
$post_fields = array();
$post_fields["currency"] = "EUR";
$post_fields["amount"] = 99;
$post_fields["return_url"] = "http://website_url.nl/return_page/";
$post_fields["transactions"][0]["payment_method"] = "ideal";
$post_fields["transactions"][1]["payment_method_details"]["issuer_id"] = "INGBNL2A";
echo '<pre>'.json_encode($post_fields).'</pre>';
/* outputs...
{
"currency":"EUR",
"amount":99,
"return_url":"http:\/\/website_url.nl\/return_page\/",
"transactions":[
{
"payment_method":"ideal",
"payment_method_details":{
"issuer_id":"INGBNL2A"
}
}
]
}
*/
I suggest that param "issuer_id" should be an array, in that case try
...
$post_fields["transactions"]["payment_method_details"]["issuer_id"] = array("INGBNL2A");
...