PHP Guzzle 请求获取access_token不起作用.与 CURL 配合使用正常



我开始尝试理解 Guzzle,但我的一个请求不断返回错误,即使使用 CURL 完成完全相同的请求工作正常。

我有一个refresh_token,想从WEB API获取access_token。

导致错误的 Guzzle 请求:

$refresh_token = '<token>';
$client = new GuzzleHttpClient(['headers' => ['Content-Type' => 'application/x-www-form-urlencoded']]);
$response = $client->request('POST', 'https://foo.bar/secure/token', [
'query' => ['grant_type' => 'refresh_token','refresh_token' => $refresh_token]
]);
echo $response->getStatusCode();
echo $response->getBody();

致命错误:在vendor/guzzlehttp/guzzle/src/Exception/RequestException.php:113中显示消息"客户端错误:导致400 Bad Request响应",未捕获异常"GuzzleHttp\Exception\ClientException">

此 CURL 请求工作正常:

$refresh_token = '<token>';
$params=['grant_type'=>'refresh_token',
'refresh_token'=>$refresh_token
];
$headers = [
'POST /secure/token HTTP/1.1',
'Content-Type: application/x-www-form-urlencoded'
];
$curlURL='https://foo.bar/secure/token';       
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$curlURL);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($params));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_VERBOSE, true);
$curl_res = curl_exec($ch);
if($curl_res) {
$server_output = json_decode($curl_res);
}
var_dump($curl_res);

我希望得到你的帮助。 这是在浏览器中打印出来的 Guzzle 调试。

Request Method: GET
Status Code: 200 OK
Remote Address: 87.236.19.237:80
Referrer Policy: no-referrer-when-downgrade
Connection: keep-alive
Content-Encoding: gzip
Content-Type: text/html
Date: Wed, 21 Aug 2019 15:46:25 GMT
Keep-Alive: timeout=30
Server: nginx-reuseport/1.13.4
Transfer-Encoding: chunked
Vary: Accept-Encoding
X-Powered-By: PHP/5.6.38
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3
Accept-Encoding: gzip, deflate
Accept-Language: ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7
Cache-Control: max-age=0
Connection: keep-alive
DNT: 1
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36

您的请求变为 GET 可能是因为"query"参数。

使用form_params而不是查询。

请参阅文档。

http://docs.guzzlephp.org/en/stable/request-options.html#form-params

这是正确的!啧

$response = $client->request('POST', 'https://sso.tinkoff.ru/secure/token', [
'form_params' => [
'grant_type' => 'refresh_token',
'refresh_token' => $refresh_token
]
]);

最新更新