如何使用Firebase云功能实现推送通知

时间:2019-05-01 11:33:05

标签: javascript firebase firebase-realtime-database firebase-cloud-messaging google-cloud-functions

我正在尝试使用Firebase云功能在聊天中实现推送通知。

我的数据库看起来像这样:

  • 消息
    • messageId
      • fromId:“”
      • toId:“”
      • messageText:“”
  • 用户
    • userId
      • 用户名:“坦率”
      • fcmToken:“ odnue38dh93hjd903jdn3obd3jfb393f”

我的功能代码:

const functions = require('firebase-functions');

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


exports.observeChat = functions.database.ref('/messages/{messageId}').onCreate((snaphot, context) => {

  var messageId = context.params.messageId;

  return admin.database().ref('/messages/' + messageId).once('value', snapshot => {
    var newMessage = snapshot.val();
    var toUid = newMessage.toId;

    console.log('LOGGER -> toid  ' + toUid);

      return admin.database().ref('/users/' + toUid).once('value', snaphsot => {
        var userTextedTo = snapshot.val();

        console.log('LOGGER -> fcmtoken   ' + userTextedTo.fcmToken);
        console.log('LOGGER -> name ' + userTextedTo.username);

        var payload = {
            notification: {
              title: 'New Message',
              body: userTextedTo.username + 'did message you'
            }
        };

        admin.messaging().sendToDevice(userTextedTo.fcmToken, payload)
          .then(function(response) {
            console.log('Successfully sent message:', response);
          })
          .catch(function(error) {
            console.log('Error sending message:', error);
          });
    })
  })
})

Firebase功能日志


Function execution started


LOGGER -> toid YyUZ3ESFA2UHTlTFurqEvpRaspu2


Function execution took 708 ms, finished with status: 'ok'


LOGGER -> fcmtoken undefined


LOGGER -> name undefined 

@firebase/database: FIREBASE WARNING: Exception was thrown by user callback. Error: Registration token(s) provided to sendToDevice() must be a non-empty string or a non-empty array.

Uncaught exception 

Error: Registration token(s) provided to sendToDevice() must be a non-empty string or a non-empty array.

所以我想我的代码有问题。任何帮助表示赞赏。

编辑:日志:LOGGER -> Usertexted [object Object] with code console.log('LOGGER -> Usertexted ' + userTextedTo);

0 个答案:

没有答案
相关问题