使用刷新令牌的谷歌日历 API


Google Calendar API using refresh token

我的网站上有一个php应用程序,允许我的用户使用我的一个谷歌日历来安排/重新安排日历事件,所以我不需要用户通过谷歌进行身份验证。 我已经完成了获取令牌并存储了刷新令牌的工作,但现在当我尝试访问日历时,我收到一个错误,说我的令牌已过期。 输出为

创建客户端找到访问令牌 = { "access_token" : "长...令 牌。。。string", "token_type" : "持有者", "expires_in" : 3600 }发生错误:(0) OAuth 2.0 访问令牌已过期,刷新令牌不可用。对于自动批准的响应,不会返回刷新令牌。

不知道为什么我会收到此错误。

function getAccessToken(){
$tokenURL = 'https://accounts.google.com/o/oauth2/token';
$postData = array(
    'client_secret'=>'My-Secret',
    'grant_type'=>'refresh_token',
    'approval_promt'=> 'force',
    'refresh_token'=>'My-Refresh-Token',
    'client_id'=>'My-Client-ID'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $tokenURL);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$tokenReturn = curl_exec($ch);
return $tokenReturn;
}
function outputCalendarByDateRange($client, $startDate='2007-05-01', $endDate='2007-08-01'){
  date_default_timezone_set("America/Chicago");
  $client->addScope('https://www.googleapis.com/auth/calendar');
  try {
    $service = new Google_Service_Calendar($client);
  }catch(Google_ServiceException $e){
    print "Error code :" . $e->getCode() . "'n";
    print "Error message: " . $e->getMessage() . "'n";
  } catch (Google_Exception $e) {
    print "An error occurred: (" . $e->getCode() . ") " . $e->getMessage() . "'n";
  }
  $optParams = array(
    'orderBy'=>'starttime',
    'singleEvents'=>False,
    'timeMax'=>$endDate,
    'timeMin'=>$startDate,
    'timeZone'=>'America/Chicago',
    'maxResults'=>1000
  );
  try{
    $events = $service->events->listEvents('primary',$optParams);
  } catch (Google_ServiceException $e) {
    print "Error code :" . $e->getCode() . "'n";
    print "Error message: " . $e->getMessage() . "'n";
  } catch (Google_Exception $e) {
    print "An error occurred: (" . $e->getCode() . ") " . $e->getMessage() . "'n";
  }
  foreach ($events->getItems() as $event) {
    echo $event->getSummary();
  }
}
echo "creating a client<br>";
$client = new Google_Client();
$accessToken = getAccessToken();
echo "found access token = ".$accessToken."<br>";
try{
  $client->setAccessToken($accessToken);
}
catch (Google_ServiceException $e) {
    print "Error code :" . $e->getCode() . "'n";
    print "Error message: " . $e->getMessage() . "'n";
  } catch (Google_Exception $e) {
    print "An error occurred: (" . $e->getCode() . ") " . $e->getMessage() . "'n";
}
outputCalendarByDateRange($client, $today, $tomorrow);

应考虑使用服务帐户执行此操作。 服务帐号将允许您的应用访问您的 Google 日历数据,而无需提示用户进行访问。

创建服务帐户时,请获取它为您提供的电子邮件地址,并将其添加到Google日历中,就像任何其他用户一样。 然后,脚本将有权访问它。

    <?php
session_start();        
require_once 'Google/Client.php';
require_once 'Google/Service/Calendar.php';     
/************************************************   
 The following 3 values an befound in the setting   
 for the application you created on Google      
 Developers console.         Developers console.
 The Key file should be placed in a location     
 that is not accessable from the web. outside of 
 web root.   
 In order to access your GA account you must    
 Add the Email address as a user at the     
 ACCOUNT Level in the GA admin.         
 ************************************************/
$client_id = '1046123799103-nk421gjc2v8mlr2qnmmqaak04ntb1dbp.apps.googleusercontent.com';
$Email_address = '1046123799103-nk421gjc2v8mlr2qnmmqaak04ntb1dbp@developer.gserviceaccount.com';     
$key_file_location = '629751513db09cd21a941399389f33e5abd633c9-privatekey.p12';     
$client = new Google_Client();      
$client->setApplicationName("Client_Library_Examples");
$key = file_get_contents($key_file_location);    
// seproate additional scopes with a comma   
$scopes ="https://www.googleapis.com/auth/calendar.readonly";   
$cred = new Google_Auth_AssertionCredentials(    
    $Email_address,      
    array($scopes),     
    $key         
    );      
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {        
    $client->getAuth()->refreshTokenWithAssertion($cred);       
}       
$service = new Google_Service_Calendar($client);    
?>
<html><body>
<?php
$calendarList  = $service->calendarList->listCalendarList();
print_r($calendarList);
while(true) {
    foreach ($calendarList->getItems() as $calendarListEntry) {
        echo "<a href='Oauth2.php?type=event&id=".$calendarListEntry->id." '>".$calendarListEntry->getSummary()."</a><br>'n";
    }
    $pageToken = $calendarList->getNextPageToken();
    if ($pageToken) {
        $optParams = array('pageToken' => $pageToken);
        $calendarList = $service->calendarList->listCalendarList($optParams);
    } else {
        break;
    }
}    
?>
</html> 

从教程中翻录的代码 谷歌日历 API 与 PHP – 服务帐户