Firebase Push Notifications with PHP: Secure & Scalable Setup

Why Old Way is getting phased out:

The “old way” of sending push notifications with Firebase Cloud Messaging is by using the HTTP Legacy API. These were accomplished by making a simple HTTP POST to https://fcm.googleapis.com/fcm/send and including a server key for authentication.

Security Concerns: The key used for the authentication process in the old API is a static server type key, which introduces a serious security risk. These are replaced by OAuth 2.0 access tokens with a short lifetime in the new HTTP v1 API. This allows much more security control over finer-grained access.

Fewer Advanced Features: The legacy API does not provide more fine-grained control of message structure, support for FCM Analytics labels, and better integration with modern Google Cloud services, unlike the HTTP v1 API.

Scalability and Flexibility: The HTTP v1 API is more in line with modern Google infrastructure on the cloud, making the system scalable, flexible, and thus seamlessly integrating with any future features of Firebase. The deprecation of the old method encourages developers to use this enhanced, more secure API.

Key Features of New Method (HTTP v1 API):

The new Firebase Cloud Messaging push notification sending method makes use of HTTP v1 API, which is more secure as compared to the legacy API, with some other capabilities like scaling and flexibility.

OAuth 2.0 Authentication: Instead of using the static server key in use, the new API employs the use of OAuth 2.0 access tokens to authenticate. Security has been increased since only authorized entities that bear a valid token are allowed to send notifications. It cuts down on the risk of exposure because the access tokens are short-lived.

JSON Web Token – JWT support: Supported on the new method for more secure, structured authentication, thus allowing more restricted access to resources.

Project-specific Endpoints: This HTTP v1 API applies project-specific URL formatting, for example, https://fcm.googleapis.com/v1/projects/your-project-id/messages:send, which offers better organization and control.

Advanced Message Structure: The new API gives you more freedom in the construction of messages. You can send notifications, data payloads, and even condition-based messages using conditions like topicA && topicB.

Supports FCM Analytics: It allows attaching labels to messages, hence giving much better tracking and analysis of notification performance.

Advantages over Old Way:

Security: OAuth 2.0 replaces the static server keys and hence is harder to abuse.

More Capabilities: Includes support for analytics, conditions of topics, and advanced management of notifications.

Future Proof: It sits easier on Google Cloud infrastructure and paves a way ahead for the future compatibility.

Summing up all these reasons, the new approach offers better security, superior control, and scalability; hence, it is always recommended for FCM notification send-outs.

How to Implement

Implement Firebase Cloud Messaging with PHP for sending push notifications using modern HTTP v1 API with OAuth 2.0 authentication. Learn device topic subscriptions, sending notifications, and handling of tokens in a scalable and future-proof way. Just what the doctor ordered for any PHP developer looking to implement real-time notifications in their web application!

Prerequisites:

  1. Firebase Project
  2. Service Account Key (JSON format from Firebase)
  3. Composer (for PHP dependencies)
  4. Google API Client Library

Steps:

  1. Setup Google Client for OAuth 2.0 Authentication
  2. Subscribe Devices to a Topic
  3. Send a Notification to a Topic
  4. Unsubscribe Devices from the Topic Complete

composer require google/apiclient
Get Access Token Function

This function retrieves an OAuth 2.0 access token by authenticating with Firebase using a service account key. The access token is required to authorize requests made to FCM.

require 'vendor/autoload.php';
use Google\Client;
function getAccessToken() {
    // Path to your service account key JSON file
    $serviceAccountPath = './serviceAccountKey.json'; // Replace with your file path
    // Create a new Google client
    $client = new Client();
    $client->setAuthConfig($serviceAccountPath);
    $client->addScope('https://www.googleapis.com/auth/cloud-platform');
    // Get OAuth 2.0 token
    $accessToken = $client->fetchAccessTokenWithAssertion();
    return $accessToken['access_token'];
}

Subscribe Devices to Topic function
This function subscribes a list of device tokens to a specified FCM topic. It sends an HTTP request to the Firebase Instance ID service, using the access token, to add devices to the topic.

function subscribeDevicesToTopic($deviceTokens, $topic) {
    $url = "https://iid.googleapis.com/iid/v1:batchAdd";
    $payload = [
        'to' => '/topics/' . $topic,
        'registration_tokens' => $deviceTokens,
    ];
    $fields = json_encode($payload);
    $accessToken = getAccessToken();
    $headers = [
        'Authorization: Bearer ' . $accessToken,
        'Content-Type: application/json',
    ];
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
    $result = curl_exec($ch);
    if ($result === FALSE) {
        die('Subscription Error: ' . curl_error($ch));
    }
    curl_close($ch);
    return $result;
}

Send Notification to Topic function:
This function sends a notification (title and body) to all devices subscribed to an FCM topic. It uses the Firebase Cloud Messaging API and the access token for authorization.

function sendFCMNotificationToTopic($topic, $title, $body) {
    $projectId = 'your-project-id'; // Replace with your Firebase project ID
    $url = "https://fcm.googleapis.com/v1/projects/{$projectId}/messages:send";
    $message = [
        'message' => [
            'topic' => $topic,
            'notification' => [
                'title' => $title,
                'body' => $body,
            ],
        ],
    ];
    $fields = json_encode($message);
    $accessToken = getAccessToken();
    $headers = [
        'Authorization: Bearer ' . $accessToken,
        'Content-Type: application/json',
    ];
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
    $result = curl_exec($ch);
    if ($result === FALSE) {
        die('Notification Send Error: ' . curl_error($ch));
    }
    curl_close($ch);
    return $result;
}

Unsubscribe Devices from Topic function:

This function unsubscribes devices from an FCM topic by sending an HTTP request to the Firebase Instance ID service to remove them from the topic.

function unsubscribeDevicesFromTopic($deviceTokens, $topic) {
    $url = "https://iid.googleapis.com/iid/v1:batchRemove";
    $payload = [
        'to' => '/topics/' . $topic,
        'registration_tokens' => $deviceTokens,
    ];
    $fields = json_encode($payload);
    $accessToken = getAccessToken();
    $headers = [
        'Authorization: Bearer ' . $accessToken,
        'Content-Type: application/json',
    ];
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
    $result = curl_exec($ch);
    if ($result === FALSE) {
        die('Unsubscribe Error: ' . curl_error($ch));
    }
    curl_close($ch);
    return $result;
}
Complete Example:

Here is the complete example that shows how to subscribe devices to a topic, send a notification, and then unsubscribe them:

$deviceTokens = [
    'your-device-token-here', // Replace with actual device tokens
    // Add more tokens as needed
];
$topic = 'news'; // Define your topic
// Step 1: Subscribe devices to the topic
$subscribeResponse = subscribeDevicesToTopic($deviceTokens, $topic);
echo "Subscribe Response: " . $subscribeResponse . "\n";
// Step 2: Send notification to the topic
$title = 'Breaking News!';
$body = 'There is a new update for you.';
$notificationResponse = sendFCMNotificationToTopic($topic, $title, $body);
echo "Notification Response: " . $notificationResponse . "\n";
// Step 3: Unsubscribe devices from the topic
$unsubscribeResponse = unsubscribeDevicesFromTopic($deviceTokens, $topic);
echo "Unsubscribe Response: " . $unsubscribeResponse . "\n";

Conclusion:

Using this method you can easily create notification push system inside your web applications, In PHP platform with firebase.

 

Post Comment

Your email address will not be published. Required fields are marked *