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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 18:15:58