【发布时间】:2019-11-05 13:48:39
【问题描述】:
我用 Javascript 编写了一个云函数,如果数据库发生更改,它应该会发送通知。
我已经在代码中记录了值,我什至在 admin.messaging().sendToDevice(token, payload) 中得到了响应。从我的 Firebase 控制台中的日志来看,一切看起来都很好,但我的设备上没有收到任何通知。此外,邮递员设置正确,因为当我按下邮递员上的发送按钮时,我确实收到了通知。
这是我在 Postman 中的 json 正文
{
"to" : "dCDqZxTYq3s:APA91bFlbFd3hGUJuvjknPhivRLew69kM4KDrNJAOkIMT5WgsoHr_Uc_41xqeOtQJvMhvXO1S56v4aT_6Zd24rlGoD-AV7pyNFMw8AxdkmwZCS3HYDidO2-xX_Da8IGcuQTN3FrnIYKo",
"data" : {
"message" : "This is my data message",
"title" : "This is my data title",
"data_type": "direct_message"
},
"notification" : {
"title": "This is a title",
"text": "this is a notification"
}
}
这是我写云函数的index.js
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotification = functions.database.ref('/problemDetails/{problemId}').onUpdate((change, context) => {
const problemId = context.params.problemId;
console.log("problemId: ", problemId);
//get the userId of the person receiving the notification because we need to get their token
const senderId = change.after.child('userId').val();
//get the status
const status = change.after.child('status').val();
// //get the user id of the person who sent the message
// const senderId = event.data.child('user_id').val(); //THis should be mechID
// console.log("senderId: ", senderId);
if(status === 'Price set by mechanic'){
//get the message
const message = "The mechanics has set the price for your service. Please check your current order if you have to take any actions.";
console.log("message: ", message);
//get the message id. We'll be sending this in the payload
const messageId = "messageId";
console.log("messageId: ", messageId);
//query the users node and get the name of the user who sent the message
return admin.database().ref("/users/" + senderId).once('value').then(snap => {
const senderName = snap.child("displayName").val();
console.log("senderName: ", senderName);
//get the token of the user receiving the message
return admin.database().ref("/users/" + senderId).once('value').then(snap => { //change senderId here to mechId who will be the receiver
const token = snap.child("messagingToken").val();
console.log("token: ", token);
//we have everything we need
//Build the message payload and send the message
console.log("Construction the notification message.");
const payload = {
data: {
data_type: "direct_message",
title: "New Message from " + senderName,
message: message,
message_id: messageId,
}
};
return admin.messaging().sendToDevice(token, payload)
.then(function(response) {
console.log("Successfully sent message:", response);
})
.catch(function(error) {
console.log("Error sending message:", error);
});
});
});
}
else{
return null;
}
});
【问题讨论】:
标签: android firebase push-notification google-cloud-functions postman