JavaScript中的Firebase云消息AJAX POST



我有以下用于测试目的的代码:

$.ajax({
url: 'https://fcm.googleapis.com/v1/projects/[PROJECT]/messages:send',
type: 'POST',
headers:{
"Authorization":"Bearer "+[Access Token from FireBase Auth]
},
contentType:"application/json",
data: {
"message":{
"token": [TOKEN from messaging.getToken],
"notification" : {
"body" : "This is an FCM notification message!",
"title" : "FCM Message",
}
}
},
success: function () { },
error: function () { },
});

这总是导致以下带有401((的响应。。。

{
"error": {
"code": 401,
"message": "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
"status": "UNAUTHENTICATED"
}
}

我做错了什么?

在我们在注释中链接的文档中:https://firebase.google.com/docs/cloud-messaging/js/first-message

检索注册令牌下,您会看到以下代码:

messaging.getToken().then(function(currentToken) {
if (currentToken) {
sendTokenToServer(currentToken);
updateUIForPushEnabled(currentToken);
} else {
// Show permission request.
console.log('No Instance ID token available. Request permission to generate one.');
// Show permission UI.
updateUIForPushPermissionRequired();
setTokenSentToServer(false);
}
}).catch(function(err) {
console.log('An error occurred while retrieving token. ', err);
showToken('Error retrieving Instance ID token. ', err);
setTokenSentToServer(false);
});

你会注意到sendTokenToServer()函数,这不是他们的函数,应该是你的。你打电话给他们的getToken(),在承诺中,你会得到结果并发送出去,看起来像这样:

function sendTokenToServer(currentToken) {
$.post({
url: 'yourServer.com/some_token_receiving_endpoint',
type: 'post',
data: {token: currentToken}
});
}

然后在服务器上,您会收到它,并将其存储在数据库中,可能与他们的配置文件信息相关。

然后,无论是在那一刻,还是在以后,您都可以查询数据库中想要通知的人,获取该令牌,并结合安全存储在服务器上的访问令牌,然后从那里发送通知。

通常是NodeJS、PHP、Python或Ruby。当事件发生时,或者按照时间表,你的服务器可以发送这样的通知:

<?php
// Get some http client service  for your language
$client = new GuzzleHttpClient();
// Get your user or users (with their tokens that you've stored)
$user = Db.someQueryReturningUser();
// Your message
$jsonData = '{
"message":{
"token": [TOKEN from messaging.getToken],
"notification" : {
"body" : "This is an FCM notification message!",
"title" : "FCM Message",
}
}
}';
// Send Mesage
$client->post('https://fcm.googleapis.com/v1/projects/[PROJECT]/messages:send',
[ 
'headers' => [
'Authorization' => 'Bearer ' . [Access Token from FireBase Auth]
],
'json' => $jsonData
]);

从广义上讲,您做错的是试图从web浏览器客户端调用FCM API。FCM消息旨在从您完全控制的后端服务器发送。您需要发送的授权令牌将有效地拥有向任何和所有用户发送消息的管理员权限,并且您不想将其交给客户端,因为这是一个巨大的安全问题。

来自文件:

从应用服务器或可信环境发送到FCM的请求必须获得授权。FCM HTTP v1 API使用短暂的OAuth 2.0访问为与您的Firebase关联的服务帐户生成的令牌项目遗留协议使用从中检索的长期API密钥Firebase控制台。在这两种情况下,都必须添加必需的发送给FCM的每个消息请求的凭证。

换句话说,您不应该允许客户端使用您的特权服务帐户凭据发送消息。该页文档的其余部分描述了如何实际完成对发送请求的授权。

最新更新