向 FCM API 发送请求时收到无效 JSON 负载

Invalid JSON payload received when sending request to FCM API

我正在通过我的 PHP 应用向 FCM 发送请求,但 returns 出现以下错误:

{ 
"code": 400,
"message": "Invalid JSON payload received. 
    Unknown name \"{\"validateOnly\":true,\"message\":{\"name\":\"testName\",\"token\":\"validToken\"}}\":
    Cannot bind query parameter. Field '{\"validateOnly\":true,\"message\":{\"name\":\"testName\",\"token\":\"validToken\"}}' 
    could not be found in request message.",
"status": "INVALID_ARGUMENT",
"details": [ { "@type": "type.googleapis.com/google.rpc.BadRequest",
"fieldViolations": [ 
   { "description": "Invalid JSON payload received. 
       Unknown name \"{\"validateOnly\":true,\"message\":{\"name\":\"testName\",\"token\":\"validToken\"}}\":
       Cannot bind query parameter.
       Field '{\"validateOnly\":true,\"message\":{\"name\":\"testName\",\"token\":\"validToken\"}}' could not be found in request message."
} ] } ] } }

我的通知

$notification = [
    'validateOnly' => true,
    'message' => [
        'name' => $name,
        'token' => "validToken"
    ]
];

$notification = json_encode($notification)

作为JSON:

{ 
   "validateOnly":true,
   "message":{ 
      "name":"testName",
      "token":"validToken"
   }
}

我的httpheader

$header = [
        'Accept' => 'application/json',
        'Content-Length' => strlen($notification),
        'Content-Type' => 'application/json',
];

$header = json_encode($header, JSON_UNESCAPED_SLASHES);

作为JSON:

{ 
   "Accept":"application/json",
   "Content-Length":72,
   "Content-Type":"application/json"
}

我的 cURL 代码

$curl_session = curl_init();
try {
    curl_setopt($curl_session, CURLOPT_URL, $this->_apiUrl);
    //_api_Url = https://fcm.googleapis.com/v1/projects/projectName/messages:send?access_token=$access_token
    curl_setopt($curl_session, CURLOPT_POST, true);
    curl_setopt($curl_session, CURLOPT_HTTPHEADER, $header);
    curl_setopt($curl_session, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl_session, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl_session, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
    curl_setopt($curl_session, CURLOPT_POSTFIELDS, $notification);
} catch (Exception $e) {
    print_r($e);
}
$result = curl_exec($curl_session);
curl_close($curl_session);

我的猜测是 \"{\"validateOnly\"... 中的前两个引号导致了问题。 那可能吗?如果是这样,您建议我如何修复它? 还有其他想法吗?据我所知,根据 HTTP v1 docs

我的所有代码都是正确的

你的headers错了。这不是 php-curl 期望的方式,因此您的请求内容类型将是默认的 application/x-www-form-urlencoded 而不是 json。它应该是这样的:

$header = [
    'Accept:application/json',
    'Content-Length:'.strlen($notification),
    'Content-Type:application/json',
];
curl_setopt($curl_session, CURLOPT_HTTPHEADER, $header);

并且不要 json 对其进行编码,只需将其传递给 curl。

您可以在此处找到此文档:https://www.php.net/manual/en/function.curl-setopt.php

An array of HTTP header fields to set, in the format array('Content-type: text/plain', 'Content-length: 100')