2014-04-17 2 views
0

페이지를 새로 고침 할 때 Google 캘린더 일정을 만들려고합니다. 여기에 내 코드입니다 :로그인하지 않고 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('[email protected]', $event); 
} else { 
$authUrl = $client->createAuthUrl(); 
print "<a class='login' href='$authUrl'>Connect Me!</a>"; 
} 

... 그리고 여기에 config 파일입니다 :

<?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/[email protected]/events : (404) 찾을 수 없습니다 ' 기본적으로 그 ID와 함께 달력을 찾을 수 없다는 말입니다. 로그인하지 않은 브라우저에서이 코드를 실행하려고하면 'else'절이 실행되고 사용자에게 로그인하라는 메시지가 표시됩니다. 캘린더 일정을 만들고 Gmail 계정에 로그인하지 않고 만들 수 있습니까? 캘린더 일정? 감사.

답변

1

먼저 나중에 나중에 사용할 수 있도록 다시 채우기 토큰을 저장해야합니다.

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

당신이 다음이를 사용하면 추가/수정/삭제 권한이 필요한 다른 구글 캘린더 방법 다시 로그인해야합니다.