建立 Firebase Messaging 訪問令牌
P粉178132828
P粉178132828 2023-12-29 13:01:24
0
1
422

我可以使用下面的 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粉178132828
P粉178132828

全部回覆(1)
P粉713866425

我找到了很多解決方案,但它們都需要大量的程式庫和依賴項。

我建立自己的解決方案,沒有額外的依賴項。這是用於獲取 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 小時。

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板