Firebase Cloud Functions调用FCM发消息失败:端点已弃用
我用Firebase Cloud Function实现了一个功能:当Firestore数据库中wpPosts/{title}文档创建时,通过FCM向newDeal主题推送消息。此前功能运行正常,但近期日志频繁出现端点弃用错误,功能时好时坏。错误提示要求迁移到FCM HTTP v1,但我并未直接调用HTTP端点,只是使用Admin SDK的sendToTopic()方法,不清楚该如何修改。
我的代码
const functions = require("firebase-functions"); const admin = require("firebase-admin"); admin.initializeApp(); exports.onWordpressPostCreate = functions.firestore .document("wpPosts/{title}") .onCreate((snap, context) => { console.log("-------------start create function-----------------"); const data = snap.data(); const title = data.title; const excerpt = data.excerpt; const payload = { notification: { title: `Neuer Deal: ${title}`, body: excerpt, badge: "1", sound: "default", }, }; return admin.messaging().sendToTopic("newDeal", payload) .then((response) => { console.log("Successfully sent message:", response); }) .catch((error) => { console.error("FCM failed", error); }); });
收到的错误提示
"message: 'An unknown server error was returned. Raw server response: "{"error":"Deprecated endpoint, see https://firebase.google.com/docs/cloud-messaging/migrate-v1"}"'"
解决方法
这个问题的核心是你使用的Firebase Admin SDK版本过旧,旧版本SDK底层仍在调用已被弃用的FCM Legacy API端点。虽然你没有直接编写HTTP请求,但SDK内部会处理这些底层逻辑,只需升级SDK即可解决问题,无需修改现有业务代码。
具体操作步骤:
- 进入你的Cloud Functions项目目录,在终端执行升级命令:
npm update firebase-admin firebase-functions - 重新部署更新后的函数:
firebase deploy --only functions:onWordpressPostCreate
升级完成后,Admin SDK会自动切换到FCM HTTP v1 API,你的sendToTopic()调用方式和payload结构完全兼容,无需额外修改。如果升级后遇到权限问题,确认你的Cloud Functions服务账号拥有Cloud Messaging Admin角色即可(默认的App Engine服务账号通常已包含该权限)。
内容的提问来源于stack exchange,提问作者schmale96

