首页 > 解决方案 > 错误凭证和注册令牌都属于同一个 Firebase 项目

问题描述

我知道最近有人问过这个问题,但我无法弄清楚。我浏览了这篇文章Firebase 消息传递/不匹配的凭据,但没有一个答案对我有用,我什至浏览了文档https://firebase.google.com/docs/cloud-messaging/send-message#admin_sdk_error_reference但它没有对我有意义

以下是我的云功能

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");
    }
  });

但是当我将一些数据添加到medical_history集合中时,我仍然会收到凭据不匹配错误:

错误:用于验证此 SDK 的凭据无权向提供的注册令牌对应的设备发送消息。确保凭据和注册令牌都属于同一个 Firebase 项目。

我在我的 Google Cloud Platform 上启用了 FCM。我的 Firebase 项目中只添加了一个应用。

我也尝试了类似下面的东西。我去了Service Accounts. 点击New Generate Private Key。然后我将下载的文件移动到我的云函数的函数文件夹中。

const serviceAccount = require("./pathtodownloadedfile.json");

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: "https://deleteme-8fee1.firebaseio.com"
});

Firebase还有什么用ServerKey。我需要在我的云功能中使用它吗?

如果我尝试从 Firebase 手动发送通知,那么我可以接收通知。所以我认为客户端设置没有错误。

标签: javascriptfirebasefirebase-cloud-messaginggoogle-cloud-functions

解决方案


推荐阅读