【问题标题】:How to send push notifications to specific users with Cloud Functions for Firebase如何使用 Cloud Functions for Firebase 向特定用户发送推送通知
【发布时间】:2017-10-08 08:35:55
【问题描述】:

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

例如,当数据库的 adminName 节点发生写入时,我将如何在下面的代码中向具有 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);
        });
    });

【问题讨论】:

  • 您必须拥有该特定用户的注册令牌并使用sendToDevice

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


【解决方案1】:

进行以下更改。它对我有用

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);
}
});

【讨论】:

    猜你喜欢
    • 2017-10-29
    • 2017-11-16
    • 2020-05-26
    • 2018-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-18
    相关资源
    最近更新 更多