首页 > 解决方案 > Firebase 云消息传递的本地 Firebase 云功能问题

问题描述

当我在本地启动函数时(firebase serve --only 函数),它可以读取和写入 Firestore 数据,但是在发送推送通知时失败并出现以下错误。它从昨天开始工作。今天我将我的 MacOS 更新到 Big Sur,然后它停止工作。

未经授权的错误 401 尝试对 FCM 服务器进行身份验证时发生错误。确保用于验证此 SDK 的凭据具有适当的权限。有关设置说明,请参阅 https://firebase.google.com/docs/admin/setup

以下是尝试发送通知的函数

exports.test = functions.https.onRequest(async (req, response) => {
    var data = {};
    const token = await util.getTokenByEmail('demouser@gmail.com');
    let payload = {}, notiData = {}, notification = {}
    notification.title = notiData.title = `Test msg`;
    notification.body = `Test msg`;
    notiData.message = `Test msg`;
    payload.notification = notification;
    payload.data = notiData;
   try {
     await admin.messaging().sendToDevice(token, payload);
   } catch (e) {
      console.log(`Error: ${e}`); // Unauthorized Error 401
       data.error = e;
   }
   response.status(200).json({ data: data });
});

我按照此处给出的步骤操作并设置了 GOOGLE_APPLICATION_CREDENTIALS。

export GOOGLE_APPLICATION_CREDENTIALS="Volumes/demo/Firebase/key.json"

我正在从 Firebase -> Settings -> Service Accounts 下载 key.json。

在此处输入图像描述

标签: firebasegoogle-cloud-functionsfirebase-cloud-messagingfirebase-cli

解决方案


事实证明,我只为那个终端会话设置了GOOGLE_APPLICATION_CREDENTIALS 。一旦我将路径设置为 $HOME/.zshrc,它就开始工作了。感谢您的时间和帮助。


推荐阅读