[英]Firebase Cloud Messaging AJAX POST in JavaScript
我有以下用于测试目的的代码:
$.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"
}
}
我究竟做错了什么?
从广义上讲,您在做的错误是尝试从Web浏览器客户端调用FCM API。 FCM消息旨在从完全由您控制的后端服务器发送。 您需要发送的授权令牌将有效地具有管理员特权,可以向任何和所有用户发送消息,并且您不想将其放弃给客户端 ,因为这是一个巨大的安全问题。
从文档中 :
从您的应用服务器或可信环境发送到FCM的请求必须经过授权。 FCM HTTP v1 API使用为与Firebase项目关联的服务帐户生成的短期OAuth 2.0访问令牌。 旧协议使用从Firebase控制台检索到的API密钥。 在这两种情况下,都必须将必需的凭据添加到发送到FCM的每个消息请求中。
换句话说,您不应授予客户访问权限,以使用特权服务帐户凭据发送邮件。 该文档页面的其余部分描述了如何实际完成对发送请求的授权。
在文档中,我们链接了注释: 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 GuzzleHttp\Client();
// 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
]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.