【问题标题】:Is there a way to send notifications by identifying user rather than device?有没有办法通过识别用户而不是设备来发送通知?
【发布时间】:2020-12-18 20:46:35
【问题描述】:

在我的 android 应用程序中,我想为从一个用户发送给另一个用户的短信发送通知,并且我已将此 Node.js 函数部署到 firebase 函数中:

'use strict'


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


exports.sendNotification = functions.database.ref(`/notification/{receiver_user_id}/{notification_id}`)
.onWrite((data, context) =>
{
    const receiver_user_id = context.params.receiver_user_id;
    const notification_id = context.params.notification_id;


    console.log('We have a notification to send to :' , receiver_user_id);


    if (!data.after.val()) 
    {
        console.log('A notification has been deleted :' , notification_id);
        return null;
    }

    const DeviceToken = admin.database().ref(`/users/${receiver_user_id}/user_id`).once('value');

    return DeviceToken.then(result => 
    {
        const token_id = result.val();
        console.log("Token Id ", token_id);

        const payload = 
        {
            notification:
            {
                title: "New Mesaage",
                body: `you have a new Message, Please Check.`,
                icon: "default"
            }
        };

        console.log("This is payload ", payload);

        return admin.messaging().sendToDevice(token_id, payload).then()
            .catch(function (error) 
                {
                    console.log("Error sending message: ", error);  // here no return
                });

    });
});

我认为问题在于 sendToDevice() 方法,因为我没有收到任何通知并且我不想通过 device_token 发送。

我想向具有特定“user_id”的用户登录的设备发送通知 This is my database model

This is the log I got:

【问题讨论】:

  • Firebase 云消息传递只知道设备/应用实例。它不了解用户。如果您想将用户与设备/应用实例相关联,您必须在自己的代码中执行此操作。
  • 那么如果同一个用户在多个设备上登录会发生什么?
  • 你可以试试ravenapp.dev。您可以在仪表板中设置 FCM 密钥,并调用其 api 来发送通知。它将为您管理您的设备令牌。

标签: android node.js firebase google-cloud-functions firebase-cloud-messaging


【解决方案1】:

我不想通过 device_token 发送

如果您想将消息定位到特定用户的设备,您必须使用设备令牌。就是这样works

FCM 对您应用的各个用户一无所知。 FCM 只知道您在应用程序中收集其令牌并将其发送到您的后端(或存储在您的数据库中)的各个设备。您必须以某种方式将令牌与用户帐户相关联。您还应该假设一位用户可能正在使用多台设备。

您可能首先应该做的是启动collecting the device tokens 并将它们存储在您的用户数据下的字段中。然后,当您查询该用户时,您可以找到用于发送消息的设备令牌。

【讨论】:

  • 是否可以通过主题消息传递??
  • 您可以尝试为每个用户分配一个主题,但这并不安全,因为任何人都可以接收来自任何主题的消息。你真的应该收集设备令牌并直接发送到设备。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多