使用Firebase Admin SDK发送FCM消息遇DeprecatedApi错误排查
解决Firebase Admin SDK调用sendToDevice返回DeprecatedApi错误
问题根源
你调用的sendToDevice是旧版Legacy FCM HTTP API对应的方法,但你仅在Firebase控制台启用了FCM API (V1),V1 API不兼容旧版方法,因此返回DeprecatedApi错误。
解决方案
改用FCM V1 API对应的发送方法,并调整消息结构至V1格式:
1. 使用正确的发送方法
针对多设备令牌,使用sendMulticast方法(替代旧版sendToDevice);单设备令牌则用send方法。
2. 调整消息结构
V1 API的消息格式与旧版不同,需要将notification和data直接放在消息对象中,同时通过tokens字段指定目标设备令牌数组(多设备场景)。
修改后的代码示例
const firebaseAdmin = require('firebase-admin'); // 初始化代码无需修改 const firebaseApp = firebaseAdmin.initializeApp ( { credential: firebaseAdmin.credential.cert ({ type: 'service_account', project_id: '你的项目ID', private_key_id: '你的私钥ID', private_key: '你的私钥', client_email: '你的客户端邮箱', client_id: '你的客户端ID', auth_uri: 'https://accounts.google.com/o/oauth2/auth', token_uri: 'https://accounts.google.com/o/oauth2/token', auth_provider_x509_cert_url: 'https://www.googleapis.com/oauth2/v1/certs', client_x509_cert_url: '你的客户端证书URL' }), databaseURL: '你的数据库URL', }, 'app' ); // 改用V1 API的sendMulticast方法发送多设备消息 async function sendFCMMessage() { const message = { tokens: ['设备令牌1', '设备令牌2'], // 替换为你的目标令牌数组 notification: { title: '通知标题', body: '通知内容' }, data: { key1: 'value1', key2: 'value2' } }; try { const response = await firebaseApp.messaging().sendMulticast(message); console.log(`成功发送 ${response.successCount} 条消息,失败 ${response.failureCount} 条`); // 处理失败的消息 response.responses.forEach((resp, idx) => { if (!resp.success) { console.error(`令牌 ${message.tokens[idx]} 发送失败: ${resp.error}`); } }); } catch (error) { console.error('发送消息失败:', error); } } sendFCMMessage();
额外注意事项
- 默认生成的服务账号已具备
Cloud Messaging Admin权限,若发送仍有异常,可在IAM控制台检查权限配置。 - Firebase Admin SDK 12.x版本完全兼容V1 API,无需额外配置,只要使用正确的方法即可。
内容的提问来源于stack exchange,提问作者Aliaksandr Luferau
相关产品推荐
相关产品推荐

