【问题标题】:google api calendar php谷歌 api 日历 php
【发布时间】:2014-12-11 19:07:36
【问题描述】:

我知道有人问过很多类似的问题,但我很难理解。我已成功使用 v3 的 php google 库与日历功能进行交互。我的代码是:

<?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 控制台中设置一个服务帐户。然后,您需要授予对发送给此帐户的电子邮件的日历访问权限。此代码有效:

标签: php api calendar


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-19
    • 1970-01-01
    • 2016-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多