首页 > 解决方案 > 使用 NodeJS 的 Firebase 网络推送通知不起作用

问题描述

我正在构建一个使用 firebase 和 NodeJs 服务器发送 Web 推送通知的应用程序,但我收到“不匹配的凭据”错误,我该如何解决这个问题?

我首先生成一个 json 文件,该文件从控制台给了我“生成私钥”按钮,然后从我的服务器代码将管理 SDK 添加到我的应用程序中,这种方式

var admin = require("firebase-admin");

var serviceAccount = require("path/to/serviceAccountKey.json");

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: "https://nodeproject-2bc3o.firebaseio.com"
});

然后我正在构建发送请求

// This registration token comes from the client FCM SDKs.
var registrationToken = 'YOUR_REGISTRATION_TOKEN';

var message = {
  data: {
    score: '850',
    time: '2:45'
  },
  token: registrationToken
};

// Send a message to the device corresponding to the provided
// registration token.
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);
  });

文档说,// This registration token comes from the client FCM SDKs所以我使用从客户端获得的令牌作为我的令牌registrationToken,我通过以下方式从客户端 javascript 代码中检索到该令牌,然后发送到服务器

messaging.getToken().then((currentToken) => {
  if (currentToken) {
    sendTokenToServer(currentToken);
    updateUIForPushEnabled(currentToken);
  }

最后,在使用令牌从服务器发送消息后,我收到以下错误

  errorInfo: {
    code: 'messaging/mismatched-credential',
    message: 'SenderId mismatch'
  },
  codePrefix: 'messaging'
}

检索客户端令牌,将其发送到服务器,然后使用它向客户端发送推送通知的正确方法是什么?或者我做错了什么?

标签: node.jsfirebasepush-notificationfirebase-cloud-messagingweb-push

解决方案


如果您使用 Firebase Cloud Functions 作为后端服务器,那么这serviceAccountKey.json 不是必需的,而且更简单。

请参阅https://firebase.google.com/docs/functions/get-started#import-the-required-modules-and-initialize-an-app

// The Cloud Functions for Firebase SDK to create Cloud Functions and setup triggers.
const functions = require('firebase-functions');

// The Firebase Admin SDK to access Cloud Firestore.
const admin = require('firebase-admin');
admin.initializeApp();

这些行加载 firebase-functions 和 firebase-admin 模块,并初始化一个管理应用实例,可以从中进行 Cloud Firestore 更改。

而且,fcm 示例是https://github.com/firebase/functions-samples/tree/master/fcm-notifications


推荐阅读