I have integrated the Wepay payment gateway. But I have facing a problem to pass json object to wepay. It always shows a incorrect json format. Please look at the below code.
$forca_a = array(
'debit_opt_in'=>true
);
$forca = json_encode($forca_a,JSON_FORCE_OBJECT);
$wepay_create_array = array(
'name' =>"xxxx",
'description' => "xxxxxxxxx xxxx",
'callback_uri' => "xxxxxxx",
'country' => "CA",
'currencies' => array('CAD'),
'country_options' => $forca,
'rbits'=> array(
array(
'receive_time'=>strtotime("now"),
'type' =>'website_uri',
'source' => 'partner_database',
'properties'=> array('uri'=>xxxxx)
)
)
);
If I won't pass the country_options, its seems to working but If I pass this parameter, it always give me an error says "Incorrect JSON format".
I sent an email to wepay help center. They told me that, you are passing the string "country_options":"{"debit_opt_in":true}" <--- this is a string Instead of "country_options":{"debit_opt_in":true} <--- this is a JSON object. So I'm confused. I have no idea how do I pass the JSON object. There is only way and is json_encode($object).
hey use below code to get proper json
<?php
$forca_a = array(
'debit_opt_in'=>true
);
// $forca = json_encode($forca_a);
$wepay_create_array = array(
'name' =>"xxxx",
'description' => "xxxxxxxxx xxxx",
'callback_uri' => "xxxxxxx",
'country' => "CA",
'currencies' => array('CAD'),
'country_options' => $forca_a,
'rbits'=> array(
array(
'receive_time'=>strtotime("now"),
'type' =>'website_uri',
'source' => 'partner_database',
'properties'=> array('uri'=>'xxxxx')
)
)
);
print_r(json_encode($wepay_create_array));
?>
this code will give following json output
{
"name": "xxxx",
"description": "xxxxxxxxx xxxx",
"callback_uri": "xxxxxxx",
"country": "CA",
"currencies": ["CAD"],
"country_options": {
"debit_opt_in": true
},
"rbits": [{
"receive_time": 1461561030,
"type": "website_uri",
"source": "partner_database",
"properties": {
"uri": "xxxxx"
}
}]
}
You have no need to make:
$forca = json_encode($forca_a,JSON_FORCE_OBJECT);
before you put it to $wepay_create_array.
Before sending request, i think, you make json_encode($wepay_create_array), and yes, after that you will have 'string' for country_options key.
Related
I am trying to hit a POST API Endpoint with Guzzle in PHP (Wordpress CLI) to calculate shipping cost. The route expects a RAW JSON data in the following format:
{
"startCountryCode": "CH"
"endCountryCode": "US",
"products": {
"quantity": 1,
"vid": x //Variable ID
}
}
Link to the API I am consuming: https://developers.cjdropshipping.com/api2.0/v1/logistic/freightCalculate
$body = [
"endCountryCode" => "US",
"startCountryCode" => "CN",
"products" => [
'vid' => $vid,
'quantity' => 1
],
];
$request = $this->client->request(
'POST', 'https://developers.cjdropshipping.com/api2.0/v1/logistic/freightCalculate',
[
'headers' => [
'CJ-Access-Token' => $this->auth_via_cj(), // unnecessary, no auth required. Ignore this header
],
'body' => json_encode( $body )
],
);
I've also tried using 'json' => $body instead of the 'body' parameter.
I am getting 400 Bad Request error.
Any ideas?
Try to give body like this.
"json" => json_encode($body)
I spent so many hours on this to just realise that products is actually expecting array of objects. I've been sending just a one-dimensional array and that was causing the 'Bad Request' error.
In order to fix this, just encapsulate 'vid' and 'quantity' into an array and voila!
You don't need to convert data in json format, Guzzle take care of that.
Also you can use post() method of Guzzle library to achieve same result of request. Here is exaple...
$client = new Client();
$params['headers'] = ['Content-Type' => 'application/json'];
$params['json'] = array("endCountryCode" => "US", "startCountryCode" => "CN", "products" => array("vid" => $vid, "quantity" => 1));
$response = $client->post('https://developers.cjdropshipping.com/api2.0/v1/logistic/freightCalculate', $params);
Sorry for the bad title, but I don't know how to create following JSON in PHP:
{
"id":"1",
"method":"getData",
"params":{
"options":{
"element":{
"id":"1a_ext",
"type":1,
"keyType":"externalkey"
},
"moreInfo":true,
"userFields":[
"id",
"name",
"longname",
"externalkey"
]
}
},
"jsonrpc":"2.0"
}
I don't know to do the part after "params" (how do I "put" options "into" params) - for the other parts I know what I have to do:
public static function getData(){
$json = array(
"id" => self::id(),
"method" => "getData",
"params" => array(
"id" => self::$userid,
"type" => self::$type
),
"jsonrpc" => "2.0"
);
$json = json_encode($json, true);
return self::request($json);
}
I would really appreciate your help, thanks!
You directly can assign to the params keys like
$json['params']['options'] = $your_options;
Full version of your code as an example
public static function getData(){
$json = array(
"id" => self::id(),
"method" => "getData",
"params" => array(
"id" => self::$userid,
"type" => self::$type
),
"jsonrpc" => "2.0"
);
# add something to param index
$json['params']['options'] = $your_options;
$json = json_encode($json, true);
return self::request($json);
}
You can create the this in array format in PHP and then JSON encode:
$arr = [
'id' => 1,
'method' => 'getData',
'params' => [
'options' => [
'element' => [
'id' => '1a_ext',
'type' => 1,
'keyType' => 'externalKey'
],
'moreInfo' => true,
'userFields' => [
'id',
'name',
'longname',
'externalKey'
]
]
],
'jsonrpc' => '2.0'
];
$json = json_encode($arr);
Instead of spoonfeeding, i would like to help related, Whenever if you find difficulties to create an array representation of a JSON then you should use var_export(array, true) the second parameter must be true to return the variable representation instead of outputting it
<?php
$json_str = '{
"id": "1",
"method": "getData",
"params": {
"options": {
"element": {"id": "1a_ext", "type": 1, "keyType": "externalkey"},
"moreInfo": true,
"userFields": ["id", "name", "longname", "externalkey"]
}
},
"jsonrpc": "2.0"
}';
$json_arr = var_export(json_decode($json_str, true), true);
print_r($json_arr);
check the output here https://paiza.io/projects/eUZZDsTsSFSM4m9WMl05Ow
$json_arr is an array representation for your JSON, now you can dynamic the array values
I am getting the JSON output below:
{
"clientCorrelator": "58a1acaf3ebf0",
"referenceCode": "REF-12345",
"endUserId": "263774705932",
"transactionOperationStatus": "Charged",
"paymentAmount": {
"0": {
"amount": 34,
"currency": "USD",
"description": "Ecofarmer Bulk Sms Online payment"
}
},
"chargeMetaData": {
"channel": "WEB",
"purchaseCategoryCode": "Online Payment",
"onBeHalfOf": "Paynow Topup"
},
"merchantCode": "42467",
"merchantPin": "1357",
"merchantNumber": "771999313"
}
I want to get the output below but somehow my php to JSON object conversion is turning the "charginginformation" key to "0".
$payment_amount = array(
$charginginformation = array(
'amount' => 34,
'currency' => 'USD',
'description' => 'Ecofarmer Bulk Sms Online payment'
)
);
$charge_data = array(
'channel' => 'WEB',
'purchaseCategoryCode' => 'Online Payment',
'onBeHalfOf' => 'Paynow Topup'
);
//API Url
$url = '';
//Initiate cURL.
$ch = curl_init($url);
//The JSON data.
$jsonData = array(
'clientCorrelator' => $u_id,
'referenceCode' => 'REF-12345',
'endUserId' => '263774705932',
'transactionOperationStatus' => 'Charged',
'paymentAmount' => $payment_amount,
'chargeMetaData' => $charge_data,
'merchantCode' => '42467',
'merchantPin' => '1357',
'merchantNumber' => '771999313'
);
//Encode the array into JSON.
$jsonDataEncoded = json_encode($jsonData, JSON_FORCE_OBJECT);
How can I stop the json_encode from changing the key?
Your issue is here:
$payment_amount = array(
//this is essentially array("cat", "dog", "etc");
$charginginformation = array(
'amount' => 34,
'currency' => 'USD',
'description' => 'Ecofarmer Bulk Sms Online payment'
)
);
You are adding an element to an array with a numeric index
To get this to work do
$payment_amount = array(
"charginginformation" => array(
//array data
)
);
I'm working with a fly web service.I should to be able to create following json format and send to the server :
{
"FareSourceCode": "313139353639393726323426363636323231",
"SessionId": "53a2210f-b151-4aa1-bef0-3db2dbe71565",
"TravelerInfo": {
"PhoneNumber": "02012345678",
"Email": "Sales#partocrs.com",
"AirTravelers": [
{
"DateOfBirth": "1990-11-01T00:00:00",
"Gender": 0,
"PassengerType": 1,
"PassengerName": {
"PassengerFirstName": "John",
"PassengerLastName": "Smith",
"PassengerTitle": 0
},
"Passport": {
"Country": "US",
"ExpiryDate": "2020-05-06T00:00:00",
"PassportNumber": "AB1234567"
},
"NationalId": "0012230877",
"Nationality": "US",
"ExtraServiceId": [
"sample string 1"
],
"FrequentFlyerNumber": "123456789",
"SeatPreference": 0,
"MealPreference": 0
}
]
}
}
I use SoapClient in php7 with this code :
<?php
$PassengerData = //Get passengers informations from mysql
$AirTravelers = array();
foreach ($PassengerData as $p) {
$PassengerType = 'Adt'; //Adult
$PassengerTitle = ($p->sex) ? 'Mrs' : 'Mr';
$AirTravelers = [
'DateOfBirth' => $p->age,
'Gender' => $p->sex ? 'Female' : 'Male',
'PassengerType' => $PassengerType,
'PassengerName' => [
'PassengerFirstName' => $p->efname,
'PassengerLastName' => $p->elname,
'PassengerTitle' => $PassengerTitle,
],
'Passport' => [
'Country' => 'IR',
'ExpiryDate' => $p->passport_expire,
'PassportNumber' => $p->passport_number,
],
'NationalId' => $p->ncode,
'Nationality' => 'IR',
'SeatPreference' => 'Any',
'MealPreference' => 'Any',
];
}
$client = new \SoapClient($ServerHttp);
$session = $client->CreateSession(array("rq" => [ "OfficeId" => $PartoOfficeId, "UserName" => $PartoUserName, "Password" => $PartoPassword]));
$AirBook = $client->AirBook(
array("rq" => [
'FareSourceCode' => $FareSourceCode,
'SessionId' => $session->CreateSessionResult->SessionId,
'TravelerInfo' => ['PhoneNumber' => $current_user_data->mobile,
'Email' => $current_user_data->user_name,
'AirTravelers' =>$AirTravelers
]
]
)
);
But this code can't make correct json format.Because php output json like this :
"AirTravelers": **[**{...}**]**
When i see json log(with json_encode):
json_encode([
'FareSourceCode' => $FareSourceCode,
'SessionId' => $session->CreateSessionResult->SessionId,
'TravelerInfo' => ['PhoneNumber' => $current_user_data->mobile,
'Email' => $current_user_data->user_name,
'AirTravelers' => $AirTravelers
]
])
It is like this (php output json):
"AirTravelers": **{**
And When i use this code :
json_encode([
'FareSourceCode' => $FareSourceCode,
'SessionId' => $session->CreateSessionResult->SessionId,
'TravelerInfo' => ['PhoneNumber' => $current_user_data->mobile,
'Email' => $current_user_data->user_name,
'AirTravelers' => **[**$AirTravelers**]**
]
])
Json output format were as follows:
$AirTravelers = **[**{....}]**strong text**
My question is :How can i send correct json format to this web service?
I use json_encode in my php request but it doesn't work and when i use :
$AirBook = $client->AirBook(
array("rq" => [
'FareSourceCode' => $FareSourceCode,
'SessionId' => $session->CreateSessionResult->SessionId,
'TravelerInfo' => ['PhoneNumber' => $current_user_data->mobile,
'Email' => $current_user_data->user_name,
'AirTravelers' =>[$AirTravelers]
]
]
)
);
I receive this error in php :
Fatal error: Uncaught SoapFault exception: [a:DeserializationFailed ] The formatter threw an exception while trying to deserialize the message: There was an error while trying to deserialize parameter http://tempuri.org/:rq. The InnerException message was 'There was an error deserializing the object of type ServiceModel.Request.AirBook. The value '1988-11-16 00:00:00' cannot be parsed as the type 'DateTime'.'. Please see InnerException for more details. in C:\wamp64 \www\paradise\wp-content\plugins\amir_traveler\fly\fly_functions.php on line 341
SoapFault: The formatter threw an exception while trying to deserialize the message: There was an error while trying to deserialize parameter http://tempuri.org/:rq. The InnerException message was 'There was an error deserializing the object of type ServiceModel.Request.AirBook. The value '1988-11-16 00:00:00' cannot be parsed as the type 'DateTime'.'. Please see InnerException for more details. in C:\wamp64\www\paradise\wp-content\plugins\amir_traveler\fly\fly_functions.php on line 341
I need to write a new geoJSON feature to a data.json file using php. Right now I'm writing my data to the file like so:
<?php
// Read from json file
$jsondata = json_decode( file_get_contents('data.json') );
// Add the new data
$jsondata []= array(
'measure_location'=> $_POST["measure_location"],
'measure_type'=> $_POST["measure_type"],
'measurement'=> $_POST["measurement"],
'note_text'=> $_POST["note_text"]
);
// encodes the array into a string in JSON format (JSON_PRETTY_PRINT - uses whitespace in json-string, for human readable)
$jsondata = json_encode($jsondata, JSON_PRETTY_PRINT);
// saves the json string in "data.json" (in "dirdata" folder)
// outputs error message if data cannot be saved
if(file_put_contents('data.json', $jsondata));
?>
And this is what the data then looks like in data.json:
{
"measure_location": "52.370611247493486, 4.91587221622467",
"measure_type": "negative",
"measurement": "violence",
"note_text": ""
}
Could I adjust my PHP code to make the data look like so:
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [
"4.91587221622467",
"52.370611247493486"
]
},
"properties": {
"type": "negative",
"input": "violence",
"note": ""
}
}
Got the answer thanks to charlietfl. Changed the php code to:
<?php
// Read from json file
$jsondata = json_decode( file_get_contents('data.json') );
// Add the new data
$jsondata [] = array(
'type' => 'Feature',
'geometry' => array(
'type' => 'Point',
'coordinates' => $_POST["measure_location"],
),
'properties' => array(
'type' => $_POST["measure_type"],
'input' => $_POST["measurement"],
'note' => $_POST["note_text"],
)
);
// encodes the array into a string in JSON format (JSON_PRETTY_PRINT - uses whitespace in json-string, for human readable)
$jsondata = json_encode($jsondata, JSON_PRETTY_PRINT);
// saves the json string in "data.json" (in "dirdata" folder)
// outputs error message if data cannot be saved
if(file_put_contents('data.json', $jsondata));
?>
I cannot the code that works for you. I have tried many times. It produced a wrong format JSON. The correct code should be,
$jsondata -> features [] = array(
'type' => 'Feature',
'geometry' => array(
'type' => 'Point',
'coordinates' => $_POST["measure_location"],
),
'properties' => array(
'type' => $_POST["measure_type"],
'input' => $_POST["measurement"],
'note' => $_POST["note_text"],
)
);