You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PHP中为Firebase Messaging生成Access Token

在PHP中程序化生成Firebase Messaging的OAuth 2.0 Access Token

前置准备

  • 从Firebase控制台获取服务账号私钥JSON文件:进入项目设置 → 服务账号 → 点击「生成新私钥」,下载后保存为service-account.json,放在PHP项目目录下(注意设置文件权限,避免公开访问)。
  • 安装依赖:使用Composer安装JWT库,执行命令:
    composer require firebase/php-jwt
    

步骤1:生成Access Token

以下PHP代码会读取服务账号密钥,构建JWT断言并向Google OAuth服务器请求Access Token:

<?php
require 'vendor/autoload.php';

use Firebase\JWT\JWT;

// 读取服务账号JSON
$serviceAccount = json_decode(file_get_contents('service-account.json'), true);

// JWT配置
$privateKey = $serviceAccount['private_key'];
$clientEmail = $serviceAccount['client_email'];
$tokenEndpoint = 'https://oauth2.googleapis.com/token';
$audience = $tokenEndpoint;
$issuedAt = time();
$expiresAt = $issuedAt + 3600; // Token有效期1小时

// 构建JWT Payload
$payload = [
    'iss' => $clientEmail,
    'sub' => $clientEmail,
    'aud' => $audience,
    'iat' => $issuedAt,
    'exp' => $expiresAt,
    'scope' => 'https://www.googleapis.com/auth/firebase.messaging' // FCM所需权限
];

// 生成JWT
$jwt = JWT::encode($payload, $privateKey, 'RS256');

// 请求Access Token
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $tokenEndpoint);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
    'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
    'assertion' => $jwt
]));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/x-www-form-urlencoded'
]);

$response = curl_exec($ch);
curl_close($ch);

$tokenData = json_decode($response, true);
$accessToken = $tokenData['access_token'] ?? null;

if (!$accessToken) {
    die('获取Access Token失败:' . json_encode($tokenData));
}

步骤2:使用Access Token发送FCM通知

拿到$accessToken后,即可用PHP实现FCM通知发送逻辑:

// FCM发送请求配置
$fcmEndpoint = 'https://fcm.googleapis.com/v1/projects/' . $serviceAccount['project_id'] . '/messages:send';
$postData = [
    'message' => [
        'topic' => 'newTopic',
        'notification' => [
            'body' => 'This is a Firebase Cloud Messaging Topic Message!',
            'title' => 'FCM Message'
        ]
    ]
];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $fcmEndpoint);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Authorization: Bearer ' . $accessToken,
    'Content-Type: application/json'
]);

$fcmResponse = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

echo 'FCM请求状态码:' . $httpCode . PHP_EOL;
echo 'FCM响应内容:' . $fcmResponse . PHP_EOL;

注意事项

  • 服务账号JSON文件要妥善保管,不要提交到版本控制系统或公开访问。
  • Access Token有效期为1小时,建议缓存token,避免重复请求。
  • 确保服务器能访问oauth2.googleapis.com和fcm.googleapis.com两个域名,无防火墙限制。

内容的提问来源于stack exchange,提问作者Noor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 09:01:33