Skip to content

Instantly share code, notes, and snippets.

@aungwinthant
Last active July 20, 2023 11:53
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save aungwinthant/de40ee0a9b3b71f9a0db9feb0c7a88c2 to your computer and use it in GitHub Desktop.
Save aungwinthant/de40ee0a9b3b71f9a0db9feb0c7a88c2 to your computer and use it in GitHub Desktop.
Firebase Cloud Messaging with Guzzle HTTP Client (Only For Topics)
<?php
use GuzzleHttp\Client;
class FCM{
protected $endpoint;
protected $topic;
protected $data;
protected $notification;
public function __construct()
{
$this->endpoint = "https://fcm.googleapis.com/fcm/send";
}
public function setEndPoint($endpoint){
//if there is a case to override endpoint
$this->endpoint = $endpoint;
}
public function data(array $data=[]){
$this->data = $data;
}
public function topic($topic){
$this->topic=$topic;
}
public function notification(array $notification = [])
{
$this->notification = $notification;
return $this;
}
public function send(){
$server_key = env("FCM_SERVER_KEY");
$headers = [
'Authorization' => 'key='.$server_key,
'Content-Type' => 'application/json',
];
$fields = [
'to'=>"/topics/" . $this->topic,
'content-available' => true,
'priority' => 'high',
'data' => $this->data,
];
$fields = json_encode ( $fields );
$client = new Client();
try{
$request = $client->post($this->endpoint,[
'headers' => $headers,
"body" => $fields,
]);
$response = $request->getBody();
return $response;
}
catch (Exception $e){
return $e;
}
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment