【问题标题】:Cloud function for sending notification not working用于发送通知的云功能不起作用
【发布时间】:2017-09-16 11:32:42
【问题描述】:

我正在尝试在添加新游戏时向“PLAYER 2”发送通知。 这是我的代码:

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


exports.sendNewGameNotification= functions.database.ref('/GAMES/{gameId}/PLAYER 2').onWrite(event => {
const player2uid = event.params.val;

const getDeviceTokensPromise = admin.database().ref(`/USERS/${player2uid}/fcm`).once('value');

return Promise.all([getDeviceTokensPromise]).then(results => {

const tokensSnapshot = results[0];
// Notification details.
const payload = {
  'data': { 
        'title': "Tienes una nueva partida"
  }
};

// Listing all tokens, error here below.
const tokens = Object.keys(tokensSnapshot.val());

// Send notifications to all tokens.
return admin.messaging().sendToDevice(tokens, payload).then(response => {
  // For each message check if there was an error.
  const tokensToRemove = [];
  response.results.forEach((result, index) => {
    const error = result.error;
    if (error) {
      console.error('Failure sending notification to', tokens[index], error);
      // Cleanup the tokens who are not registered anymore.
      if (error.code === 'messaging/invalid-registration-token' ||
          error.code === 'messaging/registration-token-not-registered') {
        tokensToRemove.push(tokensSnapshot.ref.child(tokens[index]).remove());
      }
    }
  });
  return Promise.all(tokensToRemove);
});
});
});

当它执行时,在firebase控制台中说

 TypeError: Cannot convert undefined or null to object

如果它是 null 但 fcm 在那里,我做错了什么?

【问题讨论】:

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


    【解决方案1】:

    我认为不是这个:

    const player2uid = event.params.val;
    

    你想要这个:

    const player2uid = event.data.val();
    

    编辑:

    对您的代码的此更新包含一些添加的检查和简化。这对我有用。

    用于存储令牌(或多个令牌)的数据库结构至关重要。令牌是键,而不是值。这些值不重要,可以是简单的占位符,例如布尔值。

    例如:

      "USERS" : {
        "Roberto" : {
          "fcm" : {
            "eBUDkvnsvtA:APA...rKe4T8n" : true
          }
        },
        "Juan" : {
          "fcm" : {
            "fTY4wvnsvtA:APA91bGZMtLY6R...09yTLHdP-OqaxMA" : true
          }
        }
      }
    

    .

    exports.sendNewGameNotification= functions.database.ref('/GAMES/{gameId}/PLAYER 2').onWrite(event => {
    const player2uid = event.data.val();
    
    return admin.database().ref(`/USERS/${player2uid}`).once('value').then(snapshot => {
       if (!snapshot.exists()) {
            console.log('Player not found:', player2uid);
            return;
        }
        const tokensSnapshot = snapshot.child('fcm');
        if (!tokensSnapshot.exists()) {
            console.log('No tokens for player: ', player2uid);
            return;
        }
    
        // Notification details.
        const payload = {
          'data': {
                'title': "Tienes una nueva partida"
          }
        };
    
        // Listing all tokens, error here below.
        const tokens = Object.keys(tokensSnapshot.val());
    
        // Send notifications to all tokens.
        return admin.messaging().sendToDevice(tokens, payload).then(response => {
          // For each message check if there was an error.
          const tokensToRemove = [];
          response.results.forEach((result, index) => {
            const error = result.error;
            if (error) {
              console.error('Failure sending notification to', tokens[index], error);
              // Cleanup the tokens who are not registered anymore.
              if (error.code === 'messaging/invalid-registration-token' ||
                  error.code === 'messaging/registration-token-not-registered') {
                  tokensToRemove.push(tokensSnapshot.ref.child(tokens[index]).remove());
              }
            }
          });
          return Promise.all(tokensToRemove);
    });
    });
    });
    

    【讨论】:

    • 谢谢伙计,这已经解决了,但现在它抛出了错误:提供的注册令牌无效。确保它与客户端应用从 FCM 注册时收到的注册令牌相匹配,知道为什么吗?
    • 您是在/USERS/${player2uid}/fcm 下存储一个令牌还是多个?
    • 我只存储一个
    • 你是怎么解决的?
    • 天哪,感谢您指出令牌必须作为密钥放入数据库!你节省了我用头撞墙的时间。
    猜你喜欢
    • 2020-09-13
    • 2019-02-04
    • 2019-02-23
    • 2021-04-19
    • 2021-10-20
    • 2021-03-08
    • 2018-06-01
    • 2021-04-04
    • 2018-08-05
    相关资源
    最近更新 更多