Google OAuth2返回"unsupported_grant_type"通过cURL(PHP)
问题描述:
我想获取有关Google帐户的数据.我使用下一个代码:
I want to get data about google account. I use next code:
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://www.googleapis.com/oauth2/v4/token',
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTPHEADER => [
'Cache-Control: no-cache',
'Content-Type: application/x-www-form-urlencoded',
],
CURLOPT_POSTFIELDS => [
'code' => $code,
'client_id' => '{MY_CLIENT_ID}',
'client_secret' => '{MY_CLIENT_SECRET}',
'redirect_uri' => '{SOME_URL}'
'grant_type' => 'authorization_code',
]
));
$result = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
结果我得到下一个错误:
In result I get next error:
{
"error": "unsupported_grant_type",
"error_description": "Invalid grant_type: "
}
我使用以下指示:
https://developers.google.com/identity/protocols/OpenIDConnect
变量$code
和其他数据有效!因为我尝试通过"PostMan"发送请求,所以我得到了正确的结果.
Variable $code
and another data are valid! Because I try to send request via "PostMan" and there I get correct result.
请告诉我,我哪里有错?
Tell me please, where I have mistake?
答
上面的代码在此行的末尾缺少逗号:
The above code is missing a comma at the end of this line:
'redirect_uri' => '{SOME_URL}'
完整代码应为:
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://www.googleapis.com/oauth2/v4/token',
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTPHEADER => [
'Cache-Control: no-cache',
'Content-Type: application/x-www-form-urlencoded',
],
CURLOPT_POSTFIELDS => [
'code' => $code,
'client_id' => '{MY_CLIENT_ID}',
'client_secret' => '{MY_CLIENT_SECRET}',
'redirect_uri' => '{SOME_URL}',
'grant_type' => 'authorization_code',
],
));
$result = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);