2016-12-29 6 views
2

캘린더 ID를 사용하여 캘린더에 일정을 삽입하려고합니다. Google 캘린더에 이벤트 삽입

난 그냥 here

에서 코드를 복사하여 여기에

here에서 SDK를 다운로드 내 코드

<?php 
// Refer to the PHP quickstart on how to setup the environment: 
// https://developers.google.com/google-apps/calendar/quickstart/php 
// Change the scope to Google_Service_Calendar::CALENDAR and delete any stored 
// credentials. 

include('google-api-php-client-2.0.3/vendor/autoload.php'); 
include('google-api-php-client-2.0.3/src/Google/Client.php'); 
include('google-api-php-client-2.0.3/src/Google/Service/Resource.php'); 


include('google-api-php-client-2.0.3/google-api-php-client-2.0.3/vendor/google/apiclient-services/src/Google/Service/Calendar.php'); 
include('google-api-php-client-2.0.3/google-api-php-client-2.0.3/src/Google/Service.php'); 

$event = new Google_Service_Calendar_Event(array(
    'summary' => 'Google I/O 2015', 
    'location' => '800 Howard St., San Francisco, CA 94103', 
    'description' => 'A chance to hear more about Google\'s developer products.', 
    'start' => array(
    'dateTime' => '2015-05-28T09:00:00-07:00', 
    'timeZone' => 'America/Los_Angeles', 
), 
    'end' => array(
    'dateTime' => '2015-05-28T17:00:00-07:00', 
    'timeZone' => 'America/Los_Angeles', 
), 
    'recurrence' => array(
    'RRULE:FREQ=DAILY;COUNT=2' 
), 
    'attendees' => array(
    array('email' => '[email protected]'), 
    array('email' => '[email protected]'), 
), 
    'reminders' => array(
    'useDefault' => FALSE, 
    'overrides' => array(
     array('method' => 'email', 'minutes' => 24 * 60), 
     array('method' => 'popup', 'minutes' => 10), 
    ), 
), 
)); 

$calendarId = 'xxxx[email protected]'; 

$client = new Google_Client(); 

    $client->setApplicationName("schedular app"); 
    $client->setClientId('xxxxx.apps.googleusercontent.com'); 
    $client->setClientSecret('xxxxxxxxxxxxx'); 


$service = new Google_Service_Calendar_Events_Resource($client,$event,'',''); 
$events = $service->insert($calendarId, $event); 
printf('Event created: %s\n', $event->htmlLink); 



?> 

하지만 나는

Fatal error: Cannot declare class Google_Service, because the name is already in use in D:\xampp\htdocs\gmt\google-api-php-client-2.0.3\src\Google\Service.php on line 18 

어떻게 같은 오류를 얻고있다 이것을 해결하기 위해. 또는 내가 뭘 잘못하고 있는지. 도와주세요.

답변

2

내 생각에 문제의 근원은 이 너무 많이 포함되어 있습니다. include('google-api-php-client-2.0.3/vendor/autoload.php'); 만 사용하고 나머지는 삭제하십시오. 난 당신의 코드가 구조화되는 방식은 이벤트를 생성하기에 충분해야한다고 생각하지만, 내가 그 일을 선호하는 방법은이 방법입니다

<?php 

session_start(); 

//INCLUDE PHP CLIENT LIBRARY 
require_once "google-api-php-client-2.0.3/vendor/autoload.php"; 

$client = new Google_Client(); 
$client->setAuthConfig("client_creds.json"); 
$client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/index.php'); 
$client->addScope("https://www.googleapis.com/auth/calendar"); 

if (isset($_SESSION['access_token']) && $_SESSION['access_token']) { 

    $client->setAccessToken($_SESSION['access_token']); 

    $cal = new Google_Service_Calendar($client); 

    $event = new Google_Service_Calendar_Event(array(
     'summary' => 'Event One', 
     'location' => 'Some Location', 
     'description' => 'Google API Test Event', 
     'start' => array(
     'dateTime' => '2016-11-14T10:00:00-07:00' 
    ), 
     'end' => array(
     'dateTime' => '2016-11-14T10:25:00-07:00' 
    ), 
     'reminders' => array(
     'useDefault' => FALSE, 
     'overrides' => array(
      array('method' => 'email', 'minutes' => 24 * 60), 
      array('method' => 'popup', 'minutes' => 10), 
     ), 
    ), 
    )); 

    $calendarId = 'primary'; 
    $event = $cal->events->insert($calendarId, $event); 
    printf('Event created: %s\n', $event->htmlLink); 

} else { 

    if (!isset($_GET['code'])) {  

      $auth_url = $client->createAuthUrl(); 
      header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL)); 

    } else { 

     $client->authenticate($_GET['code']); 
     $_SESSION['access_token'] = $client->getAccessToken(); 

     $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/index.php'; 
     header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL)); 

    } 

} 

?> 

내가 '을 사용하고있는 달력 아이디 값에 대한 유의하시기 바랍니다 기본 '이 인증 된 사용자의 기본 일정이기 때문입니다. 자세한 내용은 here 문서를 참조하십시오. 이게 도움이 되길 바란다!

0

포함 된 파일을 모두 확인하십시오.이 오류가 발생할 수 있습니다. 또한 당신은 PHP Quickstart 시작 할 수 있습니다 :

를 완료 단계는 구글 캘린더 API에 요청을 만드는 간단한 PHP 명령 줄 응용 프로그램을 설명했다.

<?php 
require_once __DIR__ . '/vendor/autoload.php'; 


define('APPLICATION_NAME', 'Google Calendar API PHP Quickstart'); 
define('CREDENTIALS_PATH', '~/.credentials/calendar-php-quickstart.json'); 
define('CLIENT_SECRET_PATH', __DIR__ . '/client_secret.json'); 
// If modifying these scopes, delete your previously saved credentials 
// at ~/.credentials/calendar-php-quickstart.json 
define('SCOPES', implode(' ', array(
    Google_Service_Calendar::CALENDAR_READONLY) 
)); 

if (php_sapi_name() != 'cli') { 
    throw new Exception('This application must be run on the command line.'); 
} 

/** 
* Returns an authorized API client. 
* @return Google_Client the authorized client object 
*/ 
function getClient() { 
    $client = new Google_Client(); 
    $client->setApplicationName(APPLICATION_NAME); 
    $client->setScopes(SCOPES); 
    $client->setAuthConfig(CLIENT_SECRET_PATH); 
    $client->setAccessType('offline'); 

    // Load previously authorized credentials from a file. 
    $credentialsPath = expandHomeDirectory(CREDENTIALS_PATH); 
    if (file_exists($credentialsPath)) { 
    $accessToken = json_decode(file_get_contents($credentialsPath), true); 
    } else { 
    // Request authorization from the user. 
    $authUrl = $client->createAuthUrl(); 
    printf("Open the following link in your browser:\n%s\n", $authUrl); 
    print 'Enter verification code: '; 
    $authCode = trim(fgets(STDIN)); 

    // Exchange authorization code for an access token. 
    $accessToken = $client->fetchAccessTokenWithAuthCode($authCode); 

    // Store the credentials to disk. 
    if(!file_exists(dirname($credentialsPath))) { 
     mkdir(dirname($credentialsPath), 0700, true); 
    } 
    file_put_contents($credentialsPath, json_encode($accessToken)); 
    printf("Credentials saved to %s\n", $credentialsPath); 
    } 
    $client->setAccessToken($accessToken); 

    // Refresh the token if it's expired. 
    if ($client->isAccessTokenExpired()) { 
    $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken()); 
    file_put_contents($credentialsPath, json_encode($client->getAccessToken())); 
    } 
    return $client; 
} 

/** 
* Expands the home directory alias '~' to the full path. 
* @param string $path the path to expand. 
* @return string the expanded path. 
*/ 
function expandHomeDirectory($path) { 
    $homeDirectory = getenv('HOME'); 
    if (empty($homeDirectory)) { 
    $homeDirectory = getenv('HOMEDRIVE') . getenv('HOMEPATH'); 
    } 
    return str_replace('~', realpath($homeDirectory), $path); 
} 

// Get the API client and construct the service object. 
$client = getClient(); 
$service = new Google_Service_Calendar($client); 

// Print the next 10 events on the user's calendar. 
$calendarId = 'primary'; 
$optParams = array(
    'maxResults' => 10, 
    'orderBy' => 'startTime', 
    'singleEvents' => TRUE, 
    'timeMin' => date('c'), 
); 
$results = $service->events->listEvents($calendarId, $optParams); 

if (count($results->getItems()) == 0) { 
    print "No upcoming events found.\n"; 
} else { 
    print "Upcoming events:\n"; 
    foreach ($results->getItems() as $event) { 
    $start = $event->start->dateTime; 
    if (empty($start)) { 
     $start = $event->start->date; 
    } 
    printf("%s (%s)\n", $event->getSummary(), $start); 
    } 
} 

이 포함되어야 할 필요한 파일이 무엇인지 보여줍니다

여기에 자신의 샘플 코드입니다. 희망이 도움이됩니다.