如何向Firebase推送通知中发送user_id、name等额外自定义数据
Firebase推送携带自定义参数解决方案
核心逻辑
Firebase Cloud Messaging 推送载荷里的data字段就是专门用于传递自定义业务参数的区域,你需要传给前端的user_id、name等参数都可以放到这个字段中,前端可以直接读取该字段下的所有键值对。
你原有代码里已经保留了data字段,但目前是直接复用了通知栏显示的notification内容,只需要调整这部分逻辑,追加自定义参数即可。
优化后代码
// 新增$customData可选参数,用于传入自定义业务参数,默认是空数组 function sendPushNotification($token, $push_notification_title = null, $push_notification_body = null, $customData = []){ $url = env('FIREBASE_URL'); $serverKey = env('FIREBASE_SERVER_KEY'); $title = $push_notification_title ?? "New Physician Review"; $body = $push_notification_body ?? "Your case has been reviewed"; // 通知栏显示配置,仅控制系统通知的展示样式 $notification = array('title' => $title, 'text' => $body, 'body' => $body, 'sound' => 'default', 'badge' => '1'); // 构造传给前端的自定义数据,合并基础通知信息和传入的自定义参数 $payloadData = array_merge( [ 'title' => $title, 'body' => $body ], $customData ); $arrayToSend = array( 'to' => $token, 'notification' => $notification, 'priority' => 'high', 'data' => $payloadData, // 替换为合并后的自定义数据 'content_available' => true ); $json = json_encode($arrayToSend); $headers = array(); $headers[] = 'Content-Type: application/json'; $headers[] = 'Authorization: key=' . $serverKey; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POSTFIELDS, $json); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_HEADER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); $response = curl_exec($ch); curl_close($ch); return $response; }
调用示例
传递user_id、name参数时直接在调用时传入第四个参数即可:
sendPushNotification( '用户的设备token', '审核结果通知', '你的病例已经完成审核', [ 'user_id' => '10086', 'name' => '张三', 'case_id' => '20240501001' // 还可以追加其他任意自定义参数 ] );
前端获取参数方式
- Android端:在
FirebaseMessagingService的onMessageReceived回调中,调用remoteMessage.getData()获取参数集合,直接通过键名读取对应值即可 - iOS端:在推送接收回调中,从
userInfo字典中直接读取对应的自定义参数键名即可
注意事项
- 建议
data字段内的参数值统一使用字符串类型,避免不同系统解析时出现类型转换异常 - 你原有代码中已配置
priority: high和content_available: true,可以保证应用在后台状态下也能正常获取到自定义参数
内容的提问来源于stack exchange,提问作者yohan dhanushka fernando
相关产品推荐
相关产品推荐

