【问题标题】:Sending FCM messages to web apps through firebase cloud functions通过 Firebase 云功能向 Web 应用发送 FCM 消息
【发布时间】:2021-06-06 22:42:18
【问题描述】:

当 Firestore 数据字段发生更改时,是否可以通过 Firebase Cloud Functions 发送 FCM 通知,但对于网站,而不是应用程序。除了从 Firebase 控制台发送通知外,还有很多针对 Android 和 iOS 的指导,但对于简单的 Web 应用没有任何指导)。

我一直在尝试找出如何从 Cloud Functions 触发通知,但找不到任何有用的东西。

例如,我的数据库结构如下:

  • 集合:用户
  • 文档:使用用户 ID 命名的文档
  • 数据字段:字段 1 到 5。字段 5 存储 FCM 令牌。字段 1 存储其状态(在线、离线、离线待处理消息)。

我想确保当数据字段 1 发生更改(变为“离线待处理消息”)时,相关用户会收到通知(基于文档 ID)。

编辑:在下面添加代码以供参考

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotification = functions.database.ref('/users/{doc}/{Hears}')
    .onUpdate(async (change, context) => {

        const db = admin.firestore();
        db.collection('users').doc(context.params.userId)  // get userId
        .get()
        .then(doc => {
            //this is intended to get the FCM token stored in the user's document
           const fcmToken = doc.data().usrTkn;
           // Notification details
            const payload = {
            notification: {
                title: 'You have a new message.',
                body: 'Open your app'
            }
        };
     })
    //This should send a notification to the user's device when web app is not in focus. 
    //FCM is set up in service worker
     const response = await admin.messaging().sendToDevice(fcmToken, payload);
     console.log(response);

    });

【问题讨论】:

    标签: javascript google-cloud-firestore google-cloud-functions firebase-cloud-messaging


    【解决方案1】:

    向网络应用程序发送消息与向本机移动应用程序发送消息没有什么不同,因此您发现的发送部分指南同样适用。 Firebase 文档甚至包含sending notifications on a Realtime Database trigger 的示例,对 Firestore 执行相同操作也不会有太大不同。

    如果您在发送消息时遇到特定问题,我建议您展示您尝试过的方法以及无法解决的问题。


    更新:您的代码不起作用(无论您将通知发送到哪种设备),因为您没有在代码中处理 get() 的异步性质。

    解决这个问题的最简单方法是在那里也使用await,就像调用sendToDevice 时一样。所以:

    const functions = require('firebase-functions');
    const admin = require('firebase-admin');
    admin.initializeApp(functions.config().firebase);
    exports.sendNotification = functions.database.ref('/users/{doc}/{Hears}')
        .onUpdate(async (change, context) => {
            const db = admin.firestore();
            const doc = await db.collection('users').doc(context.params.userId).get();
            const fcmToken = doc.data().usrTkn;
            const payload = {
              notification: {
                title: 'You have a new message.',
                body: 'Open your app'
              }
            };
            const response = await admin.messaging().sendToDevice(fcmToken, payload);
            console.log(response);
        })
    

    我强烈建议花一些时间了解asynchronous callsclosuresasync/await,以及如何使用debug something like this by adding logging

    【讨论】:

    • 感谢您调查此事,弗兰克。我试了一下并部署了该功能,但是当我测试用户文档(“听到”数据字段)的更新时,我没有收到我希望的预期通知。当我在窗口中时,甚至没有控制台日志(我通过 firebase 控制台测试了 FCM 通知,它在那里工作得很好)。
    • 这里很难进一步提供帮助。你检查了我提供的链接。他们是否至少解释了为什么我的答案中的代码解决了您问题中的代码的一些问题?
    • 我最终将数据发送到云函数以发送到 FCM(有效负载和设备令牌)。我必须花更多时间在异步/等待的东西上,但我的主要收获是理解“sendToDevice”部分,这很有帮助。谢谢!
    • 很高兴听到你成功了@user3385829 ?
    猜你喜欢
    • 2016-09-21
    • 1970-01-01
    • 2021-04-04
    • 2021-09-19
    • 1970-01-01
    • 1970-01-01
    • 2017-03-10
    • 2020-07-28
    相关资源
    最近更新 更多