1

我有一个网站,用户希望有他们的谷歌日历所有的例子似乎都有日历的所有者每次都进行身份验证。有没有办法验证我的应用程序以获取用户日历数据并显示它?

在他们接受我的应用程序后,我试图保存access_token所有者的,但过了一会儿我收到以下错误:

The OAuth 2.0 access token has expired, and a refresh token is not available. Refresh tokens are not returned for responses that were auto-approved.

这是我正在尝试的代码(顺便说一句,config.php 填写了所有 api 内容)

$client = new Google_Client();
$client->setUseObjects(true); 
$client->setApplicationName("My Unit Calendar");
$client->setAccessType('offline');
$client->setAccessToken($row['access_token'] ); //from the DB

$calService = new Google_CalendarService($client);

$events = $calService->events->listEvents( $row['google_cal_id'] ); //from the DB

echo "events--><pre>".print_r($events,true)."</pre>";

但我得到以下异常:

Google_AuthException-->The OAuth 2.0 access token has expired, and a refresh token is not available. Refresh tokens are not returned for responses that were auto-approved.

谢谢你的帮助

4

1 回答 1

1

在从 Google 获取/设置某些内容之前,您必须检查访问令牌是否未过期并使用刷新令牌刷新它,这是您在第一次授权后获得的(它由 返回$client->getAccessToken())。我想,你想做一些事情,像这样:

$client = new Google_Client();
$client->setUseObjects(true); 
$client->setApplicationName("My Unit Calendar");
$client->setAccessType('offline');
$client->setAccessToken($row['access_token'] ); //from the DB

$calService = new Google_CalendarService($client);

checkToken($client, $row['refresh_token']); // Added function

$events = $calService->events->listEvents( $row['google_cal_id'] );

// Check if Access token is expired and get new one using Refresh token
function checkToken($client) {
    if($client->isAccessTokenExpired()) {
        $client->refreshToken( $refresh_token );
    }
}

您必须将第一次授权时获得的数据库刷新令牌存储在数据库中,并检查访问令牌是否未过期,如果过期 - 刷新(例如在您的google_callback.php文件中):

// Initialize access to Google
$client = new Google_Client();
$client->setClientId( *** );
$client->setClientSecret( *** );
$client->setRedirectUri( *** );
$client->setAccessType( *** );

// Initialize access to Calendar as service
$service = new Google_CalendarService($client);

// If isset code - set into session
if (isset($_GET['code'])) {
    $client->authenticate($_GET['code']);
    $_SESSION['google-api']['access_token'] = $client->getAccessToken();
    header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}


// If in session is set token
if (isset($_SESSION['google-api']['access_token'])) {
    $client->setAccessToken($_SESSION['google-api']['access_token']);
}


// If Access Token Expired (uses Google_OAuth2 class), refresh access token by refresh token
if($client->isAccessTokenExpired()) {
    $client->refreshToken( /* Get refresh token from DB */);
}


// If client got access token successfuly - perform operations
$access_tokens = json_decode($client->getAccessToken());

if ($access_tokens) {
    // Update refreshToken and save data if refresh token is received (logged in now)
    if(isset($access_tokens->refresh_token)) {
        // Store in DB refresh token - $access_tokens->refresh_token
    }
}
于 2013-05-27T11:49:17.127 回答