使用Cloud Functions for Firebase发送推送通知 [英] Send push notifications using Cloud Functions for Firebase

查看:99
本文介绍了使用Cloud Functions for Firebase发送推送通知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使云功能向指定用户发送推送通知.

I am trying to make a cloud function that sends a push notification to a given user.

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

The user makes some changes and the data is added/updated under a node in firebase database (The node represents an user id). Here i want to trigger a function that sends a push notification to the user.

对于DB中的用户,我具有以下结构.

I have the following structure for the users in DB.

Users

 - UID
 - - email
 - - token

 - UID
 - - email
 - - token

直到现在我有了这个功能:

Until now i have this function:

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.知道如何解决这个问题吗?也许以后如何发送推送通知?

When i get the callback, the snapshot.val() returns null. Any idea how to solve this? And maybe how to send the push notification afterwards?

推荐答案

我设法完成了这项工作.这是使用对我有用的Cloud Functions发送通知的代码.

I managed to make this work. Here is the code that sends a notification using Cloud Functions that worked for me.

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);
    });
})

这篇关于使用Cloud Functions for Firebase发送推送通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