在未登录的情况下创建Google日历帐户


Create a Google Calendar account without being signed in

我正试图在刷新页面时创建一个谷歌日历事件。这是我的代码:

<?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帐户登录,我会收到一个错误:'调用POST时出错https://www.googleapis.com/calendar/v3/calendars/2pnfetf7qtph9i7sq9tcfep1jk@group.calendar.google.com/events:(404)未找到'这基本上是说它找不到具有该ID的日历。如果我试图在未登录的浏览器中运行此代码,"else"子句会运行并要求用户登录。有没有一种方法可以在不登录与该日历事件相关的gmail帐户的情况下创建日历事件?谢谢

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

$client->setAccessType('offline'); 

在这个过程中,您将获得访问令牌和刷新令牌。请将刷新令牌存储到数据库中。

然后在执行以下操作之前写下代码:

//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']);
}

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