使用 Cloud Functions for Firebase 发送推送通知

Posted

技术标签:

【中文标题】使用 Cloud Functions for Firebase 发送推送通知【英文标题】:Send push notifications using Cloud Functions for Firebase 【发布时间】:2017-11-16 18:39:15 【问题描述】:

我正在尝试制作一个向给定用户发送推送通知的云功能。

用户进行了一些更改,并在 firebase 数据库中的一个节点下添加/更新了数据(该节点代表一个用户 ID)。在这里,我想触发一个向用户发送推送通知的功能。

我对 DB 中的用户有以下结构。

Users

 - UID
 - - email
 - - token

 - UID
 - - email
 - - token

到目前为止,我有这个功能:

exports.sendNewTripNotification = functions.database.ref('/uid/shared_trips/').onWrite(event=>
const uuid = event.params.uid;

console.log('User to send notification', uuid);

var ref = admin.database().ref('Users/uuid');
ref.on("value", function(snapshot)
        console.log("Val = " + snapshot.val());
        ,
    function (errorObject) 
        console.log("The read failed: " + errorObject.code);
);

当我收到回调时,snapshot.val() 返回 null。知道如何解决这个问题吗?也许之后如何发送推送通知?

【问题讨论】:

uuid的console.log是否显示正确的值? 是的,uuid 是正确的。 使用反引号替换您的参考文献中uuid 的值:admin.database().ref(`Users/$uuid`)。你也应该使用once() 而不是on()on() 让听者依附;不是您想要的云功能。 此外,您的函数应返回一个承诺,向 Cloud Functions 指示您的工作何时完成并且可以安全清理。如果你在没有返回承诺的情况下进行异步工作,它就不会按照你想要的方式工作。浏览这些视频教程以了解更多信息可能是个好主意:youtube.com/playlist?list=PLl-K7zZEsYLkPZHe41m4jfAxUi0JjLgSM Doug 是正确的 - 使用 Cloud Functions,您应该返回一个承诺,以便它可以观察链执行,然后在完成时停止实例。因为它无法知道在这种情况下正在发生异步工作,所以函数在异步工作实际完成之前就已经完成。 【参考方案1】:

在云功能中发送主题通知

主题基本上是您可以为所选组发送通知的组

    var topic = 'NOTIFICATION_TOPIC';
    const payload = 
        notification: 
            title: 'Send through Topic',
            body: 'Tap here to check it out!'
        
   ;

   admin.messaging().sendToTopic(topic,payload);

您可以从移动端为任何新的或现有的主题注册设备

【讨论】:

【参考方案2】:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);


exports.sendNotificationToTopic = 
functions.firestore.document('Users/uuid').onWrite(async (event) => 

//let title = event.after.get('item_name');
//let content = event.after.get('cust_name');
var message = 
    notification: 
        title: "TGC - New Order Recieved",
        body: "A New Order Recieved on TGC App",
    ,
    topic: 'orders_comming',
;

let response = await admin.messaging().send(message);
console.log(response);
);

对于向主题发送通知,上面的代码对我来说很有效,如果您有任何疑问,请告诉我。

【讨论】:

【参考方案3】:

我设法完成了这项工作。这是使用适用于我的 Cloud Functions 发送通知的代码。

exports.sendNewTripNotification = functions.database.ref('/uid/shared_trips/').onWrite(event=>
    const uuid = event.params.uid;

    console.log('User to send notification', uuid);

    var ref = admin.database().ref(`Users/$uuid/token`);
    return ref.once("value", function(snapshot)
         const payload = 
              notification: 
                  title: 'You have been invited to a trip.',
                  body: 'Tap here to check it out!'
              
         ;

         admin.messaging().sendToDevice(snapshot.val(), payload)

    , function (errorObject) 
        console.log("The read failed: " + errorObject.code);
    );
)

【讨论】:

有没有办法使用firebase云功能向主题发送消息? 此代码会向所有用户发送通知吗?如果我只想向一个用户发送通知,例如 whatsapp 消息通知,该怎么办。 @DeepakGautam 这只会发送到一个特定的设备。注意 sendToDevice 是一种旧方法。见firebase.google.com/docs/cloud-messaging/admin/send-messages 我正在使用上面的云功能发送通知,但我不知道如何接收ios。有人可以告诉我如何接收上述通知并向用户显示其内容吗?【参考方案4】:

刚刚回答 Jerin A Mathews 的问题... 使用主题发送消息:

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

admin.initializeApp(functions.config().firebase);

//Now we're going to create a function that listens to when a 'Notifications' node changes and send a notificcation
//to all devices subscribed to a topic

exports.sendNotification = functions.database.ref("Notifications/uid")
.onWrite(event => 
    //This will be the notification model that we push to firebase
    var request = event.data.val();

    var payload = 
        data:
          username: request.username,
          imageUrl: request.imageUrl,
          email: request.email,
          uid: request.uid,
          text: request.text
        
    ;

    //The topic variable can be anything from a username, to a uid
    //I find this approach much better than using the refresh token
    //as you can subscribe to someone's phone number, username, or some other unique identifier
    //to communicate between

    //Now let's move onto the code, but before that, let's push this to firebase

    admin.messaging().sendToTopic(request.topic, payload)
    .then((response) => 
        console.log("Successfully sent message: ", response);
        return true;
    )
    .catch((error) => 
        console.log("Error sending message: ", error);
        return false;
    )
)
//And this is it for building notifications to multiple devices from or to one.

【讨论】:

您好,如果我有一个特定的主题要发送到哪里?比如说,像一些人订阅了 GoodMorning 主题和另一个组 NoonTopic。请协助。 @Gsilveira 你能检查一下吗,***.com/questions/56656303/…【参考方案5】:

返回这个函数调用。

return ref.on("value", function(snapshot)
        console.log("Val = " + snapshot.val());
        ,
    function (errorObject) 
        console.log("The read failed: " + errorObject.code);
);

这将使云功能保持活动状态,直到请求完成。通过 Doug 在评论中提供的链接了解有关返回承诺的更多信息。

【讨论】:

谢谢大家的回答。将它们结合起来帮助我实现了我想要的! 很高兴,如果对您的问题有帮助,请接受答案。 @TudorLozba

以上是关于使用 Cloud Functions for Firebase 发送推送通知的主要内容,如果未能解决你的问题,请参考以下文章

使用 Cloud Functions for Firebase 和 @google-cloud/storage 删除图像时出现问题

使用 Cloud Functions for Firebase 发送推送通知

使用 Cloud Functions for Firebase 时出现 CORS 错误

Cloud Functions for Firebase 组织

如何使用 Firestore 在 Cloud Functions for Firebase 中获取服务器时间戳?

Cloud Functions for Firebase 在生产中的 mongodb 错误