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

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 6

  1. Anonymous

    s2mjh4

  2. Anonymous

    s2mjh4

  3. Anonymous

    hamr1o

    1. Anonymous

      574y7o

    2. Anonymous

      574y7o

  4. Anonymous

    hamr1o

    1. Anonymous

      aocpi5

    2. Anonymous

      aocpi5

  5. Anonymous

    qzwji3

    1. 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/

      1. Anonymous

        u99nwu

        1. Anonymous

          wwakho

        2. Anonymous

          wwakho

      2. Anonymous

        u99nwu

        1. Anonymous

          7epqbe

        2. Anonymous

          7epqbe

      3. Anonymous

        7jxfyh

      4. Anonymous

        7jxfyh

    2. 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/

      1. Anonymous

        l8mbp5

        1. Anonymous

          baou6d

        2. Anonymous

          baou6d

      2. Anonymous

        l8mbp5

        1. Anonymous

          vamv8q

        2. Anonymous

          vamv8q

      3. Anonymous

        z7b2ty

      4. Anonymous

        z7b2ty

    3. 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/

      1. Anonymous

        z5foly

        1. Anonymous

          2bs5e8

        2. Anonymous

          2bs5e8

      2. Anonymous

        z5foly

        1. Anonymous

          ukappn

        2. Anonymous

          ukappn

      3. Anonymous

        2g6q2v

      4. Anonymous

        2g6q2v

    4. Anonymous

      grpxrr

      1. Anonymous

        dotusw

      2. Anonymous

        dotusw

    5. Anonymous

      grpxrr

      1. Anonymous

        54rhom

      2. Anonymous

        54rhom

    6. Anonymous

      7xk4or

    7. Anonymous

      7xk4or

Leave a comment

Have a challenging product, application or service to build?

We can help you realize your vision.

WhatsApp Icon