I'm using the FXHash API to access listings with this query:
query Listings($sort: ListingsSortInput) {
listings(sort: $sort) {
amount
createdAt
price
issuer {
name
}
objkt {
name
}
}
}
$options = '{
"sort": {
"createdAt": "DESC"
}
}';
I'd like to use the query above in PHP with the sort by createdAt options. How can I fit this query in to my cURL with the sort options? I don't understand how to add the $options variable into the query. Thanks for the help!
$url = 'https://api.fxhash.xyz/graphql';
$curl = curl_init();
$queryData = array();
$data = array();
$queryData = '{
listings {
amount
createdat
price
issuer {
name
}
objkt {
name
}
}
}';
$data["query"] = $queryData;
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, TRUE);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($curl, CURLOPT_HEADER, FALSE);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json'
));
You must add the POST request variables as a JSON map.
Try something like this:
$queryData = 'query Listings($sort: ListingsSortInput) {
listings(sort: $sort) {
amount
createdAt
price
issuer {
name
}
objkt {
name
}
}
}';
$options = '{
"sort": {
"createdAt": "DESC"
}
}';
$data["query"] = $queryData;
$data["variables"] = $options;
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);
how do I have to "translate" the following curl command into a valid php curl function?
curl -X POST
-F "images_file=#fruitbowl.jpg"
-F parameters=%7B%22classifier_ids%22%3A%5B%22testtype_205919966%22%5D%2C%22threshold%22%3A0%7D
'https://gateway-a.watsonplatform.net/visual-recognition/api/v3/classify?api_key={key}&version=2016-05-20'"
It seems that I'm doing something wrong and I can't figure out the problem:
$method = 'POST'
$url = 'https://gateway-a.watsonplatform.net/visual-recognition/api/v3/classify?api_key=<myApiKey>&version=2016-05-20'
$data = array(
array(<file-information>),
array(<json-string>),
)
$header = array(
'Content-Type: application/json',
'Content-Length: ' . strlen(<json-string>),
)
)
public function send($method, $url, $data = null, $header = null)
{
$curl = curl_init();
switch ($method) {
case "POST":
curl_setopt($curl, CURLOPT_POST, 1);
if ($data) {
$postData = $this->renderPostData($data);
curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
}
break;
}
if($header) {
curl_setopt($curl, CURLOPT_HEADER, 1);
curl_setopt($curl,CURLOPT_HTTPHEADER,$header);
}
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($curl);
}
protected function renderPostData($data)
{
$postData = array();
foreach ($data as $file) {
if ($file['isFile']) {
if(pathinfo($file['path'], PATHINFO_EXTENSION) == 'zip'){
$postData[$file['name']] = new \CURLFile($file['path'], 'application/zip', $file['name']);
}
else {
$postData[$file['name']] = new \CURLFile($file['path'], 'application/octet-stream', $file['name']);
}
} else {
// this contains the json encoded string
$postData[$file['name']] = $file['path'];
}
}
return $postData;
}
I tried several variations and the Watson Visual Recognition API error is now:
{
"custom_classes": 0,
"images": [
{
"error": {
"description": "Invalid image data. Supported formats are JPG and PNG.",
"error_id": "input_error"
}
}
],
"images_processed": 1
}
before it was:
{
"error": {
"code": 400,
"description": "Invalid JSON content received. Unable to parse.",
"error_id": "parameter_error"
},
"images_processed": 0
}
Thank you for your help!
My issue was this line:
$postData[$file['name']] = new \CURLFile($file['path'], 'application/zip', $file['name']);
the last parameter is the $postname. So to fix this issue I had to change this line to:
$postData[$file['name']] = new \CURLFile($file['path'], mime_content_type($file['path']), basename($file['path']));
and it worked - after I also removed the wrong $header completely
:)
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");
...
I add data add Elasticsearch this code:
$data = array("name"=>HelperMC::strToUtf8(trim($name)),
"urlname"=>HelperURL::strToURL(trim($name)),
"price"=>number_format(HelperParser::clearTextFromPrice($price), 2, ',', '.'),
"price_for_filter"=>HelperParser::clearTextFromPrice($price),
"image"=>$imgname,
"description"=>HelperMC::strToUtf8($description),
"keywords"=>HelperMC::strToUtf8($keywords),
"url"=>$k['url'],
"sitemap_id"=>intval($sitemapId),
"shop_id"=>$shop['shop_id'],
"logo"=>$shop['logo'],
"key"=>$hashKey,
"type"=>intval(1),
"shop_rating_count"=>intval($shop['rating_count']),
"shop_rating_point"=>intval($shop['rating_point']),
"created_at"=>date("Y-m-d H:i:s"),
"updated_at"=>date("Y-m-d H:i:s"));
//create elasticsearch index
HelperES::insertEntry(json_encode($data),$hashKey);
My insertEntry Function:
private static $elasticBase = "http://localhost:9200/shopping/items";
public static function insertEntry($data_string,$id = false){
if($id)
$url = self::$elasticBase."/".$id;
else
$url = self::$elasticBase;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL , $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
#$result = curl_exec($ch);
curl_close($ch);
return $result;
}
and my search Function:
public static function search($keyword, $defaultOperator = "OR" ,$start = 0, $size = 25, $from = 0, $to = 10000, $shopsArr = array(),$orderBy = "price", $order = "asc"){
$searchUrl = self::$elasticBase."/_search";
if(count($shopsArr) > 0){
$query = '{
"from" : '.$start.', "size" : '.$size.',
"query" : {
"filtered" : {
"query": {
"query_string": { "query": "'.$keyword.'",
"fields": ["name","urlname"],
"default_operator": "'.$defaultOperator.'"
}
},
"filter" : {
"bool" : {
"must" : {
"terms" : { "sitemap_id" : '.json_encode($shopsArr).' }
},
"must" : {
"range" : {
"price_for_filter" : {
"from" : "'.$from.'",
"to" : "'.$to.'"
}
}
}
}
}
}
},
"sort" : [
{"'.$orderBy.'" : {"order" : "'.$order.'", "mode" : "avg"}}
]
}';
}else{
$query = '{
"from" : '.$start.', "size" : '.$size.',
"query" : {
"filtered" : {
"query": {
"query_string": {
"query": "'.$keyword.'",
"fields": ["name","urlname"],
"default_operator": "'.$defaultOperator.'"
}
},
"filter" : {
"range" : {
"price_for_filter" : {
"from" : "'.$from.'",
"to" : "'.$to.'"
}
}
}
}
},
"sort" : [
{"'.$orderBy.'" : {"order" : "'.$order.'", "mode" : "avg"}}
]
}';
}
echo $query;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL , $searchUrl);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $query);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
#$result = curl_exec($ch);
curl_close($ch);
return $result;
}
But my search results not working.
Example: http://azdanaz.com:9200/shopping/items/_search?q=name:telefon&pretty
working but,
http://www.azdanaz.com/arama/telefon
not working.
Looking at the mapping for your shopping index, it shows that your price_for_filter field is actually a string, not a numeric type. Therefore, your range filter is doing a string comparison, not a numeric comparison. This is filtering out all of your results.
To illustrate, your range is filtering from "0" to "100000". The price_for_filter value of your first expected result is "12.97". When doing a string comparison, "12.97" is greater than "0", however, as a string, it is also greater than "100000", so this result gets filtered out ("12" > "10").
You either need to change the price_for_filter field to be a numeric field, or you need to add a new field that is a numeric type and change your range filter to use that new field.