【问题标题】:Firebase cloud function doesn't send push notification with asyncFirebase 云功能不发送异步推送通知
【发布时间】:2021-03-08 02:36:01
【问题描述】:

我的目标是在用户发送消息时发送推送通知。我试图通过从 firestore 数据库中检索所有推送令牌,并在每次将新消息添加到实时数据库时使用这些令牌发送多播消息来做到这一点。

作品

第一个示例有效。没有令牌检索,令牌是硬编码的。我确实收到了通知。

exports.notifyUsers = functions.database.ref('/messages/{messageId}').onCreate((liveSnapshot, context) => {
    const name = context.params.messageId;
    const message = liveSnapshot.val().toString();
    const tokens = [
         "e6erA_qM...",
         "ePU9p_CI...",
    ];
    const payload = {
        notification: {
            title: `New message from ${name}`,
            body: message,
            badge: '1',
            sound: 'default'
        },
        tokens: tokens,
    }
    const res = admin.messaging().sendMulticast(payload);   
    console.log(`response: ${res}`);

不起作用

这不起作用,我没有收到任何通知。

exports.notifyUsers = functions.database.ref('/messages/{messageId}').onCreate(async (liveSnapshot, context) => {
    const name = context.params.messageId;
    const message = liveSnapshot.val().toString();
    const snapshot = await admin.firestore().collection('users').get();
    const tokens = snapshot.docs.map(doc => doc.data().token);
    const payload = {
        notification: {
            title: `New message from ${name}`,
            body: message,
            badge: '1',
            sound: 'default'
        },
        tokens: tokens,
    }
    const res = await admin.messaging().sendMulticast(payload);     
    console.log(`response: ${res}`);

我已验证从数据库中检索到的令牌与使用以下代码硬编码的令牌相同。

exports.notifyUsers = functions.database.ref('/messages/{messageId}').onCreate(async (liveSnapshot, context) => {
    const hardcodedTokens = [
         "e6erA_qM...",
         "ePU9p_CI...",
    ];
    const snapshot = await admin.firestore().collection('users').get();
    const tokens = snapshot.docs.map(doc => doc.data().token);
    let same = true;
    hardcodedTokens.forEach(el => {
        if (!tokens.includes(el)) {
           same = false;
        }
    });
    console.log(same);
})

这会将 true 记录在 firebase 云函数控制台中。


该函数使用节点 12。

【问题讨论】:

    标签: node.js firebase flutter asynchronous google-cloud-functions


    【解决方案1】:

    我最近遇到了类似的问题,按照Firebase docs拆分Android和iOS的具体字段解决了:

       const message = {
      "notification": {
        "title": `New message from ${name}`,
        "body": message,
      },
      'apns': {
        'payload': {
          'aps': {
            'badge': 1,
          },
        },
      },
      'android':{
        'notification':{
          'notificationCount': 1,
        },
      },
      "tokens": tokens,
    }
    

    【讨论】:

    【解决方案2】:

    以下代码有效。

    async function getTokens() {
        const snapshot = await admin.firestore().collection('users').get();
        return snapshot.docs.map(doc => doc.data().token);
    }
    
    exports.notifyUsers = functions.database.ref('/messages/{messageId}').onCreate(async (snapshot, context) => {
        const name = context.params.messageId;
        const message = snapshot.val().toString();
        const tokens = await getTokens();
        const payload = {
            notification: {
                title: `New message from ${name}`,
                body: message,
            },
            tokens: tokens,
        };
        await admin.messaging().sendMulticast(payload);
    })
    

    我记录了我的回复如下:

    const res = await admin.messaging().sendMulticast(payload);
    console.log('response:', JSON.stringify(res));
    

    这记录了以下内容:
    response: {"responses":[{"success":false,"error":{"code":"messaging/invalid-argument","message":"Invalid JSON payload received. Unknown name \"sound\" at 'message.notification': Cannot find field."}},{"success":false,"error":{"code":"messaging/invalid-argument","message":"Invalid JSON payload received. Unknown name \"sound\" at 'message.notification': Cannot find field."}}],"successCount":0,"failureCount":2}

    基于此,我认为问题出在负载的通知部分中的sound 参数。删除后即可使用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-01
      • 2019-02-23
      • 2019-12-18
      • 2020-09-09
      • 2020-09-13
      • 2021-04-04
      • 2020-10-06
      • 1970-01-01
      相关资源
      最近更新 更多