【问题标题】:Android : Cloud function for ChatAndroid : 聊天云功能
【发布时间】:2026-01-08 23:10:01
【问题描述】:

我在创建聊天功能的云功能时遇到了困难。我的 firebase 设计如下所示:

我创建了cloud function,但它不起作用,receiverUid 也没有推送通知。

这是我的云功能:

// // Start writing Firebase Functions
// // https://firebase.google.com/functions/write-firebase-functions
//
// export const helloWorld = functions.https.onRequest((request, response) => {
//  response.send("Hello from Firebase!");
// });
let functions    = require('firebase-functions');
let admin        = require('firebase-admin');

admin.initializeApp(functions.database.ref('/chat_rooms/{pushId}')
    .onWrite(event=>{
        const message = event.data.current.val();
        const senderUid = message.from;
        const receiverUid = message.to;
        const promises = [];

        if(senderUid==receiverUid){
            //if sender is receiver, don't send push notif
            promises.push(event.data.current.ref.remove());
            return Promise.all(promises);
        }

        //dokters == doctors as the receiver
        // sender is current firebase user
        const getInstanceIdPromise = admin.database().ref(`/dokters/${receiverUid}/instanceId`).once('value');
        const getSenderUidPromise = admin.auth().getUser(senderUid);

            return Promise.all([getInstanceIdPromise, getSenderUidPromise]).then(result=>{
                const instanceId = result[0].val();
                const sender = result[1];
                console.log('notifying ' + receiverUid + ' about ' + message.body + ' from ' + senderUid);

                const payload = {
                    notification:{
                        title: sender.displayName,
                        body: message.body,
                        icon: sender.photoURL
                    }
                };

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

我的问题是如何从上述设计中创建正确的云函数。

【问题讨论】:

  • 这实际上是在部署时创建云功能吗?签名错误。

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


【解决方案1】:

您已在 initializeApp() 函数中声明了您的云函数。此函数用于初始化 Firebase SDK,您应该将项目的凭据传递给它:

admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
    databaseURL: 'https://<DATABASE_NAME>.firebaseio.com'
});

有关详细信息,请参阅Admin SDK Documentation

然后你声明你的云函数:

exports.sendNotification = functions.database.ref('/chat_rooms/{pushId}')
    .onWrite(event=>{
        const message = event.data.current.val();
        const senderUid = message.from;
        const receiverUid = message.to;
        const promises = [];

        if(senderUid==receiverUid){
            //if sender is receiver, don't send push notif
            promises.push(event.data.current.ref.remove());
            return Promise.all(promises);
        }

        //dokters == doctors as the receiver
        // sender is current firebase user
        const getInstanceIdPromise = admin.database().ref(`/dokters/${receiverUid}/instanceId`).once('value');
        const getSenderUidPromise = admin.auth().getUser(senderUid);

            return Promise.all([getInstanceIdPromise, getSenderUidPromise]).then(result=>{
                const instanceId = result[0].val();
                const sender = result[1];
                console.log('notifying ' + receiverUid + ' about ' + message.body + ' from ' + senderUid);

                const payload = {
                    notification:{
                        title: sender.displayName,
                        body: message.body,
                        icon: sender.photoURL
                    }
                };

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

【讨论】:

  • 知道如何设置数据负载而不是通知的优先级吗?
  • 我不明白。你的意思是? @BasselMourjan
  • 我想发送 >>>payload = { data: { signal: 1}, priority: 'high'}>>payload = { android: { data: { signal: 1}, priority: 'high'}}
  • 我想通了..我使用的是旧版 FCM 的问题,它有不同的文档.. 干杯