2012-10-28 27 views
2

我想使用服務帳戶訪問谷歌日曆。這是我的代碼: <NUMBER>正在取代Google API控制檯上的正確值。使用服務帳戶訪問Google日曆活動:{「error」:「access_denied」}。沒有谷歌應用程序

<?php 

require_once 'googleapi/Google_Client.php'; 
require_once 'googleapi/contrib/Google_CalendarService.php'; 

const CLIENT_ID = '<NUMBER>.apps.googleusercontent.com'; 
const SERVICE_ACCOUNT_NAME = '<NUMBER>@developer.gserviceaccount.com'; 
const MY_EMAIL = '<MY NAME>@gmail.com'; 
const KEY_FILE = 'privatekey.p12'; 

$client = new Google_Client(); 
$client->setClientId(CLIENT_ID); 
$client->setApplicationName("<APP NAME>"); 

$key = file_get_contents(KEY_FILE); 
$client->setAssertionCredentials(new Google_AssertionCredentials(
    SERVICE_ACCOUNT_NAME, 
    array('https://www.googleapis.com/auth/calendar'), 
    $key, 
    'notasecret', 
    'http://oauth.net/grant_type/jwt/1.0/bearer', 
    MY_EMAIL) 
); 

$cal = new Google_CalendarService($client); 
$calList = $cal->calendarList->listCalendarList(); 

print "<h1>Calendar List</h1><pre>" . print_r($calList, true) . "</pre>"; 

當我執行我的代碼,我得到:

Fatal error: Uncaught exception 'Google_AuthException' with message 'Error refreshing the OAuth2 token, message: '{ "error" : "access_denied" }'' in /home/www/65683f67e3f0d94b14bba3c945014cda/web/intranet/googleapi/auth/Google_OAuth2.php:279 Stack trace: #0 /home/www/65683f67e3f0d94b14bba3c945014cda/web/intranet/googleapi/auth/Google_OAuth2.php(256): Google_OAuth2->refreshTokenRequest(Array) #1 /home/www/65683f67e3f0d94b14bba3c945014cda/web/intranet/googleapi/auth/Google_OAuth2.php(209): Google_OAuth2->refreshTokenWithAssertion() #2 /home/www/65683f67e3f0d94b14bba3c945014cda/web/intranet/googleapi/service/Google_ServiceResource.php(166): Google_OAuth2->sign(Object(Google_HttpRequest)) #3 /home/www/65683f67e3f0d94b14bba3c945014cda/web/intranet/googleapi/contrib/Google_CalendarService.php(154): Google_ServiceResource->__call('list', Array) #4 /home/www/65683f67e3f0d94b14bba3c945014cda/web/intranet/testService.php(32): Google_CalendarListServiceResource->listCalendarList() #5 {main} thrown in /home/www/65683f67e3f0d94b14bba3c945014cda/web/intranet/googleapi/auth/Google_OAuth2.php on line 279

如果我更改了代碼:

$client->setAssertionCredentials(new Google_AssertionCredentials(
SERVICE_ACCOUNT_NAME, 
array('https://www.googleapis.com/auth/calendar'), 
$key)); 

我收到:

(403) Access Not Configured

這是怎麼回事這裏錯了嗎?

+1

沒關係,我有解決方案,但抱歉,我必須等待2小時後它(計算器規則);) – Fabien

回答

3

我有解決方案。 首先,良好的代碼是最後一個:

$client->setAssertionCredentials(new Google_AssertionCredentials(
     SERVICE_ACCOUNT_NAME, 
     array('https://www.googleapis.com/auth/calendar'), 
     $key)); 

的問題是不是代碼,但我的谷歌帳戶,我剛纔提到在谷歌API控制檯的Referer。刪除該字段後,代碼將起作用。

有關信息,如果您想訪問共享日曆,請不要忘記與您的[email protected](您的SERVICE_ACCOUNT_NAME)共享您的日曆。

欲瞭解更多信息,請參見:

https://groups.google.com/forum/?fromgroups=#!topic/google-ajax-search-api/kaKYuUstwB0/discussion

+0

謝謝,我用這個掙扎了一會兒..不知道我必須通過添加開發者帳戶來訪問我的日曆。 – Maarten00

相關問題