Push notifications are a great way to engage users by delivering real-time updates and alerts. Integrating Firebase Cloud Messaging (FCM) in CakePHP 5 allows you to send push notifications to web and mobile applications efficiently. In this guide, we will walk you through creating an FCM component in CakePHP 5 to handle push notifications seamlessly.
What is Firebase Cloud Messaging (FCM)?
FCM is a messaging service by Google that enables developers to send notifications to Android, iOS, and web applications. It supports both single-device notifications and broadcast notifications to multiple users.
Step 1: Set Up Firebase for Push Notifications
To use FCM in your CakePHP 5 application, follow these steps:
- Go to the Firebase Console: https://console.firebase.google.com
- Create a new project or select an existing one.
- Navigate to Project Settings > Cloud Messaging.
- Get the Server Key: Under the "Cloud Messaging" tab, copy the Server Key (used to authenticate requests).
Step 2: Create an FCM Component in CakePHP 5
CakePHP components help modularize logic that can be reused across controllers. We’ll create an FcmComponent
to handle push notifications.
Create the Component File
📌 Location: src/Controller/Component/FcmComponent.php
namespace App\Controller\Component;
use Cake\Controller\Component;
use Cake\Http\Client;
class FcmComponent extends Component {
private $serverKey;
private $apiUrl = 'https://fcm.googleapis.com/fcm/send';
public function initialize(array $config): void {
parent::initialize($config);
$this->serverKey = env('FCM_SERVER_KEY'); // Store in .env file
}
public function sendNotification($deviceTokens, $title, $body, $data = []) {
$http = new Client();
$payload = [
'registration_ids' => is_array($deviceTokens) ? $deviceTokens : [$deviceTokens],
'notification' => [
'title' => $title,
'body' => $body,
'sound' => 'default',
],
'data' => $data,
];
$response = $http->post($this->apiUrl, json_encode($payload), [
'headers' => [
'Authorization' => 'key=' . $this->serverKey,
'Content-Type' => 'application/json'
]
]);
return $response->getJson();
}
}
Configuration in .env File
Ensure you store the FCM Server Key in the .env
file for security:
FCM_SERVER_KEY=YOUR_FIREBASE_SERVER_KEY_HERE
Step 3: Use the Component in a Controller
Now, let's use this component in a controller to send notifications.
📌 Example: UsersController.php
namespace App\Controller;
use App\Controller\AppController;
use Cake\Event\EventInterface;
class UsersController extends AppController {
public function initialize(): void {
parent::initialize();
$this->loadComponent('Fcm');
}
public function sendPushNotification() {
$deviceToken = 'USER_DEVICE_TOKEN_HERE';
$title = 'New Message';
$body = 'You have a new notification!';
$data = ['key' => 'value'];
$response = $this->Fcm->sendNotification($deviceToken, $title, $body, $data);
$this->set(['response' => $response, '_serialize' => ['response']]);
}
}
Step 4: Testing the Push Notification
You can test the notification by calling the sendPushNotification method in your browser or using Postman.
Example API Request:
GET http://your-cakephp-app.local/users/sendPushNotification
If successful, you will receive a response like:
{
"multicast_id": "XXXXXXX",
"success": 1,
"failure": 0,
"results": [{ "message_id": "XXXXXXXX" }]
}
Step 5: Handling Multiple Devices
If you need to send notifications to multiple devices, simply pass an array of device tokens instead of a single one.
$deviceTokens = ['TOKEN_1', 'TOKEN_2', 'TOKEN_3'];
$response = $this->Fcm->sendNotification($deviceTokens, 'Hello Users!', 'This is a bulk notification.');
This will send a broadcast notification to multiple users at once.
Step 6: Advanced Features (Optional)
1. Handling Click Actions
If you want users to be redirected to a specific page when they tap the notification, add a click_action
field.
'notification' => [
'title' => $title,
'body' => $body,
'click_action' => 'https://your-website.com/specific-page'
],
2. Prioritizing Notifications
Set high priority for instant notifications:
'priority' => 'high'
3. Silent Push Notifications
Send data without user interaction (e.g., background updates):
'data' => ['key' => 'value'],
'content_available' => true
Conclusion
Integrating Firebase Cloud Messaging (FCM) in CakePHP 5 allows you to send real-time push notifications to users effortlessly. By following this guide, you can:
✅ Set up Firebase and retrieve API keys 🎯
✅ Create a reusable FcmComponent 📌
✅ Send notifications to single or multiple devices 🔥
✅ Extend notifications with advanced features 📲
With this setup, you can engage users effectively and keep them informed in real-time! 🚀
Comments