繁体   English   中英

通过 firebase 云函数向 web 应用发送 FCM 消息

[英]Sending FCM messages to web apps through firebase cloud functions

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

我一直在尝试找出如何从 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);

    });

将消息发送到 web 应用程序与将消息发送到本机移动应用程序没有什么不同,因此您找到的指南的发送部分同样适用。 Firebase 文档甚至包含在实时数据库触发器上发送通知的示例,并且对 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);
    })

我强烈建议花一些时间来学习异步调用闭包异步/等待,以及如何通过添加日志来调试类似的东西

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM