I have a problem sending notifications using the Firebase Cloud Functions, in case I would like the user to send notifications from the site, hosted by Firebase Hosting, to an android device. To do this I thought about having the user who wanted to send the notification to type the recipient's email, that email would be inserted in the database, and when entering such information a function would be triggered by the Firebase Cloud Functions. Such a function would have to redeem this inserted value and then compare the value with the email of all the users registered in the database for the destination user to be found and their respective token retrieved, in order to send the notification to the mobile phone this user. However, I was not successful in performing this function successfully, I hope you can help me in some way and thank you right away!
Here is my code:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotification = functions.database.ref("Mensagens/Destinatarios/{userId}")
.onWrite(event => {
var email = event.data.val();
var tokenUser = firebase.database().ref('Usuarios/{userId}/').orderByChild('email').equalTo(email).on('value', function() {
var token = snapshot.val().token;
return token;
});
var payload = {
data:{
title: "Nova Encomenda na Portaria",
body: "Você tem um nova encomenda venha buscá-la assim que possível"
}
};
admin.messaging().sendtoDevice(tokenUser, payload)
.then(function(response){
console.log("Mensagem enviada com sucesso: ", response);
})
.catch(function(error){
console.log("Erro ao enviar a mensagem: ", error);
})
})