【问题标题】:Firebase Firestore FCM message sending issueFirebase Firestore FCM 消息发送问题
【发布时间】:2017-10-24 13:03:47
【问题描述】:

我的代码:

exports.fcmSend = functions.firestore.document('messages/{userId}').onCreate(event => {
    console.log("fcm send method");
    const message = event.data.data();
    const userId = event.params.userId;
    const token_id = 'asdfsadfdsafds';
    let token = "";
    const payload = {
        notification: {
            title: "Test",
            body: "Test",
            icon: "https://placeimg.com/250/250/people"
        }
    };
    db.collection('fcmTokens').doc('token_id').get().then((doc) => {
        console.log(doc.id, '=>', doc.data());
        const data = doc.data();
        token = data.token;
        console.log("token", token);
    })
    .then(() => {
        return event.data.ref.set({"title": "hello"}).sendToDevice(token, payload);
    })
    .catch((err) => {
        console.log('Error getting documents', err);
        return err;
    });
});

错误:

获取文档时出错 TypeError: event.data.ref.set(...).sendToDevice 不是函数
在 db.collection.doc.get.then.then (/user_code/index.js:117:50)
在 process._tickDomainCallback (internal/process/next_tick.js:135:7)

【问题讨论】:

    标签: javascript firebase firebase-cloud-messaging google-cloud-firestore


    【解决方案1】:

    这里涉及两个独立的 Firebase 产品:

    1. Cloud Firestore,您可以在其中为用户敲击 FCM 令牌。
    2. Cloud Messaging Admin SDK,用于send notifications to a user

    sendToDevice 方法存在于 Cloud Messaging 的 Admin SDK 中,而不是您尝试调用它的 Firestore 数据库引用中。

    要解决此问题,您首先需要将 Admin SDK 导入您的 index.js

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

    然后修改第 1 步和第 2 步的函数。它应该如下所示:

    // Load the tokens from Firestore
    db.collection('fcmTokens').doc('token_id').get().then((doc) => {
        console.log(doc.id, '=>', doc.data());
        const data = doc.data();
        token = data.token;
        console.log("token", token);
    
        const payload = {
              notification: {
                title: 'hello',
              }
            };
    
        return admin.messaging().sendToDevice(token, payload)
    })
    .catch((err) => {
        console.log('Error getting documents', err);
        return err;
    });
    

    【讨论】:

    • 感谢您的重播,我得到了问题
    猜你喜欢
    • 2019-01-19
    • 2021-01-19
    • 2022-01-17
    • 1970-01-01
    • 2021-10-21
    • 1970-01-01
    • 2019-06-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多