如何为单个用户生成推送通知负载数组而非统一负载
解决方案:为每个用户生成个性化推送负载
原代码的核心问题是使用统一推送负载发给所有用户,完全忽略了每个用户的自定义音效设置。要实现个性化通知,需要为每个用户单独构造包含其专属音效的消息,再批量发送。
具体修改步骤
- 收集用户的token和自定义音效:遍历用户数据时,同时保存
push_token和pushnotificationsound字段(用户未设置时用default作为兜底)。 - 构造个性化消息数组:为每个用户生成独立的消息对象,将
sound字段替换为该用户的自定义音效值。 - 使用
sendEach批量发送:Firebase Messaging的sendEach方法支持传入消息数组,每个消息对应一个用户的token和专属负载,完美适配个性化需求。
修改后的完整代码
const functions = require('firebase-functions'); const admin = require('firebase-admin'); admin.initializeApp(); exports.demopush = functions.firestore.document('Demo Alarms/{documentId}').onCreate(async (snapshot, context) => { const post = snapshot.data(); const Type = post.Type; const code = post.Code; const address = post.Address; const usersSnapshot = await admin.firestore() .collection('users') .where('agency', '==', 'demo') .get(); // 收集每个用户的token和自定义音效 const usersWithTokens = []; usersSnapshot.forEach(doc => { const userData = doc.data(); const agency = userData.agency?.toLowerCase(); const token = userData.push_token; // 用户未设置音效时,默认使用系统音效 const customSound = userData.pushnotificationsound || 'default'; if (agency === 'demo' && token) { usersWithTokens.push({ token, sound: customSound }); } }); if (usersWithTokens.length === 0) { console.log('No users to send notification to.'); return; } // 为每个用户生成独立的推送负载 const messages = usersWithTokens.map(user => ({ token: user.token, notification: { title: 'DEMO DEPARTMENT', body: `${Type} ${code} at ${address}`, sound: user.sound, android_channel_id: "Alarms" } })); try { const response = await admin.messaging().sendEach(messages); console.log('Notifications sent successfully:', response); // 可选:统计成功/失败的发送数量 console.log(`Successfully sent: ${response.successCount}, Failed: ${response.failureCount}`); } catch (error) { console.error('Error sending notifications:', error); } });
关键细节说明
- 统一
agency字段的大小写判断(转小写后对比),避免因大小写差异过滤掉目标用户。 - 为
sound字段设置默认值,防止用户未配置音效时出现空值导致推送失败。 sendEach替代sendToDevice:后者只能传递统一负载,前者支持每个消息独立配置,完全满足个性化推送需求。
内容的提问来源于stack exchange,提问作者Medic305
相关产品推荐
相关产品推荐

