Created
March 29, 2021 14:09
-
-
Save Navari/a6dacc8a00183c413faa14ec88ec8665 to your computer and use it in GitHub Desktop.
Send your Firebase notifications with PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Created by PhpStorm. | |
* User: celalettinyilmaz | |
* Date: 11.02.2021 | |
* Time: 12:17 | |
*/ | |
namespace App\Services\Firebase; | |
use App\Services\Firebase\Exception\FirebaseSendNotificationError; | |
use App\Services\Firebase\Http\Request; | |
use GuzzleHttp\Client; | |
class Firebase | |
{ | |
public $server_token; | |
public $client; | |
public $firebase_url = 'https://fcm.googleapis.com/fcm/send'; | |
const HTTP_OK = 200; | |
public function __construct($server_token) | |
{ | |
$this->server_token = $server_token; | |
$this->client = new Client(); | |
} | |
public function sendNotification($to, $title, $body) | |
{ | |
$response = $this->client->post($this->firebase_url, | |
[ | |
'headers' => [ | |
'Authorization' => 'key=' .$this->server_token, | |
'Content-Type' => 'application/json' | |
], | |
'body' => json_encode([ | |
'registration_ids' => [$to], | |
'notification' => [ | |
'title' => $title, | |
'body' => $body | |
] | |
]) | |
] | |
); | |
if($response->getStatusCode() != static::HTTP_OK){ | |
throw new FirebaseSendNotificationError('Something wrong please report this issue. Response code is : '. $response->getStatusCode() . ' Response Body : '. $response->getBody()); | |
} | |
return true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment