[英]PHP Guzzle request to get access_token not working. Works fine with CURL
我開始嘗試了解 Guzzle,但我的一個請求一直返回錯誤,即使使用 CURL 完成的完全相同的請求工作正常。
我有一個 refresh_token 並且想從 WEB API 獲取一個 access_token。
導致錯誤的 Guzzle 請求:
$refresh_token = '<token>';
$client = new GuzzleHttp\Client(['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 中出現未捕獲的異常“GuzzleHttp\\Exception\\ClientException”,消息為“客戶端錯誤:導致400 Bad Request
響應”
這個 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。
使用 form_params 而不是查詢。
請參閱文檔。
http://docs.guzzlephp.org/en/stable/request-options.html#form-params
這是對的! Tnx 約翰尼克斯!
$response = $client->request('POST', 'https://sso.tinkoff.ru/secure/token', [
'form_params' => [
'grant_type' => 'refresh_token',
'refresh_token' => $refresh_token
]
]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.