我可以使用下面的 CURL 请求通过 Firebase Messaging 发送通知。我当前正在使用 OAuth 2.0 Playground 来获取访问令牌。我需要实现一个 PHP 脚本来执行此操作。如何在 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粉7138664252023-12-30 00:15:32
我找到了很多解决方案,但它们都需要大量的库和依赖项。
我构建自己的解决方案,没有额外的依赖项。这是用于获取 OAuth2 令牌的 api:https://developers. google.com/identity/protocols/oauth2/service-account#httprest
第一步是创建 JWT(Json Web 令牌)。使用该 JWT,可以请求不记名令牌。
// 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
包含不记名令牌。您应该存储此令牌以供其他请求使用,并在其即将过期时请求新的不记名令牌。该不记名令牌的最长生命周期为 1 小时。