gpt4 book ai didi

javascript - JavaScript 中的 Firebase 云消息传递 AJAX POST

转载 作者:行者123 更新时间:2023-11-28 14:31:36 24 4
gpt4 key购买 nike

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

$.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

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

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() 并在 promise 中获取结果并将其发送出去,如下所示:

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

然后在服务器上,您会收到该信息,并将其存储在数据库中(可能与他们的个人资料信息相关)。

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

通常是 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
]);

关于javascript - JavaScript 中的 Firebase 云消息传递 AJAX POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51275501/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com