【发布时间】:2014-01-09 15:17:50
【问题描述】:
我正在为此苦苦挣扎:我正在尝试使用服务帐户从 PHP 脚本在 Google 日历中创建一个事件。
这是我所做的:
- 创建了一个 Google Cloud 项目
- 启用日历 API
- 创建了一个 OAuth 2.0 服务帐户,其中包含客户端 ID、电子邮件地址和公钥
- 已下载密钥文件并将其保存在我的网站中
- 与在服务帐户中创建的电子邮件地址共享我的日历(具有管理共享权限)
这是我的代码:
<?php
require_once 'google_api_src/Google_Client.php';
require_once 'google_api_src/contrib/Google_CalendarService.php';
const CLIENT_ID = 'xxxxxxxxxxxxx.apps.googleusercontent.com';
const SERVICE_ACCOUNT_NAME = 'xxxxxxxxxxxxx@developer.gserviceaccount.com';
// Make sure you keep your key.p12 file in a secure location, and isn't
// readable by others.
const KEY_FILE = 'google_api_src/xxxxxxxxx-privatekey.p12';
$client = new Google_Client();
$client->setApplicationName("Hall Booking");
session_start();
if (isset($_SESSION['token']))
{
$client->setAccessToken($_SESSION['token']);
}
// Load the key in PKCS 12 format
$key = file_get_contents(KEY_FILE);
$client->setClientId(CLIENT_ID);
$client->setAssertionCredentials(new Google_AssertionCredentials(
SERVICE_ACCOUNT_NAME,
array('https://www.googleapis.com/auth/calendar', "https://www.googleapis.com/auth/calendar.readonly"),
$key));
$service = new Google_CalendarService($client);
//Save token in session
if ($client->getAccessToken())
{
$_SESSION['token'] = $client->getAccessToken();
}
?>
我已尽我所能调试代码,但在调用 SetAssertionCredentials 后令牌始终设置为 null。没有 PHP 错误。
知道出了什么问题,或者如何进一步调试吗? 我是否必须对 api src 文件夹中的 config.php 进行任何更改(到目前为止我还没有)? 应用程序名称重要吗?它是干什么用的?
【问题讨论】:
标签: php api google-calendar-api