skip to Main Content

I can send notification using Firebase Messaging using the CURL request below. I am using currently using the OAuth 2.0 Playground to get an access token. I need to implement a PHP script to do this. How can generate the 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"
      }
   }
}

2

Answers


  1. I found a lot of solutions, but all of them needed a lot of libraries and dependencies.

    I build my own solution, without extra dependencies. This is the api for getting a OAuth2 token: https://developers.google.com/identity/protocols/oauth2/service-account#httprest

    The first step is to create a JWT (Json Web Token). With that 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);
    

    The $response contains the bearer token. You should store this token for other requests, and request a new bearer token when it almost expires. The maximum lifetime of this bearer token is 1 hour.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search