使用 php 的 Firebase 推送通知出现问题

问题描述 投票:0回答:1

我想使用 PHP 发送推送通知,但收到此错误。 { “错误”: { “代码”:401, "message": "请求的身份验证凭据无效。需要 OAuth 2 访问令牌、登录 cookie 或其他有效的身份验证凭据。请参阅 https://developers.google.com/identity/sign-in/web/devconsole-project。" , “状态”:“未经身份验证” } }

这是我的 PHP 代码:-

  <?PHP

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Get the form data
$topic = $_POST['topic'];
$title = $_POST['title'];
$body = $_POST['body'];
$imageURL = $_POST['image_url'];

// Validate the data (you may want to add more robust validation)
if (empty($topic) || empty($title) || empty($body)) {
    die('Error: All fields are required.');
}

// Your Firebase project's server key
$serverKey = 'my key';

// FCM endpoint
$url = 'https://fcm.googleapis.com/v1/projects/myprojectid/messages:send';

// Message data
$message = [
    'message' => [
        'topic' => $topic,
        'notification' => [
            'title' => $title,
            'body' => $body,
        ],
    ],
];

// Check if an image URL is provided
if (!empty($imageURL)) {
    $message['message']['data']['image_url'] = $imageURL;
}

// Headers
$headers = [
    'Authorization: Bearer ' . $serverKey,
    'Content-Type: application/json',
];

// Initialize cURL session
$ch = curl_init($url);

// Set cURL options
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($message));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// Execute cURL session and get the response
$response = curl_exec($ch);

// Close cURL session
curl_close($ch);

// Print the response (for debugging purposes)
echo $response;
} else {
// If the request method is not POST, redirect or handle accordingly
header('Location: index.php');
exit();
}

?>
php push-notification google-cloud-messaging
1个回答
0
投票

看起来您正在使用旧的 FCM 服务器密钥调用

v1
API。从升级指南的授权请求部分来看,新 API 似乎不再支持:

HTTP v1 发送请求需要 OAuth 2.0 访问令牌,而不是旧请求中使用的服务器密钥字符串。

因此,您需要创建一个 OAuth 2 令牌并将其传递到

Authorization
中。

© www.soinside.com 2019 - 2024. All rights reserved.