How to convert PHP cURL format into Guzzle Laravel Format - php

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.

Related

GuzzleHttp firebase messaging INVALID_ARGUMENT The message is not set

I'm trying to implement a function to send a a notification using FirebaseCloudMessaging, I got the Auth part, But seems there is an issue with the GuzzleHttp\Client and how it passes the data part
This is my code
public function send(){
putenv('GOOGLE_APPLICATION_CREDENTIALS=<path-to-json-file>.json');
$scopes = ['https://www.googleapis.com/auth/firebase.messaging'];
$middleware = ApplicationDefaultCredentials::getMiddleware($scopes);
$stack = HandlerStack::create();
$stack->push($middleware);
// create the HTTP client
$client = new Client([
'handler' => $stack,
'base_uri' => 'https://fcm.googleapis.com',
'auth' => 'google_auth'
]);
$data = json_encode(
[
"message" => [
"topic" => "availableProviders",
"notification" => [
"title" => "New Order",
"body" => "New Order to accept",
],
"data" => [
"service_id" => '1'
],
],
"validateOnly" => false,
],
);
$response = $client->post('/v1/projects/<Project-id>/messages:send', [
[
'json' => $data,
'headers' => [
'accept' => 'application/json',
'Content-Type' => 'application/json',
],
]
]);
dd($response);
}
I keep getting that response 400, INVALID_ARGUMENT "The message is not set."
Client error: POST https://fcm.googleapis.com/v1/projects//messages:sendresulted in a400 Bad Request response: { "error": { "code": 400, "message": "The message is not set.", "status": "INVALID_ARGUMENT", "details (truncated...)
Although my data structure is being passed as documented, what I'm missing here?
Note: I use Laravel, I hided the , etc.
Try to use the Laravel wrapper
use Google\Auth\ApplicationDefaultCredentials;
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use Illuminate\Support\Facades\Http;
public function send(){
putenv('GOOGLE_APPLICATION_CREDENTIALS=D:\Projects\waterko_final\waterco-356810-firebase-adminsdk-brisz-11133a2abb.json');
$scopes = ['https://www.googleapis.com/auth/firebase.messaging'];
$data = [
"message" => [
"topic" => "availableProviders",
"notification" => [
"title" => "New Order",
"body" => "New Order to accept",
],
"data" => [
"service_id" => '1'
],
],
"validateOnly" => false,
];
$headers = [
'Accept' => 'application/json',
'Content-Type' => 'application/json',
];
$middleware = ApplicationDefaultCredentials::getMiddleware($scopes);
$stack = HandlerStack::create();
$stack->push($middleware);
$client = new Client([
'handler' => $stack,
'base_uri' => 'https://fcm.googleapis.com',
'auth' => 'google_auth'
]);
return Http::withHeaders($headers)->bodyFormat("json")->setClient($client)
->post('https://fcm.googleapis.com/v1/projects/waterco-356810/messages:send', $data);
}
I ran into the exact same issue, here's what worked for me:
$data should not be json encoded, but passed as an array.
And instead of the json key, it's safer to use the constant : GuzzleHttp\RequestOptions::JSON
$data = [
"message" => [
"topic" => "availableProviders",
"notification" => [
"title" => "New Order",
"body" => "New Order to accept",
],
"data" => [
"service_id" => '1'
],
],
"validateOnly" => false,
];
$response = $client->post('/v1/projects/<Project-id>/messages:send', [
[
GuzzleHttp\RequestOptions::JSON => $data,
'headers' => [
'accept' => 'application/json',
'Content-Type' => 'application/json',
],
]
]);

how fix Authorization Bearer Problem in guzzle

