在Google日历中插入活动

时间:2016-12-29 06:50:20

标签: php events insert google-calendar-api google-api-php-client

我正在尝试使用日历ID在我的日历中插入一个事件。

我刚从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' => 'lpage@example.com'),
    array('email' => 'sbrin@example.com'),
  ),
  'reminders' => array(
    'useDefault' => FALSE,
    'overrides' => array(
      array('method' => 'email', 'minutes' => 24 * 60),
      array('method' => 'popup', 'minutes' => 10),
    ),
  ),
));

$calendarId = 'xxxxxxxxxxxxxx@group.calendar.google.com';

$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 个答案:

答案 0 :(得分: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));

    }

}

?>

请注意,对于日历ID 值,我使用的是&#39; ,因为它将是经过身份验证的用户的主日历。有关详细信息,请参阅文档here。我希望这有帮助!

答案 1 :(得分:0)

检查您所包含的所有文件,这可能会导致此错误。您也可以从PHP Quickstart开始:

  

完成描述一个简单的PHP命令行应用程序的步骤,该应用程序向Google Calendar API发出请求。

以下是他们的示例代码:

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

这显示了要包含的所需文件。希望这会有所帮助。