PHP Firebase FCM - blisssan/learning-resource GitHub Wiki
Extracted from firebase-php docs
Steps to send Push Notification
-
composer require kreait/firebase-php
-
Include the vendor autoload file, initialize the Service Account using the Json configuration downloaded from Firebase
require __DIR__ . '/vendor/autoload.php';
use Kreait\Firebase\Factory;
use Kreait\Firebase\ServiceAccount;
use Kreait\Firebase\Messaging\CloudMessage;
use Kreait\Firebase\Messaging\Notification;
$serviceAccount = ServiceAccount::fromJsonFile('../YOUR PRIVATE KEY.json');
$firebase = (new Factory)
->withServiceAccount($serviceAccount)
->create();
- Initialise messaging & message
$messaging = $firebase->getMessaging();
$title = "New Work Order Allocated"; // title could be any text
$message = "#WO-000145 has to be delivered today";
$data = [
'primary' => $id,
'type' => 'workorder',
'target' => $anyObject,
];
$notification = Notification::fromArray([
'title' => $title,
'body' => $message,
'data' => $data
]);
- Sending notification can be done in three ways, sending to a single device, sending as multicast & sending to a topic
- Sending to a single device is self explanatory
- Multicast is sending to multiple devices and is limited to 500 tokens per call,
- Sending to a topic, works like a Pub-Sub mechanism, all clients who have subscribed to a topic will receive the message when pushed to that topic. This is ideal for sending push notifications to huge number of devices at the same time.
If we are planning to allow more than one devices to same employee then we have to send to multiple devices when sending to an employee.
SENDING TO SINGLE DEVICE
use Kreait\Firebase\Messaging\CloudMessage;
$deviceToken = '...'; // query from FCM Tokens table for the target employee.
$fcmMessage = CloudMessage::withTarget('token', $deviceToken)
->withNotification($notification);
messaging->send($fcmMessage);
SENDING TO MULTIPLE DEVICE
$deviceTokens = ['...', '...', '...', '...']; // query from FCM Token table fetch all tokens for the target employee
$fcmMessage = CloudMessage::new()->withNotification($notification);
$report = $messaging->sendMulticast($fcmMessage, $deviceTokens);
echo 'Successful sends: '.$report->successes()->count().PHP_EOL;
echo 'Failed sends: '.$report->failures()->count().PHP_EOL;
if ($report->hasFailures()) {
foreach ($report->failures()->getItems() as $failure) {
echo $failure->error()->getMessage().PHP_EOL;
}
}