firebase 云函数如何使用 Admin SDK 向主题发送消息?

How do firebase cloud functions send messages to topics using the Admin SDK?

我有一个执行某些逻辑的云函数,完成后它会向名为 onPlanBeginning:

的主题发送一条消息
export const onNewPendingPlan = functions.firestore
    .document('pendingPlanCreations/{id}')
    .onCreate(async (pendingPlanDocSnap) => {
        try {
            //[... some logic that executes correctly ...]

            console.log(`Sending to topic`) // this log appears correctly in the firebase console logs

            const messageResponse = await admin.messaging().sendToTopic('onPlanBeginning', {
                data: {
                    foo: 'bar',
                },
                notification: {},
            })

            console.log(`Message id: ${messageResponse.messageId}`) // this one too, with a message id
        } catch (err) {
            console.error(err)
            return
        }
    })

然后,此函数应该记录该消息的内容:

export const onPlanBeginning = functions.pubsub
    .topic('onPlanBeginning')
    .onPublish(async (message) => {
        try {

            console.log(`Recieved message: ${JSON.stringify(message.json)}`)
            return

        } catch (err) {
            console.error(err)
            return
        }
    })

sendToTopic 执行前后的日志正确显示在 firebase 控制台日志中。但是消息没有在主题中发布,因此处理程序 Cloud Function 没有被执行。

我错过了什么吗?我已经使用 GCloud 控制台手动向主题发布了一条消息,并且正确执行了 Cloud Function onPlanBeginning

您的第一个 Cloud Function 正在向 Firebase Cloud Messaging 主题发送消息,而您的第二个 Cloud Function 正在收听 Google Cloud PubSub 主题。虽然两者都称为主题,但它们彼此无关,发送到 FCM 主题的消息不会传递给 PubSub 主题观察者。

要向 PubSub 主题发送消息,请查看此 example

无法在 Cloud Functions 中接收 FCM 消息。用于接收消息的 FCM SDK 仅适用于 iOS 和 Android。