Google OAuth2通过cURL返回“unsupported_grant_type”(PHP)
问题描述:
我想获取有关Google帐户的数据。我用下面的代码:Google OAuth2通过cURL返回“unsupported_grant_type”(PHP)
$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);
在结果我得到一个错误:
{
"error": "unsupported_grant_type",
"error_description": "Invalid grant_type: "
}
我使用说明此:
https://developers.google.com/identity/protocols/OpenIDConnect
可变$code
和另一个数据是有效的!因为我试图通过“PostMan”发送请求,并且我得到了正确的结果。
请告诉我,我哪里有错?
答
尝试这样做,以这样的方式
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://www.googleapis.com/oauth2/v4/token',
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_POSTFIELDS => http_build_query([
'code' => $code,
'client_id' => '{MY_CLIENT_ID}',
'client_secret' => '{MY_CLIENT_SECRET}',
'redirect_uri' => '{SOME_URL}'
'grant_type' => 'authorization_code',
]),
));
顺便说一句,你可以使用
CURLOPT_VERBOSE => true,
答
我在C#这样做调试卷曲的要求,并认为我的问题可能有关。当指定redirect_url或任何其他字符串时,请确保您转义URI,否则它会弄乱发布请求。这是因为请求是使用application/x-www-form-urlencoded类型发送的。
感谢您的回答!我尝试了你的方式,我得到了同样的错误...但是!当我尝试不同的“redirect_uri”时,我解决了我的麻烦。我不明白,为什么不能在参数中使用每个URI?它们都添加到我的Google App的列表中,但只有一个(不是第一个!)来自6个URI是有效的!我错过了Google App的设置? – vitaliy
我找到解决方案。顺便说一句,需要设置“redirect_uri”与获取“代码”的第一个请求中设置的URL相同。就这样。 P.S .:也许我错过了来自文档的注释...... :( – vitaliy