通过 firebase 云函数将 FCM 消息发送到 Web 应用程序

Sending FCM messages to web apps through firebase cloud functions

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

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

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

我想确保当数据字段 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);

    });

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

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


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

解决这个问题的最简单方法是在那里也使用 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 calls, closures, async/await, and how to debug something like this by adding logging