How to send FCM notification to app from web
Implementing Firebase Cloud Messaging (FCM) for a chat application requires bridging the gap between your server-side logic and the client's notification channel. You've likely already handled the client-side setup, as evidenced by the fact that test pushes from the Firebase Console work correctly. The real challenge arises when you need to trigger these notifications based on real-time data changes in the Firebase Realtime Database while running on a shared hosting environment that restricts Node.js execution.
The core mechanism here is simple: your server detects a change in the database, constructs an FCM message payload, and sends it via the HTTP v1 API or the legacy FCM SDK. However, since you are constrained to PHP on shared hosting, you cannot rely on Firebase Admin SDK libraries that typically require Node.js or specific runtime environments. Instead, you must interact directly with the RESTful endpoints provided by Google Cloud Messaging.
To listen for changes in your database structureâwhere messages likely reside under a node like /messages and contain user identifiersâyou can utilize Firebase's built-in security rules to trigger functions or poll the database if triggers are unavailable on your host. If your shared hosting plan supports serverless functions or allows specific PHP extensions, you might consider implementing a lightweight polling script that checks for new entries every few seconds. Alternatively, many modern chat applications opt for a WebSocket approach where the server pushes updates directly to connected clients, which can then forward notifications for disconnected devices.
When constructing the request in PHP, you must manually serialize the JSON payload and send it using cURL. This involves several critical steps: generating an authentication token using your Firebase Service Account credentials, setting up the HTTP headers correctly, and ensuring the data field contains the necessary context (like message ID or room name) so the app can handle the notification appropriately upon arrival.
$fcmsender = 'YOUR_PROJECT_NUMBER';
$fcmapikey = 'YOUR_PRIVATE_KEY'; // Extracted from your service account JSON file
$url = "https://fcm.googleapis.com/fcm/send";
$headers = [
'Content-Type: application/json',
'Authorization: key=' . $fcmapikey,
];
// Construct the payload based on your specific device token
$data = json_encode([
'to' => $deviceToken, // The client-side token you already have
'notification' => [
'title' => 'New Message',
'body' => 'You have a new message in chat.'
],
'data' => [
'type' => 'chat',
'messageId' => $newMessageId
]
]);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpcode === 200) {
// Notification sent successfully
} else {
// Handle error (e.g., token not registered, quota exceeded)
}
One of the most common pitfalls in this architecture is managing device tokens. These tokens are dynamic; if an app is uninstalled or updates to a new version, the old token becomes invalid immediately. Your PHP script must include logic to refresh these tokens whenever the app registers or re-registers on the client side. Failing to do so will result in high error rates and wasted API quota.
Furthermore, you must be mindful of Firebase's usage quotas. Sending notifications from a shared hosting environment often means hitting rate limits much faster than a dedicated server would. If your chat app sees a spike in activity, consider batching notifications or using the FCM HTTP v1 API with proper retry logic to handle transient failures gracefully.
For more complex routing scenariosâsuch as sending messages only to specific users within a group rather than broadcasting to everyoneâyou will need to fetch the list of active user tokens associated with that chat room from your database before making the API call. This adds a layer of complexity but ensures that your notification costs remain proportional to actual engagement levels.
