谷歌 API 日历 PHP


google api calendar php

我知道已经提出了许多类似的问题,但我很难理解。我已经成功地使用 php 谷歌库 v3 与日历函数接口。我拥有的代码是:

<?php 
require_once "google-api-php-client/autoload.php";
session_start();
$client = new Google_Client();
$client->setApplicationName("My app");
$client->setClientId("CI.apps.googleusercontent.com");
$client->SetClientSecret("SECRET");
$client->setRedirectUri("redirect"); 
$client->setDeveloperKey("key");
$client->setScopes(array("https://www.googleapis.com/auth/calendar"));
if (isset($_REQUEST['logout'])) {
  unset($_SESSION['access_token']);
}

if (isset($_GET['code'])) {
  $client->authenticate($_GET['code']);
  $_SESSION['access_token'] = $client->getAccessToken();
  $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
  header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}

if (isset($_SESSION['token'])) {
   $client->setAccessToken($_SESSION['token']);//update token
  }
$service=new Google_Service_Calendar($client);  
...
?>

这工作正常,但我要修改的日历始终相同 - 该应用程序与日历在同一个帐户上注册。有没有办法绕过oauth2身份验证,以便我可以调整我拥有的日历中的条目,而无需使用重定向执行额外的身份验证步骤?我曾经使用 Zend 来做到这一点,直到最近它工作正常,但是更新到 API 的 v3 并像这样使用 oauth2 似乎有点矫枉过正。当然,我可能误解了 - 任何建议的帮助都会对我最有帮助。

好的 - 如果其他人搜索这个问题的答案,我想我会发布我的解决方案。我有点傻。如果要对应用程序进行身份验证以这种方式修改日历,则需要在Google控制台中创建服务帐户 - 而不是Web应用程序。然后,您需要使用服务帐户名称(为服务帐户的客户端 ID 提供的电子邮件地址)以允许脚本修改日历。通过转到要修改的日历的设置来手动执行此操作。然后,此代码将正常工作。

<?php 
session_start();
require_once "google-api-php-client/autoload.php";
$client_id = ''; //Client ID
$service_account_name = ''; //Email Address
$key_file_location = ''; //key.p12
$client = new Google_Client();
$client->setApplicationName("my app");
$service = new Google_Service_Calendar($client);
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();?>