If you want to get the access token manually, without external libraries, you can use this code. It creates a JWT token using your private key, and requests a bearer token.
function base64UrlEncode($text)
{
return str_replace(
['+', '/', '='],
['-', '_', ''],
base64_encode($text)
);
}
// Read service account details
$authConfigString = file_get_contents("path_to_your_private_key_file_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();
$payload = json_encode([
"iss" => $authConfig->client_email,
"scope" => "https://www.googleapis.com/auth/firebase.messaging",
"aud" => "https://oauth2.googleapis.com/token",
"exp" => $time + 3600,
"iat" => $time
]);
// 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 has 3 fields: access_token
, expires_in
, and token_type
.
You should store your token somewhere for future use, and request a new token when it expires, based on the expires_in
. (After 1 hour).
You can also request tokens with a shorter lifetime, but the maximum lifetime of a token is 1 hour.