PHP Http Post request with json response: no valid json - php

If I send the following request to an API, it says, that I use no valid JSON string. How can I transform my JSON in a valid PHP post request? I'm using guzzle:
$client = new Client();
$res = $client->request('POST', 'https://fghfgh', [
'auth' => ['user', 'pw']
]);
$res->getStatusCode();
$res->getHeader('application/json');
$res->getBody('{
"category": "ETW",
"date": "2017-03-02",
"address": {
"nation": "DE",
"street": "abc",
"house_number": "7",
"zip": "80637",
"town": "München"
},
"construction_year": "1932",
"living_area": "117.90",
"elevator": false,
"garages": false
}');

as mentioned in the documentation
you need to pass the required headers to your response object as follows:
$res = $client->request('POST', 'https://fghfgh', [
'auth' => ['user', 'pw'],
'headers' => [
'Content-Type' => 'application/json',
'Accept' => 'application/json',
]
]);

When I let php decode the json it won't give any errors, so the first thing that comes into mind is the München having an umlaut. What happens if you try this without using the umlaut?
Having said that, I recommend you using an PHP array and encoding that into a json string instead of just typing the json string. This is because PHP can check the syntax for the array and you know whether it's right or wrong immediately. If option A doesn't work, this might fix your problem instead.
It would look like this:
$data = [
'category' => 'ETW',
'date' => '2017-03-02',
'address' => [
'nation' => 'DE',
'street' => 'abc',
'house_number' => 7,
'zip' => '80637',
'town' => 'Munchen'
],
'construction_year' => 1932,
'living_area' => '117.90',
'elevator' => false,
'garages' => false,
];
$res->getBody(json_encode($data));

Looks to me like you should be using the json option if your intention is to POST JSON data
$client->post('https://fghfgh', [
'auth' => ['user', 'pw'],
'json' => [
'category' => 'ETW',
'date' => '2017-03-02',
'address' => [
'nation' => 'DE',
'street' => 'abc',
'house_number' => '7',
'zip' => '80637',
'town' => 'München'
],
'construction_year' => '1932',
'living_area' => '117.90',
'elevator' => false,
'garages' => false,
]
]);

Related

How to convert PHP cURL format into Guzzle Laravel Format

currently i'm trying to test some API endpoint use postman. As we know that postman provide us the information to integrate the request into the code in many different languages. So i select code format PHP-cURL on my laravel framework and it works. however i want to convert PHP-cURL format into laravel Guzzle. but didn't work.
here is the PHP-cURL code
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://sandbox.plaid.com/asset_report/create',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS =>'{
"client_id": "xxxx",
"secret": "xxxx",
"access_tokens": ["access-sandbox-xxx"],
"days_requested": 30,
"options": {
"client_report_id": "ENTER_CLIENT_REPORT_ID_HERE",
"webhook": "https://www.example.com/webhook",
"user": {
"client_user_id": "ENTER_USER_ID_HERE",
"first_name": "ENTER_FIRST_NAME_HERE",
"middle_name": "ENTER_MIDDLE_NAME_HERE",
"last_name": "ENTER_LAST_NAME_HERE",
"ssn": "111-22-1234",
"phone_number": "1-415-867-5309",
"email": "ENTER_EMAIL_HERE"
}
}
}',
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json'
),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;
this PHP-cURL format can success run and display the response on my laravel. but when i change to Laravel Guzzle.. it display error. here is the guzzle code
use GuzzleHttp\Client;
$guzzle = new Client;
$getAccestToken = $guzzle->request('POST', 'https://sandbox.plaid.com/asset_report/create', [
'headers' => ['Content-Type' => 'application/json'],
'json' => [
"client_id" => "xxx",
"secret" => "xxx",
"access_token" => [ "access-sandbox-xxx" ] ,
"days_requested" => 30,
"options" => [
"client_report_id" => "ENTER_CLIENT_REPORT_ID_HERE",
"webhook" => "https://www.example.com/webhook",
"user" => [
"client_user_id" => "ENTER_USER_ID_HERE",
"first_name" => "ENTER_FIRST_NAME_HERE",
"middle_name" => "ENTER_MIDDLE_NAME_HERE",
"last_name" => "ENTER_LAST_NAME_HERE",
"ssn" => "111-22-1234",
"phone_number" => "1-415-867-5309",
"email" => "ENTER_EMAIL_HERE"
]
]
]
]);
display error
Client error: POST https://sandbox.plaid.com/asset_report/create resulted in a 400 Bad Request response: { "display_message": null, "documentation_url": "https://plaid.com/docs/?ref=error#invalid-request-errors", "error (truncated...)
What is missing on my guzzle code.
please help.
Laravel has the Http client available which is a wrapper around guzzle:
$response = Http::withToken($token)->post('yourUrl', [ params ]);
dd($response->body());
You should try replacing json with body:
Also, convert the array into valid JSON format.
References: https://stackoverflow.com/a/39525059/5192105
use GuzzleHttp\Client;
$guzzle = new Client;
$getAccestToken = $guzzle->request('POST',
'https://sandbox.plaid.com/asset_report/create', [
'headers' => ['Content-Type' => 'application/json'],
'body' => json_encode([
"client_id" => "xxx",
"secret" => "xxx",
"access_token" => [ "access-sandbox-xxx" ] ,
"days_requested" => 30,
"options" => [
"client_report_id" => "ENTER_CLIENT_REPORT_ID_HERE",
"webhook" => "https://www.example.com/webhook",
"user" => [
"client_user_id" => "ENTER_USER_ID_HERE",
"first_name" => "ENTER_FIRST_NAME_HERE",
"middle_name" => "ENTER_MIDDLE_NAME_HERE",
"last_name" => "ENTER_LAST_NAME_HERE",
"ssn" => "111-22-1234",
"phone_number" => "1-415-867-5309",
"email" => "ENTER_EMAIL_HERE"
]
]
])
]);
i found the answer. i typo
"access_token" => [ "access-sandbox-xxx" ] ,
Should with "tokens"
"access_tokens" => [ "access-sandbox-xxx" ] ,
and it can be run correctly. thank you for all your response.

