如果您想手动获取访问令牌而不使用外部库,可以使用以下代码。它使用您的私钥创建JWT令牌,并请求承载令牌。
function base64UrlEncode($text)
{
return str_replace(
['+', '/', '='],
['-', '_', ''],
base64_encode($text)
);
}
$authConfigString = file_get_contents("path_to_your_private_key_file_downloaded_from_firebase_console.json");
$authConfig = json_decode($authConfigString);
$secret = openssl_get_privatekey($authConfig->private_key);
$header = json_encode([
'typ' => 'JWT',
'alg' => 'RS256'
]);
$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
]);
$base64UrlHeader = base64UrlEncode($header);
$base64UrlPayload = base64UrlEncode($payload);
$result = openssl_sign($base64UrlHeader . "." . $base64UrlPayload, $signature, $secret, OPENSSL_ALGO_SHA256);
$base64UrlSignature = base64UrlEncode($signature);
$jwt = $base64UrlHeader . "." . $base64UrlPayload . "." . $base64UrlSignature;
$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);
响应有3个字段:
access_token
,
expires_in
和
token_type
。
您应该将您的令牌存储在某个地方以备将来使用,并在基于
expires_in
的到期时请求新令牌(1小时后)。
您还可以请求寿命较短的令牌,但是令牌的最长寿命为1小时。