2014-12-05 4 views
2

내 사용자가 내 Google 캘린더 중 하나를 사용하여 캘린더 일정을 예약/일정을 조정할 수있는 PHP 앱이 있으므로 사용자가 Google 인증을받을 필요가 없습니다. 토큰을 가져 와서 새로 고침 토큰을 저장했지만 지금은 토큰이 만료되었다는 오류 메시지가 표시됩니다. 오류가 발생 출력 액세스 토큰 = { "긴 ... 토큰 ... 문자열", "token_type": "베어러", "expires_in"3600 "access_token은"} 발견 클라이언트를 생성새로 고침 토큰을 사용하는 Google 캘린더 API

인 : (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); 
+0

튜토리얼 Google Calendar API with PHP – Service Account에서 빼낸. 여기에서 https://developers.google.com/accounts/docs/OAuth2WebServer 키워드 access_type –

답변

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 = '[email protected]eaccount.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> 

코드는 때때로 때 경우 유형의 액세스 온라인 발생과 오프라인해야

+1

을 확인하십시오. 완전한! – t3living

+0

새로운 자습서입니다.이 게시물 전용입니다. – DaImTo

+0

정말 도움이 .. 많이 고마워 .. 거의 10 시간 낭비 후 .. 나는 이것을 발견하고 완벽하게 작동 ..! –

관련 문제