You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP实现Firebase多设备推送通知失败问题求助

解决FCM多设备推送失败的问题

我一眼就看出问题出在哪了!你的代码里犯了一个FCM API使用的常见错误——给单个设备推送用to字段,但多设备推送必须用registration_ids字段。

FCM的规则很明确:

  • to:只能接收单个设备令牌(string类型)
  • registration_ids:接收设备令牌数组,用来给多个设备批量推送

你现在把数组赋值给了to字段,FCM肯定识别不了,自然就没法给多设备发通知。

修正后的代码

protected function pushNotification($reg_id){
    define( 'API_ACCESS_KEY', 'AAAAgUh9ZSQ:APA91bEjQ2nO3Po9_-T_kNey4q3Eizcoc3gLsD04Bjh0KYXQu_33O2gpLBvmMV_DtbE3xP2evZ1Dwki6WRqgqu8ZYhOG2CYi-6Wpxq2CLy3SQPb1nD6QkzwNN0249pt-H2mAgB8L-sjm' );
    
    // 确保$reg_id是数组(如果调用时传的是单个token,也可以先转成数组)
    $registrationIds = is_array($reg_id) ? $reg_id : array($reg_id);
    
    $msg = array ( 
        'body' => 'Hey! You have a new order in queue', 
        'title' => 'New Order Receieved', 
        'icon' => 'myicon',/*Default Icon*/ 
        'sound' => 'mySound'/*Default sound*/ 
    );
    
    // 关键修改:把to换成registration_ids
    $fields = array ( 
        'registration_ids' => $registrationIds, 
        'notification' => $msg 
    );
    
    $headers = array ( 
        'Authorization: key=' . API_ACCESS_KEY, 
        'Content-Type: application/json' 
    );
    
    $ch = curl_init();
    curl_setopt( $ch,CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send' );
    curl_setopt( $ch,CURLOPT_POST, true );
    curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
    curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
    curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
    curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
    
    $result = curl_exec($ch );
    // 可以加个curl错误排查
    if(curl_errno($ch)){
        error_log("Curl Error: ".curl_error($ch));
    }
    curl_close( $ch );
    error_log("Result ".$result) ;
}

额外注意事项

  • 批量限制:FCM的registration_ids最多支持一次推送1000个设备,如果你的设备数量超过这个数,记得要分批处理。
  • 令牌有效性:推送前尽量过滤掉无效/过期的设备令牌,避免因为个别无效令牌导致整批推送失败。
  • 调用方式:调用这个方法时,要传入设备令牌数组,比如:
    // 示例:给两个设备发通知
    $tokens = ["token_123", "token_456"];
    $this->pushNotification($tokens);
    

这样修改后,多设备推送应该就能正常工作了!

内容的提问来源于stack exchange,提问作者user8164155

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:03:05