PHP实现Android设备FCM推送报错:JSON字段无效问题求助
解决FCM v1 API字段无效问题
你的错误根源是使用了FCM v1 API的端点,但请求payload还是旧版Legacy API的格式,FCM v1对请求结构有严格要求,和旧版完全不同。以下是修复步骤和修改后的代码:
关键问题点
- FCM v1的
messages:send仅支持单设备发送,批量发送需改用messages:sendAll端点 - v1 API要求所有消息内容嵌套在
message对象中,不允许直接在根节点放置notification/data/registration_ids android_channel_id字段需移至message.android.notification节点下,而非根notification对象
修改后的完整代码
function sendFCM($registrationIds, $notifTitle, $notifDesc, $notifChannel, $data) { $client = new Google_Client(); $client->setAuthConfig('bla.json'); $client->addScope('https://www.googleapis.com/auth/firebase.messaging'); $client->refreshTokenWithAssertion(); $token = $client->getAccessToken(); $accessToken = $token['access_token']; $headers = array ( 'Authorization: Bearer ' . $accessToken, 'Content-Type: application/json' ); // 构建批量消息数组 $messages = []; foreach ($registrationIds as $deviceToken) { $messages[] = [ 'token' => $deviceToken, 'notification' => [ "title" => $notifTitle, "body" => $notifDesc, "icon" => "ic_logo_circle" ], 'data' => $data, 'android' => [ 'notification' => [ 'channel_id' => $notifChannel ] ] ]; } // 符合FCM v1规范的请求体 $fields = [ 'messages' => $messages ]; $ch = curl_init(); // 替换为批量发送的端点 curl_setopt($ch, CURLOPT_URL, 'https://fcm.googleapis.com/v1/projects/projectname/messages:sendAll'); 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); print($result); curl_close($ch); } $notifData = array( "title" => "this is the title", "msg" => "the desc", "image" => "whatever.jpg" ); sendFCM($registrationIds, "Antwort auf Kommentar", "Cornholio hat dir geantwortet", "channel_reply_comment", $notifData);
额外注意事项
- 确保
projectname替换为你实际的Firebase项目ID sendAll端点一次最多支持发送500条消息,如果你的$registrationIds数量超过500,需要拆分分批发送- 建议开启
CURLOPT_SSL_VERIFYPEER为true以保证请求安全性,仅在测试环境临时关闭
内容的提问来源于stack exchange,提问作者TheGreatCornholio
相关产品推荐
相关产品推荐

