使用PHP API离线从Google日历事件中检索



我有一个网站,用户想要拥有其Google日历所有示例似乎每次都有日历的所有者。是否没有办法对我的应用程序进行身份验证以获取用户日历数据并显示它?

我在接受我的应用程序后试图保存所有者的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.

这是我正在尝试的代码(顺便

$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.

感谢您的任何帮助

从Google获取/设置某些内容之前,您必须检查访问令牌是否未过期,并使用Refresh令牌刷新它,您首先授权后获得(由$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
    }
}

相关内容

  • 没有找到相关文章