我想通了。由于我看不到将服务帐户与API v3一起使用的完整示例,因此我将发布完整的解决方案以供参考。但是,除了实现代码外,还需要做一些事情:
1)您需要转到Google
Developer的控制台,并将您的帐户标记为“服务帐户”。这会将其与Web应用程序区分开。重要的区别在于,添加事件之前不会提示任何人登录其帐户,因为该帐户属于您的应用程序,而不是最终用户。有关更多信息,请参阅从第5页开始的本文。
2)您需要创建一个公钥/私钥对。在开发人员的控制台中,单击“凭据”。在您的服务帐户下,单击“生成新的P12密钥”。您需要将其存储在某个地方。该文件位置
$key_file_location在下面的代码中成为变量字符串。
3)同样,从开发人员的控制台中,您需要启用
CalendarAPI。在您的项目中,您会在最左边看到
APIs。选择它并找到
CalendarAPI。单击它,接受服务条款,并确认它现在显示在
EnabledAPIs状态为
On
4)在您要向其添加事件的Google日历中,在“设置”下,单击“日历设置”,然后在顶部的“共享此日历”上。在“人员”字段中的“与特定的人共享”下,粘贴服务帐户凭据中的电子邮件地址。将权限设置更改为“对事件进行更改”。不要忘记保存更改。
然后,在某处实现此代码。
如果有混淆或遗漏之处,请发表评论。祝好运!
<?phpfunction calendarize ($title, $desc, $ev_date, $cal_id) { session_start(); set_include_path( '../google-api-php-client/src/'); require_once 'Google/Client.php'; require_once 'Google/Service/Calendar.php'; //obviously, insert your own credentials from the service account in the Google Developer's console $client_id = '843319906820-xxxxxxxxxxxxxxxxxxxdcqal54p1he6.apps.googleusercontent.com'; $service_account_name = '843319906820-xxxxxxxxxxxxxxxxxxxdcqal54p1he6@developer.gserviceaccount.com'; $key_file_location = '../google-api-php-client/calendar-xxxxxxxxxxxx.p12'; if (!strlen($service_account_name) || !strlen($key_file_location)) echo missingServiceAccountDetailsWarning(); $client = new Google_Client(); $client->setApplicationName("Whatever the name of your app is"); if (isset($_SESSION['service_token'])) { $client->setAccessToken($_SESSION['service_token']); } $key = file_get_contents($key_file_location); $cred = new Google_Auth_AssertionCredentials( $service_account_name, array('https://www.googleapis.com/auth/calendar'), $key ); $client->setAssertionCredentials($cred); if($client->getAuth()->isAccessTokenExpired()) { $client->getAuth()->refreshTokenWithAssertion($cred); } $_SESSION['service_token'] = $client->getAccessToken(); $calendarService = new Google_Service_Calendar($client); $calendarList = $calendarService->calendarList; //Set the Event data $event = new Google_Service_Calendar_Event(); $event->setSummary($title); $event->setDescription($desc); $start = new Google_Service_Calendar_EventDateTime(); $start->setDateTime($ev_date); $event->setStart($start); $end = new Google_Service_Calendar_EventDateTime(); $end->setDateTime($ev_date); $event->setEnd($end); $createdEvent = $calendarService->events->insert($cal_id, $event); echo $createdEvent->getId();}?>一些有用的资源:
服务帐户的Github示例
Google Developers Console,用于在API
v3中插入事件
使用OAuth 2.0访问Google API



