谷歌api日历PHP

时间:2014-12-11 19:07:37

标签: php api calendar

我知道有很多类似的问题,但我很难理解。我已成功使用php google库for 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似乎有点矫枉过正。我当然可能误解了 - 任何建议的帮助对我来说都是最有帮助的。

1 个答案:

答案 0 :(得分:0)

好的 - 如果有其他人搜索到这个问题的答案,我想我会发布我的解决方案。我有点傻。如果要以这种方式验证应用程序以修改日历,则需要在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();?>