Google OAuth2 错误 - 缺少必需参数:刷新时grant_type


Google OAuth2 error - Required parameter is missing: grant_type on refresh

>我已经使用Google日历API构建了一个原型日历同步系统,除了刷新访问令牌外,它运行良好。这些是我经历的步骤:

1) 授权我的 API 并收到授权代码。

2) 将授权代码交换为访问令牌和刷新令牌。

3) 使用日历 API,直到访问令牌过期。

此时,我尝试使用刷新令牌来获取另一个访问令牌,因此我的用户不必继续授予访问权限,因为日记同步发生在他们脱机时。

这是PHP代码,我在整个系统中使用curl请求。

$requestURL = "https://accounts.google.com/o/oauth2/token";
$postData = array("grant_type" => "refresh_token", 
                  "client_id" => $clientID,    
                  "client_secret" => $clientSecret, 
                  "refresh_token" => $refreshToken);
$headers[0] = 'Content-Type: application/json';
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_URL, $requestURL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData));
$response = curl_exec($ch);
$responseArray = json_decode($response, TRUE);

我得到的回应是:

[error] => invalid_request
[error_description] => Required parameter is missing: grant_type

未报告卷曲错误。

我尝试了标题内容类型:application/x-www-form-urlencoded,以及许多其他东西,结果相同。

我怀疑这在我的 curl 设置或标题中很明显,因为此请求的 Google 文档中提到的每个参数都已设置。但是,我正在兜圈子,因此希望得到任何帮助,包括指出我忽略的任何明显错误。

您的请求不应发布 JSON 数据,而应查询表单编码数据,如下所示:

$requestURL = "https://accounts.google.com/o/oauth2/token";
$postData = "grant_type=refresh_token&client_id=$clientID&client_secret=$clientSecret&refresh_token=$refreshToken";
$headers[0] = 'Content-Type: application/x-www-form-urlencoded';
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_URL, $requestURL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
$response = curl_exec($ch);
$responseArray = json_decode($response, TRUE);