【发布时间】:2019-06-07 04:42:40
【问题描述】:
我正在尝试在 firebase 云功能中使用 firebase-admin 通过 firebase 云消息传递 (FCM) 发送消息。
阅读documentation 时会显示
要使用 Admin FCM API,您必须首先按照将 Firebase Admin SDK 添加到您的服务器中的步骤操作。
但我认为这不是必需的,因为我只使用云功能?
无论如何,直到admin.messaging().send 出现此错误为止,这一切都有效:
Error sending message: { Error: Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.
at FirebaseMessagingError.Error (native)
at FirebaseMessagingError.FirebaseError [as constructor] (/user_code/node_modules/firebase-admin/lib/utils/error.js:39:28)
at FirebaseMessagingError.PrefixedFirebaseError [as constructor] (/user_code/node_modules/firebase-admin/lib/utils/error.js:85:28)
at new FirebaseMessagingError (/user_code/node_modules/firebase-admin/lib/utils/error.js:241:16)
at Function.FirebaseMessagingError.fromServerError (/user_code/node_modules/firebase-admin/lib/utils/error.js:271:16)
at FirebaseMessagingRequestHandler.handleHttpError (/user_code/node_modules/firebase-admin/lib/messaging/messaging-api-request.js:125:50)
at /user_code/node_modules/firebase-admin/lib/messaging/messaging-api-request.js:113:23
at process._tickDomainCallback (internal/process/next_tick.js:135:7)
errorInfo:
{ code: 'messaging/invalid-apns-credentials',
message: 'Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.' },
codePrefix: 'messaging' }
这是我的云函数源代码
import * as functions from 'firebase-functions'
import * as admin from 'firebase-admin'
admin.initializeApp(functions.config().firebase)
const firestore = admin.firestore()
firestore.settings({timestampsInSnapshots: true})
exports.notification = functions.firestore
.document(path)
.onUpdate(async (change, context) => {
const deviceTokens = ['deviceToken-123123123']
deviceTokens.forEach(token => {
const fcmMessage = {
notification: {title: 'test title', body: 'test body'},
token
}
admin.messaging().send(fcmMessage)
.then((response) => {
// Response is a message ID string.
console.log('Successfully sent message:', response)
})
.catch((error) => {
console.log('Error sending message:', error)
})
})
})
设备令牌存储在 firestore 中,也可以从该云函数内的 firestore 中检索。设备令牌的格式正确。对于这个示例,我已将其替换为占位符。
我也四处寻找类似的问题,但我能找到的唯一一个是this one
【问题讨论】:
-
我认为 FCM 发送的错误信息在这里相当具有误导性。我已将此情况报告给 FCM 团队以跟进和改进。
标签: node.js firebase firebase-cloud-messaging google-cloud-functions firebase-admin