3

我想使用服务帐户访问谷歌日历。这是我的代码: <NUMBER>被 Google API 控制台上的正确值替换。

<?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>";

当我执行我的代码时,我收到:

致命错误:未捕获的异常“Google_AuthException”与消息“刷新 OAuth2 令牌时出错,消息:'{“error”:“access_denied”}'' 在 /home/www/65683f67e3f0d94b14bba3c945014cda/web/intranet/googleapi/auth/Google_OAuth2.php :279 堆栈跟踪:#0 /home/www/65683f67e3f0d94b14bba3c945014cda/web/intranet/googleapi/auth/Google_OAuth2.php(256): Google_OAuth2->refreshTokenRequest(Array) #1 /home/www/65683f67e3f0d94b14bba3c945014cda/webtranet/ /auth/Google_OAuth2.php(209): Google_OAuth2->refreshTokenWithAssertion() #2 /home/www/65683f67e3f0d94b14bba3c945014cda/web/intranet/googleapi/service/Google_ServiceResource.php(166): Google_OAuth2->签名(对象(Google_HttpRequest))#3 /home/www/65683f67e3f0d94b14bba3c945014cda/web/intranet/googleapi/contrib/Google_CalendarService.php(154):Google_ServiceResource->__call('list',数组)#4 /home/www/65683f67e3f0d94b14bba3c945014c /web/intranet/testService.php(32): Google_CalendarListServiceResource->listCalendarList() #5 {main} 在/home/www/65683f67e3f0d94b14bba3c945014cda/web/intranet/googleapi/auth/Google_OAuth2.php 279 行

如果我更改我的代码:

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

我收到:

(403) 访问未配置

这里出了什么问题?

4

1 回答 1

3

我有解决办法。首先好的代码是最后一个:

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

问题不在于代码,而在于我的 google 帐户,我在 Google API Console 中提到了一个 Referer。擦除字段后,代码工作。

仅供参考,如果您想访问共享日历,请不要忘记与您的 XXXXXX@developer.gserviceaccount.com(您的 SERVICE_ACCOUNT_NAME)共享您的日历。

有关更多信息,请参阅:

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

于 2012-10-29T08:16:27.583 回答