【问题标题】:Firebase web push notification with NodeJS not working使用 NodeJS 的 Firebase 网络推送通知不起作用
【发布时间】:2020-10-15 10:01:43
【问题描述】:

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

我首先生成一个 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'
}

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

【问题讨论】:

  • 我发现了问题,我使用的是另一个项目的 Firebase Admin SDK。

标签: node.js firebase push-notification firebase-cloud-messaging web-push


【解决方案1】:

如果您使用 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

【讨论】:

    猜你喜欢
    • 2020-06-11
    • 1970-01-01
    • 1970-01-01
    • 2017-04-29
    • 1970-01-01
    • 1970-01-01
    • 2023-01-31
    • 1970-01-01
    相关资源
    最近更新 更多