node.js - 如何使用 Cloud Functions for Firebase 向特定用户发送推送通知

标签 node.js firebase firebase-realtime-database firebase-cloud-messaging google-cloud-functions

我使用 Firebase 作为我的 Android 应用程序的后端,并且对使用 Cloud Functions for Firebase 非常陌生,我想知道在事件发生时如何向特定用户发送推送通知。

例如,当数据库的 adminName Node 发生写入时,我如何在下面的代码中向具有 uId 的用户发送推送通知:

exports.sendNotification = functions.database.ref('/users/{uId}/groups/{adminName}')
    .onWrite(event => {

    // Grab the current value of what was written to the Realtime Database.
    var eventSnapshot = event.data;
    var str1 = "Author is ";
    var str = str1.concat(eventSnapshot.child("author").val());
    console.log(str);

    var topic = "android";
    var payload = {
        data: {
            title: eventSnapshot.child("title").val(),
            author: eventSnapshot.child("author").val()
        }
    };

    // Send a message to devices subscribed to the provided topic.
    return admin.messaging().sendToTopic(topic, payload)
        .then(function (response) {
            // See the MessagingTopicResponse reference documentation for the
            // contents of response.
            console.log("Successfully sent message:", response);
        })
        .catch(function (error) {
            console.log("Error sending message:", error);
        });
    });

最佳答案

进行以下更改。对我有用

const functions = require('firebase-functions');
const admin = require('firebase-admin');

admin.initializeApp(functions.config().functions);

var newData;

exports.myTrigger = functions.firestore.document('TestCollection/{id}').onWrite(async (snapshot, context) => {
//

if (snapshot.empty) {
    console.log('No Devices');
    return;
}

newData = snapshot.data();

const deviceIdTokens = await admin
    .firestore()
    .collection('DeviceIDTokens')
    .get();

var tokens = [];

for (var token of deviceIdTokens.docs) {
    tokens.push(token.data().device_token);
}
var payload = {
    notification: {
        title: 'Push Title',
        body: 'Push Body',
        sound: 'default',
    },
    data: {
        push_key: 'Push Key Value',
        key1: newData.data,
    },
};

try {
    const response = await admin.messaging().sendToDevice(tokens, payload);
    console.log('Notification sent successfully');
} catch (err) {
    console.log(err);
}
});

关于node.js - 如何使用 Cloud Functions for Firebase 向特定用户发送推送通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43879872/

相关文章:

firebase - Firestore onSnapshot 更新事件是否由于本地客户端设置而导致?

javascript - angularfiresignedIn 函数仅在页面刷新时评估?

javascript - Firebase 事务返回 null 并无错误地完成

javascript - 检查用户是否在 Firebase 中在线

Node.JS 在不同机器上使用 Nginx 进行反向代理

node.js - 如何将 Jade 模板编译成 JavaScript 函数以在客户端使用它们?

swift - 在我的设备上没有收到通知,只是在控制台中

ios - 与 Firebase 一起创建 DataManger

node.js - NodeJS 使用 Moment 将日期保存到 MongoDB

node.js - 如何使用 `bodyParser.raw()`获取raw body?