Firebase Cloud Functions 上“尝试向 FCM 服务器进行身份验证时发生错误”

wuj*_*jek 6 firebase typescript google-cloud-functions firebase-cloud-messaging firebase-admin

我正在尝试通过创建 Firestore 文档(消息)时触发的 Firebase 云函数中的 FCM 向主题发送消息。订阅主题(也使用函数完成)并触发发送函数工作正常,但实际发送失败,并显示:

Error: An error occurred when trying to authenticate to the FCM servers. Make sure the credential used to authenticate this SDK has the proper permissions. See https://firebase.google.com/docs/admin/setup for setup instructions.
Run Code Online (Sandbox Code Playgroud)

以及一些包含<H1>PROJECT_NOT_PERMITTED</H1>和的原始 HTML <H1>PROJECT_NOT_PERMITTED</H1>

这是我的代码(index.ts):

Error: An error occurred when trying to authenticate to the FCM servers. Make sure the credential used to authenticate this SDK has the proper permissions. See https://firebase.google.com/docs/admin/setup for setup instructions.
Run Code Online (Sandbox Code Playgroud)

和(messages.ts):

import * as admin from 'firebase-admin';

admin.initializeApp({
    credential: admin.credential.applicationDefault(),
});

export * from './messages';
Run Code Online (Sandbox Code Playgroud)

根据https://firebase.google.com/docs/cloud-messaging/auth-server#provide-credentials-using-adc这应该有效。我也尝试过在没有任何参数的情况下执行此操作(https://firebase.google.com/docs/admin/setup#initialize-without-parameters),但它仍然失败。我缺少什么?

wuj*_*jek 5

事实证明,而不是这个

      const message = {
        notification: {
          title: `${data.sentBy} sent a message`,
          body: data.message,
        },
      };

      return admin.messaging().sendToTopic('messages', message);
Run Code Online (Sandbox Code Playgroud)

我需要这个:

      const message = {
        notification: {
          title: `${data.sentBy} sent a message`,
          body: data.message,
        },
        topic: 'messages',
      };

      return admin.messaging().send('messages', message);
Run Code Online (Sandbox Code Playgroud)