using php guzzle for PUT with stream and parameters

I'm trying to figure out how to implement the following REST PUT using Guzzle. I've tried using multipart and json, but I'm not sure what the syntax should be for having the parameters with a streamed xml file.
Can anyone help me translate this into a proper query? Below is what I tried so far, but it returns an error because it says the ProjectXML must be included.
$newUri = sprintf('%s/projects/%s/storage', $api_base, $testPid);
$newResp = $client->put($newUri,
[
'headers' => [
'Authorization' => sprintf("HubApi %s", $api_key),
],
'multipart' => [
[
'name' => 'ProjectXml',
'contents' => file_get_contents("xml/$testPid.xml")
],
[
'name' => 'ProjectId',
'contents' => $testPid
],
[
'name' => 'HubUserId',
'contents' => "xxxxxxx-xxxxx-xxxx-xxxxx-xxxxxxxx"
],
[
'name' => 'ProductId',
'contents' => "$(package:ourcompany/ourproducttype)/products/ProductABC123"
],
[
'name' => 'ThemeUrl',
'contents' => "$(package:ourcompany/ourproducttype)/themes/themename-white-Classic"
],
]
]
);
Response:
`400 Bad Request - Validation Error` response:
{"code":"RequestValidationError","message":"'Project Xml' should not be empty."}

Send request parameter from console commands laravel

How can I send request via console commands in laravel 5.1 ? I need to pass API request to controller in same folder project, my first attempt is using guzzle :
$gClient = new \GuzzleHttp\Client(['base_uri' => env('URL_AUTO_CONFIRM_PAYMENT')]);
$res = $gClient->post('api/payment/inquiries',
[
'headers'=> [
'Content-Type' => 'application/json',
'Accept' => 'application/json'
],
'json'=>[
'payment_method' => 'transfer',
'payment_channel' => 'bca',
'account_number' => $row->parameter['accountNo'],
'invoice_id' => $row->parameter['paymentInvoice'],
'amount' => (int)$row->parameter['totalCommission'],
'currency_code' => 'IDR',
'description' => 'Testing'
],
'http_errors' => false
]
);
but I think its not good because in same folder project, which can I call controller directly, but the problem is, my controller has been set to only receive $request not param (my_controller(Request $request)).
So, how can I handle this ? It is ok using guzzle ? Or should I use another alternative ?
Any advice will appreciate.
Thanks
Make a request instance and pass that to the specific controller method.
use Illuminate\Http\Request;
$request = new Request(
[
'payment_method' => 'transfer',
'payment_channel' => 'bca',
'account_number' => $row->parameter['accountNo'],
'invoice_id' => $row->parameter['paymentInvoice'],
'amount' => (int)$row->parameter['totalCommission'],
'currency_code' => 'IDR',
'description' => 'Testing'
],
[],
[],
[],
[],
['CONTENT_TYPE' => 'application/json']
);
$response = $controller->edit($request);

