使用Curl调用FCM V1 API向主题发通知时出现400错误
解决FCM v1 API发送主题通知时的400错误
错误信息
"code": 400,
"message": "Invalid JSON payload received. Unknown name "to": Cannot find field."
问题原因
你使用的是FCM v1版本API,但请求Payload里沿用了旧版Legacy API的to字段指定主题。FCM v1 API中,指定主题目标需使用topic字段,而非to。
修改后的代码
public function sendTopic($topic,$title,$body, $data , $type, $image='') { $client = new Client(); $url = 'https://fcm.googleapis.com/v1/projects/wooloveapp-dda64/messages:send'; $fields = [ 'message' => [ // 将原"to"字段替换为v1 API要求的"topic"字段 "topic" => $topic, "notification" => [ "title" => $title, "body" => $body, ], "data" => [ "data" => json_encode($data) ], "android" => [ "notification" => [ "sound" => "default", "title" => $title, "body" => $body, 'tag' => $topic, "channel_id" => "500", ], "priority" => "high", "ttl" => "86400s" //"badge" => 1 ], "apns" => [ "payload" => [ "aps" => [ "sound" => "default" ] ], "headers" => [ "apns-priority" => "5", "content_available" => "1" ], ], "webpush"=>[ "headers"=>[ "Urgency"=> "high", //"image" => "https://wooloveapp.com/img/misc/logo-02.jpg" ] ], ] ]; $headers = [ 'Authorization: Bearer ' .$this->getGoogleAccessToken(), 'Accept:application/json', 'Content-Type:application/json', ]; // 移除手动设置的Content-Length,curl会自动计算处理,避免编码误差导致请求失败 // 'Content-Length:'.strlen(json_encode($fields)), $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); 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); $result = [ 'result' => $result, //'statusCode' => $statusCode ]; return $result; }
额外说明
- 若需实现多主题组合的目标筛选,可使用
condition字段,格式示例:"'topic1' in topics && 'topic2' in topics" - 手动设置
Content-Length容易因字符编码、转义等问题出现计算误差,交由curl自动处理更可靠
内容的提问来源于stack exchange,提问作者gabogabans
相关产品推荐
相关产品推荐

