Firebase push notifications from function

Hi there.
I’ve seen a few posts about this in the forum, but no answers that helped me.
I’m trying to implement firebase push notifications, but i have no idea of how to store the ‘serviceaccountkey.json’ and read it from the function. I have tried storing it as a value, and getting the value from context, but was unable to make it work.

My code:

exports =  function(deviceToken){
  
  var admin = require("firebase-admin");
  var serviceAccount = context.values.get("firebase_json");
  //var serviceAccount = require("path/to/serviceAccountKey.json");
  
  
  const jsonObject = JSON.parse(serviceAccount);
  console.log('Before stringify');
  console.log(JSON.stringify(json));
  
    admin.initializeApp({
      credential: admin.credential.cert(jsonObject)
    });
  
  

Anyone succesfully managed to use the firebase api to send pushnotifications from a function called from a trigger?

Thanks in advance for any help

EDIT:
What i’m trying to achive is something like this (taken from a sample written in c#)

FirebaseApp.Create(new AppOptions()
            {
                Credential = GoogleCredential.FromFile("private_key.json")
            });

            // This registration token comes from the client FCM SDKs.
            //var registrationToken = "TOKEN_HERE";

            // See documentation on defining a message payload.
            var message = new Message()
            {
                Data = new Dictionary<string, string>()
    {
        { "myData", "1337" },
    },
                //Token = registrationToken,
                Topic = "all",
                Notification = new Notification()
                {
                    Title = "Test from code",
                    Body = "Here is your test!"
                }
            };

            // Send a message to the device corresponding to the provided
            // registration token.
            string response = FirebaseMessaging.DefaultInstance.SendAsync(message).Result;
            // Response is a message ID string.
            Console.WriteLine("Successfully sent message: " + response);

Found here:

Never mind, i figured it out:

exports =  function(deviceToken){
  
  var admin = require('firebase-admin');
  var json = context.values.get("firebase_json");
    console.log(JSON.stringify(json));
  const message = {
    "topic": 'all',
    "notification": {
      "title": "Test Title",
      "body": "Test Message"
    },
    "data": 
    {
      "id":"1234"
    },
    webpush:{
        headers:{
            Urgency:'high'
        }
    },
    android:{
        priority:'high'
    },
  };

  var doc = JSON.parse(JSON.stringify(json)); 
  admin.initializeApp({
      credential: admin.credential.cert(doc)
    });

  admin.messaging().send(message);
};
1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.