PHP Guzzle POST Request Returning Null

I'm racking my brains over this - the request goes fine in Postman, but I can't access the body using Guzzle.
$client = new \GuzzleHttp\Client();
$res = $client->request('POST', 'https://apitest.authorize.net/xml/v1/request.api', [
'headers' => [
'Content-Type' => 'application/json',
],
'body' => json_encode([
'createTransactionRequest' => [
'merchantAuthentication' => [
'name' => '88VuW****',
'transactionKey' => '2xyW8q65VZ*****'
],
'transactionRequest' => [
'transactionType' => 'authCaptureTransaction',
'amount' => "5.00",
'payment' => [
'opaqueData' => [
'dataDescriptor' => 'COMMON.ACCEPT.INAPP.PAYMENT',
'dataValue' => $_POST['dataValue']
]
]
]
]
])
]);
dd(json_decode($res->getBody()));
The above returns null - no errors, just null. The below is the same request in Postman, successful with a body.
Any ideas would be really appreciated, thanks!
You should use $res->getBody()->getContents().
And json_decode() returns null in case of any error. You have to check them separately (unfortunately) with json_last_error().

Php, Guzzle, Schema validation failed but working in curl

I'm in the process of convert from cURL to Guzzle, and got most of it working.
GET requests working great etc.
My problem is the POST request, getting Schema validation errors.
It works in curl, so I'm a bit confused... well, a lot.
Client error: `POST https://restapi.e-conomic.com/customers` resulted in a `400 Bad Request` response:
{"message":"Schema validation failed.","errorCode":"E00500"
I hope one of you can tell me, if I did something wrong in the convert? Maybe my arrays needs to be formatted in another way.
This is my old working "cURL code":
$data = array(
'name' => 'Test User',
'address' => 'Road 123',
'email' => 'morten#domain.com',
'zip' => '9000',
'city' => 'City',
'country' => 'Danmark',
'corporateIdentificationNumber' => '12345678',
'customerGroup' => array(
'customerGroupNumber' => 1
),
'currency' => 'DKK',
'paymentTerms' => array(
'paymentTermsNumber' => 1
),
'vatZone' => array(
'vatZoneNumber' => 1
)
);
$options = array(
CURLOPT_URL => 'https://restapi.e-conomic.com/customers',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_HTTPHEADER => array(
'X-AppSecretToken:[removed]',
'X-AgreementGrantToken:[removed]',
'Content-Type:application/json; charset=utf-8'
),
CURLOPT_POSTFIELDS => json_encode($data)
);
curl_setopt_array($ch, $options);
This is my new "guzzle code", that is causing me problems:
$client = new GuzzleHttp\Client();
$headers = [
'X-AppSecretToken' => '[removed]',
'X-AgreementGrantToken' => '[removed]',
'Content-Type' => 'application/json;charset=utf-8',
'debug' => false
];
$form_params = [
'name' => 'Test User',
'address' => 'Road 123',
'email' => 'test#email.dk',
'zip' => '9000',
'city' => 'City',
'country' => 'Danmark',
'corporateIdentificationNumber' => '12345678',
'customerGroup' => [
'customerGroupNumber' => 1
],
'currency' => 'DKK',
'paymentTerms' => [
'paymentTermsNumber' => 1
],
'vatZone' => [
'vatZoneNumber' => 1
]
];
$response = $client->post('https://restapi.e-conomic.com/customers', [
'headers' => $headers,
'form_params' => $form_params
]);
I tried to use the "body" parameter, as stated in the Guzzle documentation, but received this error:
Passing in the "body" request option as an array to send a POST request has been deprecated. Please use the "form_params" request option to send a application/x-www-form-urlencoded request, or the "multipart" request option to send a multipart/form-data request.
I'm not sure what to do and really hope, that one of you guys will tell me what i'm doing wrong.
https://restapi.e-conomic.com/schema/customers.post.schema.json#_ga=2.167601086.1488491524.1500877149-796726383.1499933074
https://restdocs.e-conomic.com/#post-customers
I had to post the quest as json:
$response = $client->post('https://restapi.e-conomic.com/customers', [
'headers' => $headers,
'json' => $form_params
]);

Categories