I know this question has been asked recently but i am not able to figure it out. I went through this post Firebase messaging/mismatched-credential but none of the answer works for me I even went through the docs https://firebase.google.com/docs/cloud-messaging/send-message#admin_sdk_error_reference but it does not makes any sense to me
Following is my cloud function
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp(functions.config().firebase);
function cleanupTokens(response, tokens) {
// For each notification we check if there was an error.
const tokensDelete = [];
response.results.forEach((result, index) => {
const error = result.error;
if (error) {
console.error("Failure sending notification to", tokens[index], error);
if (
error.code === "messaging/invalid-registration-token" ||
error.code === "messaging/registration-token-not-registered"
) {
}
}
});
return Promise.all(tokensDelete);
}
exports.sendNotifications = functions.firestore
.document("medical_history/{patientId}")
.onCreate(async snapshot => {
const text = "Hi there";
const payload = {
notification: {
title: "Hi",
body: "Dummy Text"
}
};
const allTokens = await admin
.firestore()
.collection("tokens")
.get();
const tokens = [];
allTokens.forEach(tokenDoc => {
console.log(`tokenIdis ${tokenDoc.id}`);
tokens.push(tokenDoc.id);
});
if (tokens.length > 0) {
const response = await admin.messaging().sendToDevice(tokens, payload);
await cleanupTokens(response, tokens);
console.log("Notification Send");
}
});
but i still get the credentials mismatch error when i add some data to medical_history
collection saying:
Error: The credential used to authenticate this SDK does not have permission to send messages to the device corresponding to the provided registration token. Make sure the credential and registration token both belong to the same Firebase project.
I have enabled FCM on my Google Cloud Platform. I have only one app added to my Firebase project.
I also tried something like below. I went to the Service Accounts
. Click on the New Generate Private Key. Then i moved the downloaded file to the functions folder of my cloud functions.
const serviceAccount = require("./pathtodownloadedfile.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://deleteme-8fee1.firebaseio.com"
});
Also what is the use of ServerKey
from Firebase. Do I need to use it in my cloud functions?
If i try sending notifications manually from Firebase, then i am able to receive the notifications. So i don't think there is an error from the client side setup.