如何从实时数据库中检索保存的设备令牌并使用Firebase云功能向其发送通知?



我想向一小组设备发送通知,因此我想在Firebase云函数中使用"SendToDevice"选项。我不熟悉javascript,所以请帮助我从Firebase实时数据库中检索令牌并向他们发送通知。

存储在我的数据库中的设备令牌的结构,这些键是令牌:

{   
"tokens" : {
"-KdD1f0ecmVXHZ3H3abZ" : {
"token" : "true",
},
"-KdG4iHEYjInv7ljBhgG" : {
"token" : "true",
}
}

错误:Firebase.child 失败:第一个参数是无效路径: "/shopdata/${shopKey/${acYear}/notestokens/${sectionKey}".路径必须 为非空字符串,不能包含"."、"#"、"$"、"["或"]">

我尝试删除这些美元符号,但再次收到日志消息"没有要发送到的通知令牌"。

这是我的代码:

exports.sendClassNotesNotification = functions.database.ref('/shopdata/{shopKey}/{year}/notes/{sectionKey}').onWrite(event => {
const shopdata = event.params.shopdata;
const year = event.params.year;
const sectionKey = event.params.sectionKey;
// Get the list of device notification tokens.
const getDeviceTokensPromise = admin.database().ref('/shopdata/${shopKey/${year}/notestokens/${sectionKey}').once('value');
return Promise.all([getDeviceTokensPromise]).then(results => {
const tokensSnapshot = results[0];
// Check if there are any device tokens.
if (!tokensSnapshot.hasChildren()) {
return console.log('There are no notification tokens to send to.');
}
const payload = {
notification: {
title: 'Section Note',
body: `You have new note`
}
};
// Listing all tokens.
const tokens = Object.keys(tokensSnapshot.val());
// Send notifications to all tokens.
return admin.messaging().sendToDevice(tokens, payload);
});
});

做这样的事情,记住你必须从 .once('value') 返回承诺。

exports.pushNotification = functions.database.ref('/groupchat/{pushId}').onWrite( event => {
return admin.database().ref('/tokens/...refrence...').once('value')
.then(function(tokensSnapshot){
const tokens = Object.keys(tokensSnapshot.val());
const payload = {
notification: {
title: 'App Name',
body: "New Message",
sound: "default"
}   
};
return admin.messaging().sendToDevice(tokens, payload);
});
});

有关工作代码示例,请在此处查看官方示例存储库。

最新更新