Skip to content

Instantly share code, notes, and snippets.

@afiqiqmal
Last active May 20, 2020 10:21
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 afiqiqmal/bb0c3023f894e13b701b91d935deaf39 to your computer and use it in GitHub Desktop.
Save afiqiqmal/bb0c3023f894e13b701b91d935deaf39 to your computer and use it in GitHub Desktop.
Firebase notification PHP class for easier boilerplate

Firebase Notification using PHP

Usage

push_notification() // i already defined in helper.. If dont, you just replace with (new FireBaseNotification())
     ->setPayload($this->payload)
     ->pushByTopic()
     ->setTopic("notification_event_topic")
     ->sendTo("android")
     ->push();

// will push by topic which device subscribe topic "android-notification_event_topic". If onlyForDevelopment() is set, the subscribe event change to "android-notification_event_topic-local"

push_notification() // i already defined in helper.. If dont, you just replace with (new FireBaseNotification())
     ->setPayload($this->payload)
     ->pushByDevice()
     ->setRegistrationIds("DEVICE_PERSONAL_FCM_TOKEN")
     ->push();
// will push to the device which the device generate the fcm token
Method Exist
  1. setHeaders(array) - set custom headers if you wish. See default in constructor
  2. setKey(string) - set Firebase Key if you want beside set it on Env
  3. setBaseUrl(string) . - set Firebase Url if you want beside set it on Env
  4. pushByTopic() / pushByDevice() - 1- Push By Topic 2- Push By Device Id. Default is 1
  5. setPayload(array) - set body what to send in the push notification
  6. setPriority(string) - 'high' or 'low'. default is 'high'
  7. setChannelName(string)- set Topic name or Token Device
  8. sendTo(string) - send to 'android' or 'ios'. Default is 'android'
  9. push - the executer
<?php
namespace App\Exceptions;
use Symfony\Component\HttpKernel\Exception\HttpException;
class BaseHttpException extends HttpException
{
protected $default_headers = [
'Access-Control-Allow-Origin' => '*',
];
protected $apiMessage = null;
protected $extras = null;
/**
* Create a new exception instance.
*
* @param string|null $message
* @param int $code
* @param array $headers
* @param array $extras
*/
public function __construct($message = null, $code = 400, array $headers = [], $extras = [])
{
$this->apiMessage = $message;
$this->extras = $extras;
$headers = array_merge($this->default_headers, $headers);
parent::__construct($code, __($message), null, $headers, $code);
}
/**
* @return null
*/
public function getApiMessage()
{
return $this->apiMessage;
}
/**
* @return null
*/
public function getExtras()
{
return $this->extras;
}
}
<?php
/**
* Created by PhpStorm.
* User: hafiq
* Date: 18/03/2019
* Time: 11:59 PM.
*/
namespace App\Firebase;
use App\Exceptions\FirebaseNotificationException;
class FireBaseNotification
{
protected $headers = [];
protected $key = null;
protected $baseUrl = null;
protected $pushBy = 1; // 1- topic 2- device
protected $payload = null;
protected $channelRegistrationIds = null;
protected $channelTopic = null;
protected $to_whom = null;
protected $priority = 'high';
protected $env = 'production';
public function __construct()
{
$this->key = config('notification.fire_key');
$this->headers = [
'Content-Type' => 'application/json',
'Authorization' => 'key='.$this->key,
];
$this->baseUrl = config('notification.fire_url');
}
public function setHeaders(array $headers): self
{
if ($headers) {
$this->headers = array_merge($this->headers, $headers);
}
return $this;
}
public function setKey(string $key): self
{
if ($key) {
$this->key = $key;
$this->headers['Authorization'] = 'key='.$this->key;
} else {
throw new FirebaseNotificationException('Firebase Server Key is needed. It Cannot be null!!');
}
return $this;
}
public function setBaseUrl(string $baseUrl): self
{
if ($baseUrl) {
$this->baseUrl = $baseUrl;
} else {
throw new FirebaseNotificationException('Firebase URL is needed. It Cannot be null!!');
}
return $this;
}
public function pushByTopic()
{
$this->pushBy = 1;
return $this;
}
public function pushByDevice()
{
$this->pushBy = 2;
return $this;
}
public function setPayload(array $payload): self
{
$this->payload = $payload;
return $this;
}
public function setPriority(string $priority): self
{
$this->priority = $priority;
return $this;
}
public function onlyForDevelopment(): self
{
$this->env = 'local';
return $this;
}
public function setRegistrationIds($channelName): self
{
$this->channelRegistrationIds = $channelName;
return $this;
}
public function setTopic($channelTopic)
{
$this->channelTopic = $channelTopic;
return $this;
}
public function sendTo(string $to_whom): self
{
$this->to_whom = preg_replace('/\s+/', '_', strtolower($to_whom));
return $this;
}
public function push()
{
$response = api_request()
->baseUrl($this->baseUrl)
->postMethod()
->setHeader($this->headers)
->jsonRequest()
->setRequestBody($this->getBody())
->setParam([
'verify' => false,
])->fetch();
if (! $response['error']) {
return [
'data' => 'Notification Success',
'statusCode' => $response['status_code'],
'payload' => $response,
];
} else {
return $response;
}
}
private function getBody()
{
if ($this->pushBy == 1) {
if (!$this->channelTopic) {
throw new FirebaseNotificationException("Topic is Required");
}
$this->channelTopic = "/topics/{$this->channelTopic}";
if ($this->to_whom) {
$this->channelTopic .= "-{$this->to_whom}";
}
if ($this->env == 'local') {
$this->channelTopic .= '-local';
}
if ($this->to_whom == 'android') {
return $this->buildBodyAndroid();
} elseif ($this->to_whom == 'ios') {
return $this->buildBodyIOS();
} else {
return $this->buildBodyUniversal();
}
} else {
if (!$this->channelRegistrationIds) {
throw new FirebaseNotificationException("Push Token is Required");
}
$this->channelRegistrationIds = is_array($this->channelRegistrationIds) ? $this->channelRegistrationIds : [$this->channelRegistrationIds];
return $this->buildBodyUniversal();
}
}
private function buildBodyUniversal()
{
$this->payload['sound'] = 'default';
$data = [
'priority' => $this->priority,
'data' => $this->payload,
'notification' => $this->payload,
'content_available' => true,
];
if ($this->pushBy == 1) {
$data['to'] = $this->channelTopic;
} else {
$data['registration_ids'] = $this->channelRegistrationIds;
}
return $data;
}
private function buildBodyAndroid()
{
$data = [
'priority' => $this->priority,
'data' => $this->payload,
];
if ($this->pushBy = 1) {
$data['to'] = $this->channelTopic;
} else {
$data['registration_ids'] = $this->channelRegistrationIds;
}
return $data;
}
private function buildBodyIOS()
{
$this->payload['sound'] = 'default';
$data = [
'priority' => $this->priority,
'notification' => $this->payload,
'content_available' => true,
];
if ($this->pushBy = 1) {
$data['to'] = $this->channelTopic;
} else {
$data['registration_ids'] = $this->channelRegistrationIds;
}
return $data;
}
}
<?php
namespace App\Exceptions;
class FirebaseNotificationException extends BaseHttpException
{
/**
* Create a new exception instance.
*
* @param string|null $message
* @param array $headers
* @param int $code
*/
public function __construct($message = null, $code = 482, array $headers = [])
{
parent::__construct($message, $code, $headers);
}
}
<?php
return [
'fire_key' => env('FIREBASE_KEY'),
'fire_url' => 'https://fcm.googleapis.com/fcm/send',
];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment