如何从Firebase功能中使用FCM

时间:2020-10-11 01:08:41

标签: firebase firebase-cloud-messaging

我正在尝试从Firebase函数中发送FCM,但每次都会收到以下错误:

await admin.messaging().sendToDevice(registrationToken, message)

我遵循了this post, of the same topic的建议,没有帮助。指向文章中的另一个链接Add the Firebase Admin SDK to your server,因为我使用的是Firebase Server,它并没有太大帮助。

本文与Sending FCM using Firebase Functions相同,我使用的是相同的代码(FCM代码),并且存在相同的错误。

这是完整的错误:

Error sending message: { 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. Raw server response: "<HTML>
<HEAD>
<TITLE>Unauthorized</TITLE>
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000">
<H1>Unauthorized</H1>
<H2>Error 401</H2>
</BODY>
</HTML>
". Status code: 401.
    at FirebaseMessagingError.FirebaseError [as constructor] (/workspace/node_modules/firebase-admin/lib/utils/error.js:43:28)
    at FirebaseMessagingError.PrefixedFirebaseError [as constructor] (/workspace/node_modules/firebase-admin/lib/utils/error.js:89:28)
    at new FirebaseMessagingError (/workspace/node_modules/firebase-admin/lib/utils/error.js:255:16)
    at Object.createFirebaseError (/workspace/node_modules/firebase-admin/lib/messaging/messaging-errors-internal.js:57:12)
    at /workspace/node_modules/firebase-admin/lib/messaging/messaging-api-request-internal.js:78:51
    at process._tickCallback (internal/process/next_tick.js:68:7)
  errorInfo:
   { code: 'messaging/authentication-error',
     message:
      '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. Raw server response: "<HTML>\n<HEAD>\n<TITLE>Unauthorized</TITLE>\n</HEAD>\n<BODY BGCOLOR="#FFFFFF" TEXT="#000000">\n<H1>Unauthorized</H1>\n<H2>Error 401</H2>\n</BODY>\n</HTML>\n". Status code: 401.' },
  codePrefix: 'messaging' } 

2 个答案:

答案 0 :(得分:0)

好的,无关但相关,我找到了答案...

gcp-the-caller-does-not-have-a-permission

基本上,按照these的说明进行添加

Firebase管理员

到您的.gserviceaccount.com帐户。

答案 1 :(得分:0)

我是如何解决的:

  1. 转到 Google Service Account 并选择您的项目。
  2. 它将显示帐户列表。点击帐户something@appspot.gserviceaccount.com
  3. 选择标签“键”。生成新密钥并将其下载为 JSON。
  4. 最后,使用函数 .cert() 将生成的 JSON 添加到您的项目中:

这仅用于测试,请记住在部署函数时删除凭据!

admin.initializeApp({
  credential: admin.credential.cert(
    "route/to/generatedJSON.json"
  ),
});
const messaging = admin.messaging();