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

时间:2017-06-14 14:31:22

标签: android firebase firebase-cloud-messaging google-cloud-functions

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

用户进行一些更改,并在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。不知道怎么解决这个问题?也许以后如何发送推送通知?

5 个答案:

答案 0 :(得分:11)

我成功完成了这项工作。以下是使用适用于我的云功能发送通知的代码。

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

答案 1 :(得分:3)

只需回答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.

答案 2 :(得分:0)

返回此函数调用。

Smalltalk saveSession.
Smalltalk quitPrimitive.

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

答案 3 :(得分:0)

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

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

答案 4 :(得分:0)

发送云中主题的通知

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

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

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

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