Home  >  Q&A  >  body text

Create a Firebase Messaging access token

I can send notifications via Firebase Messaging using the CURL request below. I'm currently using the OAuth 2.0 Playground to obtain access tokens. I need to implement a PHP script to do this. How to generate access token programmatically in PHP?

curl -X POST -k -H 'Authorization: Bearer access_token_goes_here' -H 'Content-Type: application/json' -i 'https://fcm.googleapis.com/v1/projects/projectId/messages:send' --data '{
  "message":{
    "topic" : "newTopic",
    "notification" : {
      "body" : "This is a Firebase Cloud Messaging Topic Message!",
      "title" : "FCM Message"
      }
   }
}

P粉178132828P粉178132828318 days ago378

reply all(1)I'll reply

  • P粉713866425

    P粉7138664252023-12-30 00:15:32

    I found a lot of solutions, but they all require a lot of libraries and dependencies.

    I build my own solution with no additional dependencies. This is the api for getting OAuth2 tokens: https://developers.google.com/identity/protocols/oauth2/service-account#httprest

    The first step is to create a JWT (Json Web Token). Using this JWT, a bearer token can be requested.

    // php doesn't have build-in support for base64UrlEncoded strings, so I added one myself
    function base64UrlEncode($text)
    {
        return str_replace(
            ['+', '/', '='],
            ['-', '_', ''],
            base64_encode($text)
        );
    }
    
    // Read service account details
    $authConfigString = file_get_contents("path_to_the_json_file_jou_downloaded_from_firebase_console.json");
    
    // Parse service account details
    $authConfig = json_decode($authConfigString);
    
    // Read private key from service account details
    $secret = openssl_get_privatekey($authConfig->private_key);
    
    // Create the token header
    $header = json_encode([
        'typ' => 'JWT',
        'alg' => 'RS256'
    ]);
    
    // Get seconds since 1 January 1970
    $time = time();
    
    // Allow 1 minute time deviation
    $start = $time - 60;
    $end = $time + 3600;
    
    $payload = json_encode([
        "iss" => $authConfig->client_email,
        "scope" => "https://www.googleapis.com/auth/firebase.messaging",
        "aud" => "https://oauth2.googleapis.com/token",
        "exp" => $end,
        "iat" => $start
    ]);
    
    // Encode Header
    $base64UrlHeader = base64UrlEncode($header);
    
    // Encode Payload
    $base64UrlPayload = base64UrlEncode($payload);
    
    // Create Signature Hash
    $result = openssl_sign($base64UrlHeader . "." . $base64UrlPayload, $signature, $secret, OPENSSL_ALGO_SHA256);
    
    // Encode Signature to Base64Url String
    $base64UrlSignature = base64UrlEncode($signature);
    
    // Create JWT
    $jwt = $base64UrlHeader . "." . $base64UrlPayload . "." . $base64UrlSignature;
    
    //-----Request token------
    $options = array('http' => array(
        'method'  => 'POST',
        'content' => 'grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer&assertion='.$jwt,
        'header'  =>
            "Content-Type: application/x-www-form-urlencoded"
    ));
    $context  = stream_context_create($options);
    $responseText = file_get_contents("https://oauth2.googleapis.com/token", false, $context);
    
    $response = json_decode($responseText);
    

    $response Contains the bearer token. You should store this token for use by other requests and request a new bearer token when it is about to expire. The maximum lifetime of this bearer token is 1 hour.

    reply
    0
  • Cancelreply