firebase function getMessaging is not Define FCM

Viewed 961

I follow this doc to set FCM, but does not work.

error in firebase functions log:

ReferenceError: getMessaging is not defined

https://firebase.google.com/docs/cloud-messaging/send-message#send-messages-to-specific-devices

const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp({ credential: admin.credential.applicationDefault() });

exports.updateUser = functions
  .region("australia-southeast1")
  .firestore.document("messages/{groupId1}/{groupId2}/{message}")
  .onCreate(async (snap, context) => {
    console.log("----------------start function--------------------");

    const doc = snap.data();
    
    const idFrom = doc.idFrom;
    const idTo = doc.idTo;
    const contentMessage = doc.content;
    admin
      .firestore()
      .collection("users")
      .where("id", "==", idTo)
      .get()
      .then((querySnapshot) => {
        querySnapshot.forEach((userTo) => {
                  const message = {
                    message: {
                      xxxxxxx
                    },
                  };
                  admin
                    .getMessaging()  // <-------
                    .send(message)   // <-------
                    .then((response) => {
                      // Response is a message ID string.
                      console.log("Successfully sent message:", response);
                    })
                    .catch((error) => {
                      console.log("Error sending message:", error);
                    });
                });
              });
    return { success: true };
  });

1 Answers

Try so many times.
To use FCM in Firebase function with the new HTTP v1 API use:

const functions = require("firebase-functions");
const admin = require("firebase-admin");
// to get the ADC automatically
admin.initializeApp({ credential: admin.credential.applicationDefault() }); 

....

admin
                    .messaging()
                    .send(message)
                    .then((response) => {
                      // Response is a message ID string.
                      console.log("Successfully sent message:", response);
                    })
                    .catch((error) => {
                      console.log("Error sending message:", error);
                    });

admin.messaging().send(message) is the old method I think, because the online doc has no mention about it.
but it works fine with v1 payload, and the iphone bedge count showes.

Related