How to Migrate from Legacy FCM APIs to HTTP v1 API in PHP

  • September 19, 2024

    How to Migrate from Legacy FCM APIs to HTTP v1 API in PHP

    With the introduction of the HTTP v1 API, Firebase Cloud Messaging (FCM) has improved security and expanded capabilities. This guide will help you migrate from the legacy FCM APIs to the HTTP v1 API in PHP web development.

    Prerequisites

    1. Service Account Key: Ensure you have a service account JSON key file for your Firebase project. Generate this from the Firebase Console under “Project Settings” > “Service Accounts” > “Generate New Private Key”.
    2. Google Client Library: Ensure the `google/apiclient` package is installed. If not, install it using Composer:
    composer require google/apiclient

    Legacy FCM API (Before)
    Here’s a typical example of using the legacy FCM API to send a message:

    $apiKey = 'your_legacy_server_key';
    $deviceToken = 'device_token';
    $message = [
    'to' => $deviceToken,
    'notification' => [
    'title' => 'Briskbrain',
    'body' => 'This is notification from Briskbrain Team',
    ],
    ];

    $headers = [
    'Authorization: key=' . $apiKey,
    'Content-Type: application/json',
    ];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send');
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($message));

    $response = curl_exec($ch);
    curl_close($ch);
    echo $response;

    HTTP v1 API (After)

    The HTTP v1 API uses OAuth2 for authentication and a different endpoint structure for sending messages. Follow these steps to migrate to the HTTP v1 API.

    1. Authenticate and Get Access Token

    Use the service account JSON file to authenticate and obtain an access token.

    require 'vendor/autoload.php';
    use Google\Client;
    function getAccessToken($serviceAccountPath) {
    $client = new Client();
    $client->setAuthConfig($serviceAccountPath);
    $client->addScope('https://www.googleapis.com/auth/firebase.messaging');
    $client->useApplicationDefaultCredentials();
    $token = $client->fetchAccessTokenWithAssertion();
    return $token['access_token'];
    }

    2. Send a Message Using HTTP v1 API

    With the access token, you can send a message using the HTTP v1 API.

    function sendMessage($accessToken, $projectId, $message) {
    $curlurl = 'https://fcm.googleapis.com/v1/projects/' . $projectId . '/messages:send';
    $headers = [
    'Authorization: Bearer ' . $accessToken,
    'Content-Type: application/json',
    ];
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $curlurl);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(['message' => $message]));
    $response = curl_exec($ch);
    if ($response === false) {
    throw new Exception('Curl error: ' . curl_error($ch));
    }
    curl_close($ch);
    return json_decode($response, true);
    }

    3. Example Usage

    Combine the functions to get an access token and send a message.

    // Path to your service account JSON key file
    $serviceAccountPath = 'path/to/yourdirectory/service-account-file.json';

    // Your Firebase project ID
    $projectId = 'your_firebase_project_id';

    // Example message payload
    $message = [
    'token' => 'device_token',
    'notification' => [
    'title' => 'Briskbrain',
    'body' => 'This is notification from Briskbrain Team',
    ],
    ];
    try {
    $accessToken = getAccessToken($serviceAccountPath);
    $response = sendMessage($accessToken, $projectId, $message);
    echo 'Message sent successfully: ' . print_r($response, true);
    } catch (Exception $e) {
    echo 'Error: ' . $e->getMessage();
    }

    Important Notes

    • Replace `path/to/yourdirectory/service-account-file.json` with the actual path to your service account JSON key file.
    • Replace `your_firebase_project_id` with your actual Firebase project ID.
    • Replace `device_token` with the target device’s FCM token.
    • The `message` array structure should match the HTTP v1 API message format.
    • By following these steps, you can migrate your FCM integration from the legacy API to the HTTP v1 API, taking advantage of improved security and functionality.

    References

    Comments

WhatsApp