I'm trying to send this request to the server, but with a 401 error
Which part of the code can the problem be?
"guzzle version 6.3"
try {
$urlDoPayment = 'https://api.example.com/v1/pay';
$client = new Client();
try {
$response = $client->request('POST', $urlDoPayment, [
\GuzzleHttp\RequestOptions::JSON => [
'form_params' => [
'amount' => 100,
'returnUrl' => "https://example.com/payment/verify",
'payerIdentity' => "",
'payerName' => "",
'description' => "",
'clientRefId' => ""
],
'headers' => [
'Content-Type' => 'application/json',
'Authorization' => 'Bearer MY_TOKEN',
'Accept' => 'application/json'
]
]
]);
$statusCode = $response->getStatusCode();
$content = $response->getBody();
dd($content);
} catch (GuzzleException $e) {
dd($e->getMessage());
}
} catch (\Exception $exception) {
dd($exception->getCode());
}
The headers in the request are nested in the wrong part of the request options. That should at least fix the 401 error if the token is valid.
Try:
$response = $client->request('POST', $urlDoPayment, [
\GuzzleHttp\RequestOptions::JSON => [
'form_params' => [
'amount' => 100,
'returnUrl' => "https://example.com/payment/verify",
'payerIdentity' => "",
'payerName' => "",
'description' => "",
'clientRefId' => ""
],
// headers should not be here
], // json post body params end
'headers' => [
'Content-Type' => 'application/json',
'Authorization' => 'Bearer MY_TOKEN',
'Accept' => 'application/json'
]
]);
This problem solved using this code
$response = $client->request('POST', $urlDoPayment, [
'json' => [
'amount' => 100,
'returnUrl' => "http://example.com/payment/verify",
'payerIdentity' => "",
'payerName' => "",
'description' => "",
'clientRefId' => ""
],
'headers' => [
'Content-Type' => 'application/json',
'Authorization' => 'Bearer MY_TOKEN',
'Accept' => 'application/json'
]
]);
I suspect that the problem lays in undefined port or protocol. Headers content wasn't an issue for me. I resolved same problem by changing:
115.12.3.44 to 115.12.3.44:80
also tested
115.12.3.44 to http://115.12.3.44
or
google.com to http://google.com

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 Http Post request with json response: no valid json

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,
]
]);

Converting Curl request to Guzzle issues with cert

I am Trying to convert an existing phpCurl request to latest guzzle and not getting anywhere fast.
This is the current request.
$curl_opts = array(
CURLOPT_HEADER => false,
CURLOPT_HTTPHEADER => array('Content-Type: text/json', 'Content-length: '.strlen($json)),
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $json,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_URL => 'https://the-domainservice.php',
CURLOPT_VERBOSE => false,
CURLOPT_SSLCERT => '/path/to/file.pem',
CURLOPT_SSLCERTTYPE => 'pem',
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSLVERSION => CURL_SSLVERSION_TLSv1
);
$curl = curl_init();
curl_setopt_array($curl, $curl_opts);
$response = curl_exec($curl);
For Guzzle I have tried so many ways but here are a couple of example.
$response = $this->client->post('https://the-domainservice.php', [
'body' => $postData,
'cert' => '/path/to/file.pem',
'config' => [
'curl' => [
CURLOPT_SSLVERSION => CURL_SSLVERSION_TLSv1,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_RETURNTRANSFER => true
]
]
]
);
And more verbose of
$request = $this->client->createRequest('POST', 'https://the-domainservice.php', [
'cert' => '/path/to/file.pem',
'verify' => false,
'headers' => [
'Content-Type' => 'text/json',
'Content-length' => strlen(json_encode($postData))
]
]);
$postBody = $request->getBody();
foreach ($postData as $key => $value) {
$postBody->setField($key, $value);
}
$response = $this->client->send($request);
For my guzzle requests I am just getting
GuzzleHttp\Exception\ServerException: Server error response [url] https://the-domainservice.php [status code] 500 [reason phrase] Internal Service Error
Really hope someone can advise.
Feel a little stupid now.
Just needed to send json data and all worked, end result was.
$response = $this->client->post('https://the-domainservice.php', [
'body' => json_encode($postData),
'cert' => '/path/to/file.pem',
]
);
Excellent stuff Guzzle !

Categories