无需登录即可创建Google日历帐户

时间:2014-04-17 23:30:08

标签: php calendar google-calendar-api google-oauth

我正在尝试在刷新页面时创建Google日历活动。这是我的代码:

<?php
require_once '../../src/config.php';

session_start();

$client = new Google_Client();
$client->setApplicationName("Google Calendar PHP Starter Application");

// Visit https://code.google.com/apis/console?api=calendar to generate your
//client id, client secret, and to register your redirect uri.
$client->setClientId('--the client id--');
$client->setClientSecret('--the client secret--');
$client->setRedirectUri('http://acromediainc.acrobuild.com/calendar/google-api-php-client/examples/calendar/simple.php');
//$client->setDeveloperKey('--the developer key--');
$cal = new Google_CalendarService($client);



if (isset($_GET['logout'])) {
  unset($_SESSION['token']);
}

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

if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}

if ($client->getAccessToken()) {
$calList = $cal->calendarList->listCalendarList();
print "<h1>Calendar List</h1><pre>" . print_r($calList, true) . "</pre>";


$_SESSION['token'] = $client->getAccessToken();

$event = new Google_Event();
$event->setSummary('Halloween');
$event->setLocation('The Neighbourhood');
$start = new Google_EventDateTime();
$start->setTimeZone('America/Los_Angeles');
$start->setDateTime('2014-4-30T10:00:00.000');
$event->setStart($start);
$end = new Google_EventDateTime();
$end->setTimeZone('America/Los_Angeles');
$end->setDateTime('2014-4-30T10:20:00.000');
$event->setEnd($end);
$createdEvent = $cal->events->insert('mycalendarid@group.calendar.google.com', $event);
} else {
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Connect Me!</a>";
}

...这里是配置文件:

<?php
/*
 * Copyright 2010 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


require_once "Google_Client.php";
require_once "contrib/Google_CalendarService.php";
require_once 'service/Google_ServiceResource.php';
require_once 'service/Google_Service.php';
require_once 'Google_Client.php';

global $apiConfig;
$apiConfig = array(
// True if objects should be returned by the service classes.
// False if associative arrays should be returned (default behavior).
'use_objects' => false,

// The application_name is included in the User-Agent HTTP header.
'application_name' => 'Calendar',

// OAuth2 Settings, you can get these keys at https://code.google.com/apis/console
//'oauth2_client_id' => 'my client id',
//'oauth2_client_secret' => 'my client secret',
// 'oauth2_redirect_uri' => 'http://acromediainc.acro.dev/calendar/calendar.php',

// The developer key, you get this at https://code.google.com/apis/console
'developer_key' => 'my developer key',

// Site name to show in the Google's OAuth 1 authentication screen.
'site_name' => 'www.example.org',

// Which Authentication, Storage and HTTP IO classes to use.
'authClass'    => 'Google_OAuth2',
'ioClass'      => 'Google_CurlIO',
'cacheClass'   => 'Google_FileCache',

// Don't change these unless you're working against a special development or testing environment.
'basePath' => 'https://www.googleapis.com',

// IO Class dependent configuration, you only have to configure the values
// for the class that was configured as the ioClass above
'ioFileCache_directory'  =>
    (function_exists('sys_get_temp_dir') ?
        sys_get_temp_dir() . '/Google_Client' :
    '/tmp/Google_Client'),

// Definition of service specific values like scopes, oauth token URLs, etc
'services' => array(
  'analytics' => array('scope' => 'https://www.googleapis.com/auth/analytics.readonly'),
  'calendar' => array(
      'scope' => array(
          "https://www.googleapis.com/auth/calendar",
          "https://www.googleapis.com/auth/calendar.readonly",
      )
  ),
  'books' => array('scope' => 'https://www.googleapis.com/auth/books'),
  'latitude' => array(
      'scope' => array(
          'https://www.googleapis.com/auth/latitude.all.best',
          'https://www.googleapis.com/auth/latitude.all.city',
      )
  ),
  'moderator' => array('scope' => 'https://www.googleapis.com/auth/moderator'),
  'oauth2' => array(
      'scope' => array(
          'https://www.googleapis.com/auth/userinfo.profile',
          'https://www.googleapis.com/auth/userinfo.email',
      )
  ),
  'plus' => array('scope' => 'https://www.googleapis.com/auth/plus.login'),
  'siteVerification' => array('scope' => 'https://www.googleapis.com/auth/siteverification'),
  'tasks' => array('scope' => 'https://www.googleapis.com/auth/tasks'),
  'urlshortener' => array('scope' => 'https://www.googleapis.com/auth/urlshortener')
)
);

我已将OAuth内容注释掉,因为我想使用开发人员密钥。现在,如果我在与日历相关联的帐户上登录浏览器,我的代码工作正常,但如果我使用其他Gmail帐户登录,则会收到错误消息: &#39;调用POST https://www.googleapis.com/calendar/v3/calendars/2pnfetf7qtph9i7sq9tcfep1jk@group.calendar.google.com/events时出错:(404)未找到&#39; 这基本上是说它无法找到带有该ID的日历。如果我尝试在未登录的浏览器中运行此代码,那么&#39; else&#39;子句运行并要求用户登录。有没有办法创建日历事件而不登录到与该日历事件关联的Gmail帐户?感谢。

1 个答案:

答案 0 :(得分:1)

首先,您需要存储Refesh令牌以备将来使用。你可以通过

获得它
$client->setAccessType('offline'); 

在此您将获得访问令牌以及刷新令牌。请将刷新令牌存储到db中。

然后在执行操作之前记下代码,如下所示:

//Code start here to get access token

if($client->isAccessTokenExpired()) {

    echo 'Access Token Expired'; // Debug
    $client->refreshToken("Stored Refesh Token"); //Stored Refesh Token is what we save for first req
    $_SESSION['access_token']=$client->getAccessToken();
    $client->setAccessToken($_SESSION['access_token']);
}

如果你使用这个,那么你需要再次登录以添加/编辑/删除或任何其他需要授权的谷歌日历方法。