I've saved some of my mobile registration_codes that are connected with my development environment of Firebase. Once I send a manual notification by the api I receive empty feedback from Firebase himself. After debugging I found that the notification has not been send. What's wrong with my call, because the call I make is the same in the examples and the registration_code is exactly the code what I receive from Flutter libary of Firebase.
code:
$response = Http::withToken(env('FCM_TOKEN'))->post(self::GLOBAL_URL, [
'registration_ids' => $request->users,
'data' => [
'title' => $request->title,
'message' => $request->message,
],
]);
return response()->json(["result" => $response]);
result:
{
"result": {
"cookies": {},
"transferStats": {}
}
}
First, you should not use env directly, because your .env file will not be used when the configuration is cached. Instead, you should set this value in your config/services.php file:
return [
'firebase' => [
'fcm_token' => env('FCM_TOKEN')
]
];
Second, your issue is that you are serializing the Illuminate\Http\Client\Response object instead of getting its value. To return the JSON result of your request, call json():
$response = Http::withToken(config('firebase.fcm_token'))->post(self::GLOBAL_URL, [
'registration_ids' => $request->users,
'data' => [
'title' => $request->title,
'message' => $request->message,
],
])->json(); // Notice the `json` call here
return response()->json(["result" => $response]);
If you inspect the Illuminate\Http\Client\Response object itself, you will see that it contains cookies and transferStats properties (specifically, they are on the PendingRequest object). That's why you are seeing this in your result.
Related
I have the following Postman request for testing a third party API;
What I am trying to do is convert this into code using Laravel's HTTP class, the code i currently have is;
public function uploadToThridParty()
{
$uploadContents = [
'id' => 'this-is-my-id',
'fileUpload' => true,
'frontfile' => Storage::get('somefrontfile.jpg'),
'sideview' => Storage::get('itsasideview.png'),
];
$request = Http::withHeaders(
[
'Accept' => 'application/json',
]
);
$response = $request
->asForm()
->post(
'https://urltoupload.com/upload', $uploadContents
)
}
But every time I run this, the 3rd party API comes back with Invalid ID, even though if i use Postman with the same ID it works fine.
I cant seem to figure out where i am going wrong with my code;
As #Cbroe mention about attach file before sending post request you can make this like this example:
public function uploadToThridParty()
{
$uploadContents = [
'id' => 'this-is-my-id',
'fileUpload' => true
];
$request = Http::withHeaders(
[
'Accept' => 'application/json',
]
);
$response = $request
->attach(
'frontfile', file_get_contents(storage_path('somefrontfile.jpg')), 'somefrontfile.jpg'
)
->attach(
'sideview', file_get_contents(storage_path('itsasideview.png')), 'itsasideview.jpg'
)
->post(
'https://urltoupload.com/upload', $uploadContents
)
}
Also i think you need remove asForm method because it's override your header accept type to application/x-www-form-urlencoded that is way your exception is Invalid ID
Some third party API would require you to have the request with content type as multipart/form data
you can double check all the headers being pass on your postman request HEADERS tab and view on Hidden headers.
If you indeed need your request to be in multipart/form-data, You can use the multipart options of guzzle.
Although this doesnt seem to be on Laravel HTTP-Client docs, you can simply pass a asMultipart() method in your HTTP request
just check the /vendor/laravel/framework/src/Illuminate/Support/Facades/Http.php for full reference of HTTP client.
You can have your request like this.
public function uploadToThridParty() {
$uploadContents = [
[
'name' => 'id',
'contents' => 'this-is-my-id'
],
[
'name' => 'fileUpload',
'contents' => true
],
[
'name' => 'frontfile',
'contents' => fopen( Storage::path( 'somefrontfile.jpg' ), 'r')
],
[
'name' => 'sideview',
'contents' => fopen( Storage::path( 'itsasideview.jpg' ), 'r')
],
];
$request = Http::withHeaders(['Accept' => 'application/json']);
$response = $request->asMultipart()->post('https://urltoupload.com/upload', $uploadContents );
}
I'm working on Lavravel 9 with guzzle to send some data in
the below code need to get some data from the database how can get data from the database?.
$response = Http::post('APIurl', [
"headers" => [
//header information
],
"body" => [
'title' => "**Get data from database**",
'body' => "**Get data from database**,
'userId' => 22
],
]);
Thank you
Assuming your API returns a json result, simply call the json() method on the Response object. If you want the raw response body, use body() instead.
For example, take github's api:
$response = Http::get('api.github.com'); // replace with your call
$body = $response->body(); // returns string
$json = $response->json(); // tries to return a json array.
To add data to your request, try passing a json string in the body.
$data = json_encode([
'title' => ...,
'body' => ...,
'user_id' => ...,
]);
$response = Http::post('your-api-here', [
'headers' => [
...
],
'body' => $data,
]);
Does anybody know the correct way to PUT using Guzzle? my code is not working
but my post methods are working
$enrolment = $client->request('PUT', $url,[
'form_params' => [
'contactID' =>12345,
'type' =>'w'
],
'headers' => [
'apitoken' => $api_token,
'wstoken' => $ws_token
]
]);
resulted in a 500 Internal Server Error response:↵{"DATA":"","ERROR":true,"MESSAGES":"key [TYPE] doesn't exist","CODE":"0","DETAILS":""}
The PUT request does't accept form_params type as request option, so it may ignore the setting.
From Docs:
form_params
Used to send an application/x-www-form-urlencoded
POST request.
Maybe you can try using json for PUT request.
In the json part of Docs, it uses PUT as well.
$enrolment = $client->request('PUT', $url,[
'json' => [
'contactID' =>12345,
'type' =>'w'
],
'headers' => [
'apitoken' => $api_token,
'wstoken' => $ws_token
]
]);
my PHP application is hosted on Azure and I'm using SendGrid PHP client to send emails to the application users. Everything was working fine till yesterday evening and suddenly after that emails have stopped working. On further debugging I found that the following piece of code
$response = $sg->client->mail()->send()->post($mail);
echo $response->statusCode();
is returning statusCode as zero. 0 as I understood is not returned by the server. To cross check I sent test mails through my local XAMPP PHP server and it worked well. So I assume that Azure is not able to reach sendgrid servers.
Please note that the same code was working till yesterday evening and neither code changes nor setting changes were done to trigger any issue.
To reproduce the issue, I have created a simple procedure
public function test_sendgrid_email(){
$api_key = '***************************'; //Hidden for security reasons
$request_body = [
'personalizations' => [
[
'to' => [
[
'email' => 'test#example.com',
'name' => 'Test'
]
],
'subject' => "Sending with SendGrid is Fun"
]
],
'from' => [
'email' => 'example#test.com',
'name' => 'Example'
],
'content' => [
[
'type' => 'text/html',
'value' => "and easy to do anywhere, even with PHP"
]
]
];
$request_body_formatted = json_decode(json_encode(($request_body)));
$sg = new \SendGrid($api_key);
try{
$response = $sg->client->mail()->send()->post($request_body_formatted);
return ['status' => 'success', 'message' => 'status code : ' . $response->statusCode()];
} catch (Exception $ex) {
return ['status' => 'failure', 'message' => 'Failure'];
}
}
Output: {"status":"success","message":"status code : 0"}
Is there any thing that has to be changed in Azure settings to get it back working? Any recent updates to Azure environments that forced this issue ?
I'm trying to delete files from my CloudFlare cache using PHP. Using Guzzle I've done this:
$client = new \GuzzleHttp\Client;
$response = $client->delete('https://api.cloudflare.com/client/v4/zones/myzoneid/purge_cache', [
'query' => [
'files' => 'https://example.com/styles.css,
],
'headers' => [
'X-Auth-Email' => 'myemail',
'X-Auth-Key' => 'myapikey',
],
]);
But when I run this I get an error:
Client error: DELETE https://api.cloudflare.com/client/v4/zones/myzoneid/purge_cache?files=https%3A%2F%2Fexample.com/etc resulted in a 400 Bad Request response: {"success":false,"errors":[{"code":1012,"message":"Request must contain one of \"purge_everything\", \"files\", \"tags\" (truncated...)
I can't get it to work using Postman either. I put in the required headers and try to set a key of files or files[] with the URL but it doesn't work. I've also tried data with raw JSON as the value like {"files":["url"]} (along with a JSON content-type header) but get the same error. It thinks I'm not sending the files key.
The method for purge_cache is POST instead of DELETE (Source: https://api.cloudflare.com/#zone-purge-files-by-url).
The payload is not sent as 'query', but as 'json'.
Files should be an array, not a string.
So the correct syntax should be....
$client = new \GuzzleHttp\Client;
$response = $client->post('https://api.cloudflare.com/client/v4/zones/myzoneid/purge_cache', [
'json' => [
'files' => ['https://example.com/styles.css'],
],
'headers' => [
'X-Auth-Email' => 'myemail',
'X-Auth-Key' => 'myapikey',
],
]);