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',
],
]
]);
Related
i use Fast Excel library from https://github.com/rap2hpoutre/fast-excel, can i put return from ->download('file.xlsx') to Guzzle post request? with this code i'm not get anything
$httpClient = new \GuzzleHttp\Client([
'headers' => [
'Authorization' => mdmTokenGenerate($token),
'Accept' => 'application/json'
],
'verify' => false
]);
$response = $httpClient->post(
"{$client->domain}/api/push", [
'multipart' => [
[
'name' => 'file',
'contents' => (new FastExcel(MasterNumbers::limit(1000)->get()))->download('file.xlsx')
]
]
]
);
I am having a problem in clevertap. I tried the test account that clevertap give in postman and it works.
but when I put my account id and passcode it shows Invalid Endpoint.
$profile = [
"identity"=>"jorem34.like#gmail.com",
"ts"=>1419421212,
"type"=>"profile",
"profileData"=>[
"Name"=>"Jorem",
"Email"=>"jorem#gmail.com",
"Phone"=>"+14153412312",
"Gender"=>"M",
"Employed"=>"Y",
"Age"=>21,
"Customer Type"=>"Silver",
]];
$body = json_encode([
'd' => [
$profile
]
]);
$response = $client->request(
'POST',
self::API_URL,
['headers' => [
'X-CleverTap-Account-Id' => '*****************',
'X-CleverTap-Passcode' => '************',
'Content-Type' => 'application/json'
],
'body' => $body
]
);
I have a simple registration form that the user can register in my app, now I want to send submitted data to another service.
First I test my request using postman as follows using a raw option in a postman panel.
Api url : app3.salesmanago.pl/api/contact/upsert
JSON DATA:
{
"clientId":"w2ncrw06k7ny45umsssc",
"apiKey":"ssssj2q8qp4fbp9qf2b8p49fz",
"requestTime":1327056031488,
"sha":"ba0ddddddb543dcaf5ca82b09e33264fedb509cfb4806c",
"async" : true,
"owner" : "adam#rce.com",
"contact" : {
"email" : "test-1#konri.com",
"name" : "Test",
"address":{
"streetAddress":"Brzyczynska 123",
}
}
}
I get the following success result
{
"success": true,
"message": [],
"contactId": "b52910be-9d22-4830-82d5-c9dc788888ba",
"externalId": null
}
Now using guuzle htpp request in laravel
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
$current_timestamp = Carbon::now()->timestamp;
$client = new Client();
$request = $client->post('app3.salesmanago.pl/api/contact/upsert', [
\GuzzleHttp\RequestOptions::JSON => [
'headers' => [
'Accept' => 'application/json, application/json',
'Content-Type' => 'application/json',
'clientId' => 'dd2ncrw06k7ny45umce',
'apiKey' => 'ddjdd2q8qp4fbp9qf2b8p49fdzd',
'sha' => ' wba0b543dcaf5ca82b09e33264fedb4509cfb4806ec',
"requestTime" => $current_timestamp,
"owner" => "testemail#wp.com",
],
'form_params' => [
'name' => $data['name'],
'email' => $data['email'],
]
]
]);
$response = $request->getBody();
$r = json_decode($response);
dd($r);
return $user;
}
When I run my app and send the form data I get this using the same data as in postman I get this
{#306 ▼
+"success": false
+"message": array:1 [▼
0 => "Not authenticated"
]
+"contactId": null
+"externalId": null
}
Can someone tell me why in Postman everything works fine but in laravel It fails?
What is wrong with my code?
Because you wrote headers inside json option. here is the correct one
$client = new Client();
$request = $client->post('app3.salesmanago.pl/api/contact/upsert', [
\GuzzleHttp\RequestOptions::JSON => [
'form_params' => [
'name' => $data['name'],
'email' => $data['email'],
],
],
\GuzzleHttp\RequestOptions::HEADERS => [
'Accept' => 'application/json, application/json',
'Content-Type' => 'application/json',
'clientId' => 'dd2ncrw06k7ny45umce',
'apiKey' => 'ddjdd2q8qp4fbp9qf2b8p49fdzd',
'sha' => ' wba0b543dcaf5ca82b09e33264fedb4509cfb4806ec',
"requestTime" => $current_timestamp,
"owner" => "testemail#wp.com",
],
]);
You can use it like
$client->request('POST', 'app3.salesmanago.pl/api/contact/upsert', [
'form_params' => [
'name' => $data['name'],
'email' => $data['email'],
],
'headers' => [
'Accept' => 'application/json, application/json',
'Content-Type' => 'application/json',
'clientId' => 'dd2ncrw06k7ny45umce',
'apiKey' => 'ddjdd2q8qp4fbp9qf2b8p49fdzd',
'sha' => ' wba0b543dcaf5ca82b09e33264fedb4509cfb4806ec',
'requestTime' => $current_timestamp,
'owner' => 'testemail#wp.com',
]
]);
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
I'd like to add some data to a Guzzle Http Request. There are file name, file content and header with authorization key.
$this->request = $this->client->request('POST', 'url', [
'multipart' => [
'name' => 'image_file',
'contents' => fopen('http://localhost:8000/vendor/l5-swagger/images/logo_small.png', 'r'),
'headers' =>
['Authorization' => 'Bearer uCMvsgyuYm0idmedWFVUx8DXsN8QzYQj82XDkUTw']
]]);
but I get error
Catchable Fatal Error: Argument 2 passed to GuzzleHttp\Psr7\MultipartStream::addElement() must be of the type array, string
given, called in vendor\guzzlehttp\psr7\src\MultipartStream.php on line 70 and defined in vendor\guzzlehttp\psr7\src\MultipartStream.php line 79
In Guzzle 6 documentation is something like this: http://docs.guzzlephp.org/en/latest/request-options.html#multipart
Who knows where I made a mistake?
Here is the solution. Header with access token should be outside multipart section.
$this->request = $this->client->request('POST', 'request_url', [
'headers' => [
'Authorization' => 'Bearer access_token'
],
'multipart' => [
[
'Content-type' => 'multipart/form-data',
'name' => 'image_file',
'contents' => fopen('image_file_url', 'r')
]
]
]);
As per the docs, "The value of multipart is an array of associative arrays", so you need to nest one level deeper:
$this->request = $this->client->request('POST', 'url', [
'multipart' => [
[
'name' => 'image_file',
'contents' => fopen('http://localhost:8000/vendor/l5-swagger/images/logo_small.png', 'r'),
'headers' => ['Authorization' => 'Bearer uCMvsgyuYm0idmedWFVUx8DXsN8QzYQj82XDkUTw']
]
]
]);
try this
works for me
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Utils;
$this->client = new Client([
'base_uri' => 'https://baseurl'
]);
$body = Utils::tryFopen($tempPath . $fileName, 'r');
$res = $this->client->request(
'POST',
'url',
[
'headers' => [
...
],
'body' => $body
]
);