Notification with Firebase Cloud Functions for single device

Asked

Viewed 190 times

1

I have a problem sending notifications using Firebase Cloud Functions, in case I would like the user to send notifications from the site, hosted by Firebase Hosting, to an android device. Since to do this I thought of making the user who wanted to send the notification type the email of the recipient, this email would be inserted in the database, and when entering such information a function would be triggered by Firebase Cloud Functions. Such function would have to redeem this entered value and after that compare the value with the email of all users registered in the database for the target user to be found and their respective token to be recovered, to this way send the notification to the mobile of this user. However, I have not succeeded in doing this job successfully, I hope you can help me in some way and I thank you in advance!

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.