1

在过去的几天里,我一直在努力解决这个问题。我已经阅读了所有论坛,但仍然没有解决方案。任何帮助表示赞赏。

我一直在尝试使用刷新代码。(我不想重复使用过期的访问代码)。我的代码基于http://www.jensbits.com/demos/ga/app/ga_app_oauth2_refreshtoken.txt

代码如下:

if (isset($_GET['code'])) {
    $accessToken = get_oauth2_token($_REQUEST['code'],"online"); //refresh_token not fetched

}

//注意如果我将上面的行替换为$client->authenticate(),然后是$client->getAccessToken(),程序正在运行。但后来我没有得到刷新代码

下面我从链接粘贴函数

function get_oauth2_token3($grantCode, $grantType) {
$redirect_uri = "xxxx";

$oauth2token_url = "https://accounts.google.com/o/oauth2/token";
$clienttoken_post = array(
    "client_id" => GCLIENT_ID,
    "client_secret" => GCLIENT_SECRET);

if ($grantType === "online") {
    $clienttoken_post["code"] = $grantCode;
    $clienttoken_post["redirect_uri"] = $redirect_uri;
    $clienttoken_post["grant_type"] = "authorization_code";
}

if ($grantType === "offline") {
    $clienttoken_post["refresh_token"] = $grantCode;
    $clienttoken_post["grant_type"] = "refresh_token";
}

$curl = curl_init($oauth2token_url);

curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $clienttoken_post);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

$json_response = curl_exec($curl);
curl_close($curl);

echo '<pre>';
print_r($grantCode);
print_r($json_response);
print_r(json_decode($json_response));
echo '</pre>';

这里没有刷新令牌

$authObj = json_decode($json_response);

//if offline access requested and granted, get refresh token
if (isset($authObj->refresh_token)) {
    global $refreshToken;

没有刷新令牌 $refreshToken = $authObj->refresh_token; }

$accessToken = $authObj->access_token;
return $accessToken;

}

修改后的代码

if ($grantType === "offline") {
    $clienttoken_post["grant_type"] = "authorization_code";
    $clienttoken_post["response_type"] = "code";

    $clienttoken_post["scope"] = "https://www.googleapis.com/auth/plus.me";
    $clienttoken_post["redirect_uri"] = $redirect_uri;
}

还将网址从 https://accounts.google.com/o/oauth2/token更改为https://accounts.google.com/o/oauth2/auth

4

3 回答 3

1

您需要请求令牌以使用“离线”而不是“在线”,以便取回刷新令牌。

请参阅https://developers.google.com/accounts/docs/OAuth2WebServer了解幕后情况的概述,这将有助于理解 OAuth 2 离线流程。

于 2013-01-18T20:51:38.137 回答
1

好吧,我认为您的代码是正确的。请检查执行步骤以验证是否执行了正确的代码。

如果它不是最新的,也请尝试更新您的 SDK。当我遇到这个问题时,我更新了 SDK 并且它工作了......

于 2013-01-27T11:28:51.527 回答
-1

此消息的另一个可能原因是 CLIENT_ID 或 CLIENT_SECRET 不正确

于 2013-10-01T15:34:09.583 回答