使用服务帐户访问Google日历事件:{&Quot;Error&Quot;:&Quot;Access_Denided&Quot;}。没有谷歌应用程序

人气:177 发布:2022-10-16 标签: php google-api google-calendar-api

问题描述

我想使用服务帐户访问Google日历。这是我的代码: <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->刷新令牌请求(数组)#1 /home/www/65683f67e3f0d94b14bba3c945014cda/web/intranet/googleapi/auth/Google_OAuth2.php(209): Google_OAuth2->renhTokenWithAssertion()#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’,数组)#4 /home/www/65683f67e3f0d94b14bba3c945014cda/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)访问权限未配置

这里出了什么问题?

推荐答案

我有解决方案。 首先是好的代码,最后才是代码:

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

问题不是代码,而是我的Google账户,我在Google API控制台中提到了一个推荐人。擦除该字段后,代码即可工作。

为了提供信息,如果您想要访问共享日历,请不要忘记与您的XXXXXX@developer.gserviceAccount.com(您的服务帐户名称)共享您的日历。

有关详细信息,请参阅:

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

329