首页 > 解决方案 > 如何编写 Firebase 云消息传递功能以发送推送通知

问题描述

我正在尝试通过 FCM 从管理界面向用户发送推送通知,我得到了用户订阅管理员主题的部分。

当我从 Firebase 控制台发送通知时,它正在工作。管理员可以将数据上传到 Firebases 实时数据库,其中包括通知文本和主题(如果缺少某些内容,请告诉我)。

如何编写在通知上传到实时数据库时触发的 Firebase函数,并向订阅该主题的用户发送通知?如果有人能与我分享一个例子,我会很高兴,因为我不熟悉 node.js ......谢谢!

标签: node.jsfirebasepush-notificationdartflutter

解决方案


您需要的是此处概述的数据库触发器。您可以编写如下函数:

exports.sendNotification = functions.database  
            .ref('/notification/{topicId}/messages/{messageId}')
            .onCreate((snapshot, context) => {


    const topicId  = context.params.topicId;
    const messageId = context.params.messageId;
    const summaryLabel = topicId +"-"messageId; 
    const receivedOn = Date.now();

    const payload = {

        data: {
            topicId: topicId,
            messageId: messageId,
            time: receivedOn
        },

        notification: {
            title: "Notification Title",
            body: summaryLabel,
            icon: '/img/blue_map_icon.png',
            click_action: `https://${process.env.GCLOUD_PROJECT}.firebaseapp.com`,
            sound: "default"
        }
    };

    const options = {
        priority: "high",
        timeToLive: 60 * 60 * 2
    }; 

    return admin.messaging().sendToTopic(topicId, payload, options);


});

推荐阅读