【发布时间】:2021-04-20 07:05:56
【问题描述】:
我需要通过 fcm 中的主题来实现广播通知。我正在使用 firebase-admin 发送这些。任何人都可以发布代码的 sn-p 以通过 node.js 发送这些通知吗?
【问题讨论】:
标签: node.js firebase firebase-cloud-messaging backend
我需要通过 fcm 中的主题来实现广播通知。我正在使用 firebase-admin 发送这些。任何人都可以发布代码的 sn-p 以通过 node.js 发送这些通知吗?
【问题讨论】:
标签: node.js firebase firebase-cloud-messaging backend
const topic = "test";
const payload = {
notification: {
title: "New news",
body: "2:45",
},
};
admin
.messaging()
.sendToTopic(topic, payload)
.then((response2) => {
// Response2 is a message ID string.
console.log("Successfully sent message:", response2);
})
.catch((error) => {
console.log("Error sending message:", error);
});
【讨论】:
首先您需要为用户订阅给定的主题
// These registration tokens come from the client FCM SDKs.
var registrationTokens = [
'YOUR_REGISTRATION_TOKEN_1',
// ...
'YOUR_REGISTRATION_TOKEN_n'
];
// Subscribe the devices corresponding to the registration tokens to the
// topic.
admin.messaging().subscribeToTopic(registrationTokens, topic)
.then(function(response) {
// See the MessagingTopicManagementResponse reference documentation
// for the contents of response.
console.log('Successfully subscribed to topic:', response);
})
.catch(function(error) {
console.log('Error subscribing to topic:', error);
});
然后您可以使用
广播通知// The topic name can be optionally prefixed with "/topics/".
var topic = 'highScores';
var message = {
data: {
score: '850',
time: '2:45'
},
topic: topic
};
// Send a message to devices subscribed to the provided topic.
admin.messaging().send(message)
.then((response) => {
// Response is a message ID string.
console.log('Successfully sent message:', response);
})
.catch((error) => {
console.log('Error sending message:', error);
});
您可以阅读更多关于它的信息here
【讨论】:
你需要 Firebase 项目 设备注册令牌 firebase 云功能
firebase 通知的工作: 设备到设备通知: 从设备 1 - firebase 数据库(函数在写入数据库时触发) -firebase 云功能(云功能将向 dev 2 发送通知)- device2
【讨论】: