【问题标题】:Insert event in google calender在谷歌日历中插入事件
【发布时间】:2016-12-29 06:50:20
【问题描述】:

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

我刚刚从here复制了一个代码sn-p

并从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

如何解决这个问题。或者我做错了什么。请帮忙。

【问题讨论】:

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


    【解决方案1】:

    我猜你问题的根源是你使用了太多的includes。仅使用 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));
    
        }
    
    }
    
    ?>
    

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

    【讨论】:

      【解决方案2】:

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

      完成向 Google Calendar 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);
        }
      }
      

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

      【讨论】:

        猜你喜欢
        • 2012-10-10
        • 2018-09-13
        • 1970-01-01
        • 1970-01-01
        • 2012-08-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-05-25
        相关资源
        最近更新 更多