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

    Anonymous
    Anonymous

    s2mjh4

    Reply
    Anonymous
    Anonymous

    hamr1o

    Reply
    Anonymous
    Anonymous

    574y7o

    Reply
    Anonymous
    Anonymous

    574y7o

    Reply
    Anonymous
    Anonymous

    hamr1o

    Reply
    Anonymous
    Anonymous

    aocpi5

    Reply
    Anonymous
    Anonymous

    aocpi5

    Reply
    Anonymous
    Anonymous

    qzwji3

    Reply
    Anonymous
    Anonymous

    grpxrr

    Reply
    Anonymous
    Anonymous

    54rhom

    Reply
    Anonymous
    Anonymous

    54rhom

    Reply
    Anonymous
    Anonymous

    grpxrr

    Reply
    Anonymous
    Anonymous

    dotusw

    Reply
    Anonymous
    Anonymous

    dotusw

    Reply
    Anonymous
    Anonymous

    My spouse aand I stumbled over here from a dijfferent web page and thought I might as well check things out. I like what I see so now i'm following you. Look forward to looking over your web page again. http://boyarka-inform.com/

    Reply
    Anonymous
    Anonymous

    2g6q2v

    Reply
    Anonymous
    Anonymous

    2g6q2v

    Reply
    Anonymous
    Anonymous

    z5foly

    Reply
    Anonymous
    Anonymous

    ukappn

    Reply
    Anonymous
    Anonymous

    ukappn

    Reply
    Anonymous
    Anonymous

    z5foly

    Reply
    Anonymous
    Anonymous

    2bs5e8

    Reply
    Anonymous
    Anonymous

    2bs5e8

    Reply
    Anonymous
    Anonymous

    I've been surfing online more than 4 hours today, yeet I never found any interesting article like yours. It is pretty worth enlugh for me. In myy opinion, if all site owners and bloggers ade good content as you did, the web will be a lot more useful than ever before. http://Boyarka-Inform.com/

    Reply
    Anonymous
    Anonymous

    z7b2ty

    Reply
    Anonymous
    Anonymous

    z7b2ty

    Reply
    Anonymous
    Anonymous

    l8mbp5

    Reply
    Anonymous
    Anonymous

    vamv8q

    Reply
    Anonymous
    Anonymous

    vamv8q

    Reply
    Anonymous
    Anonymous

    l8mbp5

    Reply
    Anonymous
    Anonymous

    baou6d

    Reply
    Anonymous
    Anonymous

    baou6d

    Reply
    Anonymous
    Anonymous

    you're in point of fact a just right webmaster. The site loading speed iss incredible. It seems that you are doing any unique trick. In addition, The contents arre masterwork. you've perfrmed a magnificent process on this topic! http://Boyarka-Inform.com/

    Reply
    Anonymous
    Anonymous

    7jxfyh

    Reply
    Anonymous
    Anonymous

    7jxfyh

    Reply
    Anonymous
    Anonymous

    u99nwu

    Reply
    Anonymous
    Anonymous

    7epqbe

    Reply
    Anonymous
    Anonymous

    7epqbe

    Reply
    Anonymous
    Anonymous

    u99nwu

    Reply
    Anonymous
    Anonymous

    wwakho

    Reply
    Anonymous
    Anonymous

    wwakho

    Reply
    Anonymous
    Anonymous

    qzwji3

    Reply
    Anonymous
    Anonymous

    k9v4bo

    Reply
    Anonymous
    Anonymous

    k9v4bo

    Reply
    Anonymous
    Anonymous

    43fyr9

    Reply
    Anonymous
    Anonymous

    r9ngyg

    Reply
    Anonymous
    Anonymous

    r9ngyg

    Reply
    Anonymous
    Anonymous

    43fyr9

    Reply
    Anonymous
    Anonymous

    jbetgu

    Reply
    Anonymous
    Anonymous

    jbetgu

    Reply
WhatsApp