Manoj Damor

Unlock the World of Coding with Coding Funda

How to Generate Access Token for Firebase Push Notifications (FCM) in 2024

Firebase Cloud Messaging (FCM) is a powerful tool for sending push notifications to Android, iOS, and web applications. As of 2024, Firebase’s v1 API requires OAuth 2.0 access tokens to authenticate requests. This guide walks you through the steps to generate an OAuth 2.0 access token using Firebase service account credentials for sending push notifications via FCM.

1. Prerequisites

Before starting, make sure you have:

  • A Firebase project.
  • A service account JSON file from your Firebase project.
  • PHP, Node.js, or any other server-side language set up to make HTTP requests.

Step-by-Step Guide to Generate Firebase Access Token for FCM

Step 1: Create a Firebase Project

If you haven’t already, you’ll need to create a Firebase project:

  1. Go to the Firebase Console.
  2. Click on “Add Project” and follow the setup steps.

Step 2: Generate Service Account Credentials

Firebase allows you to manage server-to-server interactions through service accounts. To generate a service account for your Firebase project:

  1. Open your project in the Firebase Console.
  2. In the left sidebar, navigate to Project Settings (the gear icon).
  3. Go to the Service Accounts tab.
  4. Click Generate New Private Key to download your service account JSON file.

This file contains the necessary credentials (client email, private key, etc.) to generate access tokens.

Step 3: Create a JWT to Obtain OAuth 2.0 Token

You must use the credentials in the service account file to generate a JSON Web Token (JWT). Firebase’s v1 API requires an OAuth 2.0 token, which is obtained by signing a JWT using the private key in the service account file.

What is JWT?

JWT (JSON Web Token) is a standard for creating tokens that assert certain claims, like authentication, which are signed using a cryptographic algorithm.

Step 4: Generate JWT Programmatically

Here’s how you can generate a JWT using the service account’s private key in PHP:

PHP Code to Generate JWT:
<?php

// Path to your Firebase service account key file
define('SERVICE_ACCOUNT_FILE', 'path/to/your-service-account-file.json');

/**
 * Function to generate JWT for OAuth 2.0.
 */
function generateJWT() {
    $serviceAccount = json_decode(file_get_contents(SERVICE_ACCOUNT_FILE), true);

    // JWT Header
    $header = base64url_encode(json_encode([
        'alg' => 'RS256',
        'typ' => 'JWT'
    ]));

    // JWT Claims
    $now = time();
    $claimSet = base64url_encode(json_encode([
        'iss' => $serviceAccount['client_email'],  // Service account email
        'scope' => 'https://www.googleapis.com/auth/firebase.messaging',  // Scope for Firebase messaging
        'aud' => $serviceAccount['token_uri'],  // Google OAuth token URI
        'exp' => $now + 3600,  // Token expiration (1 hour)
        'iat' => $now  // Token issued at
    ]));

    // Combine header and claim set
    $signatureInput = $header . '.' . $claimSet;

    // Sign the JWT using the private key from the service account
    $signature = '';
    openssl_sign($signatureInput, $signature, $serviceAccount['private_key'], 'SHA256');

    // Combine all parts to form the JWT
    $jwt = $signatureInput . '.' . base64url_encode($signature);

    return $jwt;
}

/**
 * Helper function to encode base64 URLs (URL-safe).
 */
function base64url_encode($data) {
    return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}

// Example usage: Generate JWT
$jwt = generateJWT();
echo "Generated JWT: " . $jwt;
?>

Step 5: Obtain the Access Token

Once you have the JWT, the next step is to obtain the OAuth 2.0 access token. You’ll need to make an HTTP POST request to Google’s OAuth 2.0 token endpoint.

PHP Code to Obtain Access Token:
<?php

/**
 * Function to get OAuth 2.0 access token using JWT.
 */
function getAccessToken() {
    // Call the generateJWT() function to get the JWT
    $jwt = generateJWT();

    // Initialize cURL
    $ch = curl_init();

    // Set the URL for the Google OAuth 2.0 token endpoint
    curl_setopt($ch, CURLOPT_URL, 'https://oauth2.googleapis.com/token');
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    // Set the POST fields (grant_type and assertion)
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
        'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
        'assertion' => $jwt
    ]));

    // Execute the cURL request
    $response = curl_exec($ch);

    // Check for errors
    if (curl_errno($ch)) {
        die('Curl error: ' . curl_error($ch));
    }

    // Close cURL
    curl_close($ch);

    // Decode the response (OAuth token)
    $jsonResponse = json_decode($response, true);

    // Return the access token
    return $jsonResponse['access_token'];
}

// Example usage: Get access token
$accessToken = getAccessToken();
echo "Access Token: " . $accessToken;
?>

Step 6: Use the Access Token to Send Firebase Notifications

Once you’ve obtained the OAuth 2.0 access token, you can use it to send Firebase Cloud Messaging notifications.

PHP Code to Send FCM Notification:
<?php

/**
 * Function to send FCM notification using OAuth 2.0 access token.
 */
function sendFCMNotification($deviceToken, $title, $body, $data = []) {
    // Get the OAuth 2.0 access token
    $accessToken = getAccessToken();

    // FCM v1 API URL
    $url = 'https://fcm.googleapis.com/v1/projects/YOUR_PROJECT_ID/messages:send';

    // Prepare the notification payload
    $payload = [
        'message' => [
            'token' => $deviceToken,
            'notification' => [
                'title' => $title,
                'body' => $body
            ],
            'data' => $data  // Optional custom data
        ]
    ];

    // Initialize cURL
    $ch = curl_init();

    // Set cURL options
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Authorization: Bearer ' . $accessToken,
        'Content-Type: application/json'
    ]);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));

    // Execute the cURL request
    $response = curl_exec($ch);

    // Check for errors
    if ($response === false) {
        die('Curl error: ' . curl_error($ch));
    }

    // Close cURL
    curl_close($ch);

    // Return the response
    return $response;
}

// Example usage
$deviceToken = 'YOUR_DEVICE_TOKEN';  // Replace with the actual device token
$title = 'Test Notification';
$body = 'This is a test notification using Firebase v1 API in 2024.';
$customData = ['key1' => 'value1', 'key2' => 'value2'];

// Send the notification
$response = sendFCMNotification($deviceToken, $title, $body, $customData);

// Output the response
echo $response;
?>

Final Steps

  • Test your notification: Ensure the device token is valid, and test sending notifications.
  • Use logging: Add logging or print statements to check responses and errors during the notification sending process.

Conclusion

By following this guide, you can manually generate OAuth 2.0 access tokens and use them to send Firebase push notifications in 2024 using the Firebase v1 API. This solution doesn’t require additional libraries like Composer, and you can adapt it to other server-side languages by applying similar principles for generating and signing JWTs.

Check My Social Profile Links

Instagram

Youtube

Website

Linkedin

Android Application

About The Author

Leave a Reply

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

Follow by Email
fb-share-icon
Share