首页 文章

Google Calendar API使用刷新令牌

提问于
浏览
2

我的网站上有一个php应用程序,允许我的用户使用我的一个谷歌日历安排/重新安排日历活动,因此我不需要用户通过谷歌进行身份验证 . 我已经通过获取令牌并存储了刷新令牌,但现在当我尝试访问日历时,我收到一条错误消息,表明我的令牌已过期 . 输出是

创建客户端发现访问令牌= {“access_token”:“long ... token ... string”,“token_type”:“Bearer”,“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);

1 回答

  • 2

    您应该考虑使用服务帐户执行此操作 . service account将允许您的应用访问您的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>
    

    从教程中删除的代码Google Calendar API with PHP – Service Account

相关问题