Skip to content

Instantly share code, notes, and snippets.

@tzkmx
Forked from aungwinthant/FCM.php
Created January 9, 2020 01:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tzkmx/8c9641ea9f177fd65217c9132313f0fa to your computer and use it in GitHub Desktop.
Save tzkmx/8c9641ea9f177fd65217c9132313f0fa 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