Google API:无人值守的日历阅读.如何登录?

Ser*_*ier 3 php google-calendar-api google-api-php-client

我觉得这个会变得轻而易举.因此我一开始就陷入困境:-(

我创建了一个Google日历,用户可以使用"共享"专用登录信息添加活动.然后我需要在我的服务器上编写一个PHP脚本来读取给定时间范围内的事件.

我认为这里描述的API密钥就足够了.但事实并非如此.

 curl https://www.googleapis.com/calendar/v3/users/me/calendarList?key=mykey
Run Code Online (Sandbox Code Playgroud)

Login required.

所以我读到了OAuth2.0以及我需要用户进行身份验证的方法.问题是我的脚本不是交互式的(虽然硬编码脚本中的登录对我来说不是问题:信息不是生命关键).所以我读到了服务帐户,但它看起来像非用户信息.

问题:如何在不涉及人类的情况下编写脚本以强制执行给定登录?

注意:这个SO问题似乎很有希望,但答案是针对API版本2.0,这似乎已经过时了.

Chi*_*hah 7

您需要做的第一件事是获取访问令牌.这将需要一个人.假设您正在使用Google API PHP客户端,可以使用此脚本(从命令行运行)来完成.

注意:下面的代码段使用已安装应用程序客户端ID.确保在Google API Access控制台中创建此类型的客户端ID.

require_once '../../src/apiClient.php';
defined('STDIN') or define('STDIN', fopen('php://stdin', 'r'));

$client = new apiClient();
// Visit https://code.google.com/apis/console to create your client id and cient secret
$client->setClientId('INSERT_CLIENT_ID');
$client->setClientSecret('INSERT_CLIENT_SECRET');
$client->setRedirectUri('urn:ietf:wg:oauth:2.0:oob');
$client->setScopes(array(
    'https://www.googleapis.com/auth/calendar',
    'https://www.googleapis.com/auth/calendar.readonly',
));

$authUrl = $client->createAuthUrl();

print "Please visit:\n$authUrl\n\n";
print "Please enter the auth code:\n";
$authCode = trim(fgets(STDIN));

$_GET['code'] = $authCode;
$token = $client->authenticate();
var_dump($token);
Run Code Online (Sandbox Code Playgroud)

这将为您提供包含accessToken和refreshToken的json编码字符串.accessToken在1小时后过期,但不要担心.refreshToken将不会过期(除非您卸载应用程序),并且可用于获取新的refreshToken.客户端库负责这部分.

接下来,保存完整的json字符串标记(不仅是安全位置的access_token属性,并确保其他人无法读取.您的应用程序可以调用$client->setAccessToken($token)从安全位置查找$ token的位置(同样,$token是完整的json编码字符串,不限于其access_token属性).

现在,您可以向Calendar API发出经过身份验证的请求!

require_once '../../src/apiClient.php';
require_once '../../src/contrib/apiCalendarService.php';
session_start();

$client = new apiClient();
$client->setApplicationName("Google Calendar PHP Sample Application");
$cal = new apiCalendarService($client);

$client->setAccessToken($tokenFromSafePlace);

$calList = $cal->calendarList->listCalendarList();
print "<h1>Calendar List</h1><pre>" . print_r($calList, true) . "</pre>";
Run Code Online (Sandbox Code Playgroud)