susilolabs

Google API Calendar Service Account Example

Sep 28th, 2016
273
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.26 KB | None | 0 0
  1. <?php
  2. ...
  3.     private function getMinMaxOfDay($min=true) {
  4.         $date  = new DateTime(date('c'));
  5.         $today = date('j');
  6.  
  7.         if($min) {
  8.             $today -= 1;
  9.             $date->modify("-$today day");
  10.  
  11.         }else {
  12.             $maxDay = date('t') - $today;
  13.             $date->modify("$maxDay day");
  14.         }
  15.  
  16.         return $date->format('c');
  17.     }
  18.  
  19.     public function actionDemo() {
  20.         $client = new \Google_Client();
  21.         $client->setApplicationName('Demo Calendar Service');
  22.  
  23.         $clientEmail = 'calendar@demo.iam.gserviceaccount.com';
  24.         $privateKey = join('/', [Yii::getPathOfAlias('application.config'),
  25.             'Demo123.json']);
  26.         $scopes = 'https://www.googleapis.com/auth/calendar.readonly';
  27.         putenv('GOOGLE_APPLICATION_CREDENTIALS=' . $privateKey);
  28.  
  29.         $client->addScope(\Google_Service_Calendar::CALENDAR_READONLY);
  30.         $client->useApplicationDefaultCredentials();
  31.         $client->setSubject($clientEmail);
  32.         $client->setAuthConfig($privateKey);
  33.        
  34.         $service = new Google_Service_Calendar($client);
  35.         $optParams = [
  36.             'maxResults'   => 10,
  37.             'orderBy'      => 'startTime',
  38.             'singleEvents' => true,
  39.             'timeMax'      => $this->getMinMaxOfDay(false),
  40.             'timeMin'      => $this->getMinMaxOfDay(),
  41.         ];
  42.         $calendar = $service->events->listEvents('primary', $optParams);
  43.         print_r($calendar->getItems());
  44.     }
  45. ...
Add Comment
Please, Sign In to add comment