【发布时间】:2015-12-25 07:03:58
【问题描述】:
我正在尝试使用来自 PHP GAE 的 Google Api OAuth 服务帐户创建 Google 日历活动。
我需要日历事件字段“创建者”中的正确会话 ID 或用户电子邮件 ID。 这在 Google Apps Script(GAS) 中是可行的,它使用正确的会话 ID 创建事件。
但是,我希望在 PHP GAE(Google App Engine) 中做同样的事情。所以,我尝试冒充用户ID如下:Perform Google Apps Domain-Wide Delegation of Authority
我的目标是自动插入任何最终用户的正确用户 ID,就像在 GAS(Google Apps Script) 中一样。 我不希望在“创建者”字段中设置任何默认凭据..
使用 PHP 客户端库,我尝试在 Calendar API 中模拟用户。我没有得到任何完整的 Calendar API 示例。所以,我尝试了 Drive API 文档sample,这个示例似乎工作正常,也使用其他域用户
我使用日历 API 编写了以下示例。
<?php
require_once realpath(dirname(__FILE__).'/google-api-php-client-master/src/Google/autoload.php');
require_once realpath(dirname(__FILE__).'/google-api-php-client-master/src/Google/Service/Calendar.php');
require_once realpath(dirname(__FILE__).'/google-api-php-client-master/src/Google/Service/Oauth2.php');
use google\appengine\api\users\User;
use google\appengine\api\users\UserService;
$user = UserService::getCurrentUser();
$userEmail=$user->getEmail();
$client_email = '34234242424-qssjf8kg1kk42dnjdvd2ndrk7rou44@developer.gserviceaccount.com';
$private_key = file_get_contents('key.p12');
$scopes = array('https://www.googleapis.com/auth/calendar');
$credentials = new Google_Auth_AssertionCredentials(
$client_email,
$scopes,
$private_key
);
$credentials->sub = $userEmail;
$client = new Google_Client();
$client->setAssertionCredentials($credentials);
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion();
}
$service =new Google_Service_Calendar($client);
$event = new Google_Service_Calendar_Event();
$start = new Google_Service_Calendar_EventDateTime();
$start->setDateTime('2015-09-26T10:00:00.000-07:00');
$event->setStart($start);
$end = new Google_Service_Calendar_EventDateTime();
$end->setDateTime('2015-09-26T10:00:00.000-07:00');
$event->setEnd($end);
$createdEvent = $service->events->insert('abc@group.calendar.google.com', $event);
当我检查这封电子邮件时,它运行良好,我得到了正确的服务帐户凭据。 但是当我使用不同的电子邮件 ID 时,我得到了以下错误
PHP Fatal error: Uncaught exception 'Google_Auth_Exception' with message 'Error refreshing the OAuth2 token, message: '{ "error" : "unauthorized_client", "error_description" : "Unauthorized client or scope in request." }'' in /base/data/home/apps/s~production/1.3874/google-api-php-client-master/src/Google/Auth/OAuth2.php:363 Stack trace: #0 /base/data/home/apps/s~production/1.387/google-api-php-client-master/src/Google/Auth/OAuth2.php(314): Google_Auth_OAuth2->refreshTokenRequest(Array) #1 /base/data/home/apps/s~ei-html-production/1.3874/final.php(34): Google_Auth_OAuth2->refreshTokenWithAssertion() #2 {main} thrown in /base/data/home/apps/s~production/1.38742/google-api-php-client-master/src/Google/Auth/OAuth2.php on line 363
请帮助我做错了什么。为什么会出现问题,当我使用差异电子邮件 ID 时,我将创建 cal 事件的最终用户可能是任何基于 GMAIL 或 Google 的域 ID。
所以,请至少提供一个示例部分...
参考链接:
How do I Insert Google Calendar Event using Google Api 3 for any user in the domain?
【问题讨论】:
标签: php google-app-engine google-calendar-api google-api-php-client service-accounts