简体   繁体   English

创建未登录的Google日历帐户

[英]Create a Google Calendar account without being signed in

I'm trying to create a Google calendar event when a page is refreshed. 我正在尝试刷新页面时创建Google日历事件。 Here's my code: 这是我的代码:

<?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>";
}

...and here's the config file: ...这是配置文件:

<?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')
)
);

I've got the OAuth stuff commented out because I want to use the developer key instead. 我已经注释掉了OAuth内容,因为我想改用开发人员密钥。 Right now, my code works fine if I'm logged into my browser on the account the calendar is associated with, but if I'm logged on with another gmail account, I get an error: 'Error calling POST https://www.googleapis.com/calendar/v3/calendars/2pnfetf7qtph9i7sq9tcfep1jk@group.calendar.google.com/events : (404) Not Found' Which is basically saying it can't find the calendar with that ID. 现在,如果我使用日历所关联的帐户登录到浏览器,则我的代码可以正常工作,但是如果我使用其他gmail帐户登录,则会收到错误消息:“调用POST https:// www时出错.googleapis.com / calendar / v3 / calendars / 2pnfetf7qtph9i7sq9tcfep1jk @ group.calendar.google.com / events :(404)找不到“,这基本上是说找不到具有该ID的日历。 If I try to run this code in a browser that is not logged in, the 'else' clause runs and asks the user to log in. Is there a way to create a calendar event without being logged in to a gmail account associated with that calendar event? 如果我尝试在未登录的浏览器中运行此代码,则将运行“ else”子句,并要求用户登录。有没有一种方法可以创建日历事件而无需登录到与此帐户相关联的gmail帐户日历活动? Thanks. 谢谢。

First you need to store Refesh token for future use. 首先,您需要存储Refesh令牌以备将来使用。 You can get it by 你可以得到它

$client->setAccessType('offline'); 

in this you will get access token along with refresh token. 在此您将获得访问令牌以及刷新令牌。 Please store refresh token into db. 请将刷新令牌存储到db中。

And then write down code before you perform action as given below: 然后在执行以下操作之前写下代码:

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

If you use this then you need to login again to add/edit/delete or any other google calendar method which required authorization. 如果使用此功能,则需要再次登录以添加/编辑/删除或需要授权的其他任何Google日历方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM