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().
Related
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',
],
]
]);
I've been trying to upload a pdf file when providing an evidence to Paypal Disputes in the Claim Stage after verifying that the dispute case has the /provide-evidence on its HATEOAS links, the curl code below works in the CLI:
$ curl -v -X POST https://api.sandbox.paypal.com/v1/customer/disputes/PP-D-12345/provide-evidence \
-H "Content-Type: multipart/related" \
-H "Authorization: Bearer {AccessToken}" \
-F 'input={"evidences":[{"evidence_type": "PROOF_OF_FULFILLMENT", "evidence_info": {"tracking_info": [{"carrier_name": "FEDEX", "tracking_number": "123456789"}]}, "notes": "Test"}]};type=application/json' \
-F 'file1=#D:\Sample\storage\app\paypal\sample.pdf'
However when converted to PHP, either using curl or guzzle the API returns VALIDATION_ERROR - MISSING_OR_INVALID_REQUEST_BODY, I've tried almost every possible approach, but the error is consistent.
Using Guzzle: (trying to copy the working curl above as much as possible, since Guzzle can't send multipart/related request, I had to modify the content-type manually).
$pdf = 'D:\Sample\storage\app\paypal\sample.pdf';
$input = [
'evidences' => [
[
'evidence_type' => 'PROOF_OF_FULFILLMENT',
'evidence_info' => [
'tracking_info' => [
'carrier_name' => "FEDEX",
'tracking_number' => '122533485'
]
],
'notes' => 'Test',
],
]
];
$client = new \GuzzleHttp\Client([
'base_uri' => 'https://api.sandbox.paypal.com',
'timeout' => 2.0,
'version' => 1.1
]);
$options = [
'headers' => [
'Authorization' => "Bearer $token",
],
'multipart' => [
[
'name' => 'input',
'contents' => json_encode($input),
'headers' => ['Content-Type' => 'application/json']
],
[
'name' => 'file1',
'contents' => fopen($pdf, 'r'),
'filename' => 'sample.pdf',
'headers' => ['Content-Type' => 'application/pdf']
],
]
];
$url = '/v1/customer/disputes/'.$disputeId.'/provide-evidence';
$headers = isset($options['headers']) ? $options['headers'] : [];
$body = new \GuzzleHttp\Psr7\MultipartStream($options['multipart']);
$request = new \GuzzleHttp\Psr7\Request('POST', $url, $headers, $body, '1.1');
$modify['set_headers']['Content-Type'] = 'multipart/related; boundary=' . $request->getBody()->getBoundary();
$request = \GuzzleHttp\Psr7\modify_request($request, $modify);
$response = $client->send($request);
The guzzle code above still return {VALIDATION_ERROR - MISSING_OR_INVALID_REQUEST_BODY} and same result when I just do a normal multipart/form-data request.
What could be the issue? Any ideas or suggestion would very much help, thanks.
$input = [
'evidences' => [
[
'evidence_type' => 'PROOF_OF_FULFILLMENT',
'evidence_info' => [
'tracking_info' => [
'carrier_name' => "FEDEX",
'tracking_number' => '122533485'
]
],
'notes' => 'Test',
],
]
];
This is your $input, if you json_encode() it, you get
{
"evidences":
[
{
"evidence_type":"PROOF_OF_FULFILLMENT",
"evidence_info":{
"tracking_info":{
"carrier_name":"FEDEX",
"tracking_number":"122533485"
}
},
"notes":"Test"
}
]
}
which does not matches with your request body,
I have changed your $input by inserting another square bracket,
$input = [
'evidences' => [
[
'evidence_type' => 'PROOF_OF_FULFILLMENT',
'evidence_info' => [
'tracking_info' => [[
'carrier_name' => "FEDEX",
'tracking_number' => '122533485'
]]
],
'notes' => 'Test',
],
]
];
Now it matches your curl request,
{
"evidences":
[
{
"evidence_type":"PROOF_OF_FULFILLMENT",
"evidence_info":
{
"tracking_info":
[
{
"carrier_name":"FEDEX",
"tracking_number":"122533485"
}
]
},
"notes":"Test"
}
]
}
I hope it helps. If it doesn't work, then problem might lie somewhere else but the request body will match, you can try the guzzle call first.
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."}
I am using guzzle 6.3 to post a file along with some data to my api built on laravel 5.5. When i post the data, i am not able to get the data sent to the api except the file posted.
Client Side
$client = new Client([
'headers' => [ 'Content-Type' => 'application/json' ]
]);
$response = $client->request('POST',$url, [
'multipart' => [
[
'name' => 'body',
'contents' => json_encode(['documentation' => 'First Doc', 'recipient' => ['78011951231']]),
'headers' => ['Content-Type' => 'application/json']
],
[
'name' => 'file',
'contents' => fopen('/path/public/media/aaaah.wav', 'r'),
'headers' => ['Content-Type' => 'audio/wav']
],
],
]);
echo($response->getBody()->getContents());
API Controller
if (($Key)) {
return response()->json([
'status' => 'success',
'documenation' => $request->get('documentation'),
'recipient' => $request->get('recipient'),
'file' =>$request->get('file'),
'media'=>$request->hasFile('file')
]);
}
Response
{"status":"error","documentation":null,,"recipient":null,"file":null,"media":true}
Why am i getting NULL returned for the data that i am posting? Could it be because of the file that i am posting ?
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,
]
]);