如何使用firebase功能向一个用户发送PushNotification(例如Flutter中的聊天应用程序)?

问题描述 投票:0回答:1

我希望它发送给一个用户,但它发送给所有用户 nad 这是我的 index.js 并通过来自 firebase cloud firestore connect(Collection)=>userID(connect(Document))=>userconnect(collection)=> 的查询PetID(Document)=>message(collection)=>messageID(message(Document))=>字段名称中的 uid 是接收者的 uid,在同一查询中,电子邮件字段是发送者用户的电子邮件。

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();

exports.notifyUserOnMessage = functions.firestore.document('connect/{userId}/userconnect/{petId}/message/{messageId}')
    .onCreate(async (snapshot, context) => {
        const messageData = snapshot.data();

        // Extract the userId and petId from the context
        const targetUserId = context.params.userId;
        const petId = context.params.petId;

        // Fetch the userconnect document to get the userid field
        const userConnectDoc = await admin.firestore().doc(`connect/${targetUserId}/userconnect/${petId}`).get();
        const userConnectData = userConnectDoc.data();

        let recipientUserId;

        if (messageData.uid === userConnectData.userid) {
            recipientUserId = targetUserId;
        } else {
            recipientUserId = userConnectData.userid;
        }

        const payload = {
            notification: {
                title: 'You Have New Message',
                body: 'New Message Arrive.',
                clickAction: 'FLUTTER_NOTIFICATION_CLICK',
            },
            data: {
                click_action: 'FLUTTER_NOTIFICATION_CLICK', // for background
            }
        };


        return admin.messaging().sendToTopic(recipientUserId, payload);
    });

我怎样才能将其发送给我指定的用户。

node.js flutter firebase push-notification firebase-cloud-messaging
1个回答
0
投票

您应该在最终用户端为每个用户检索唯一的令牌,比如说在他们登录到您的应用程序后 前任。 Flutter 应用程序使用

FirebaseMessaging.instance.getToken().then((token) {
      appPrint('Token is $token');
    });

然后您应该将此令牌存储在某处(与用户数据一起),并且每当您想为此用户发送通知时,只需将存储的令牌传递到地图有效负载中即可

const payload = {
        token: storedToken, // TOKEN THAT YOU ALREADY STORED IT
        notification: {
            title: 'You Have New Message',
            body: 'New Message Arrive.',
            clickAction: 'FLUTTER_NOTIFICATION_CLICK',
        },
        data: {
            click_action: 'FLUTTER_NOTIFICATION_CLICK', // for background
        }
    };

通过后,Firebase 将为您施展魔法。

如果对你有帮助的话请点个赞吧

© www.soinside.com 2019 - 2024. All rights reserved.