• Post author:
  • Post category:Tech

公司有很多活動需要更新到行事曆去,隨者越來越多,用手動實在是太不自動化拉,我就開始研究API部分,過程有點繁瑣不過串接API上是簡單的 , 使用PHP語言與Laravel 架構 。

首先要先到 https://console.cloud.google.com/ 要創立一個專案與設定好OAuth 應用程式,產生後就會有Key 跟Secret 後續要用到 。

複製ID 與Secret 貼到下方還有設定好redirectURL ,轉頁的URL與開啟登入頁這個頁面是同一個,下方注意到 access_type 設定為offline 讓這個token 一直都有效,OAuth 做好自動轉回這頁,頁面上就會看到Token了。

   /* Google App Client Id */
        define('CLIENT_ID', 'xxxxx');

        define('CLIENT_SECRET', 'xxxxx');

        define('CLIENT_REDIRECT_URL', 'xxxxx');

        $login_url = 'https://accounts.google.com/o/oauth2/auth?scope=' . urlencode('https://www.googleapis.com/auth/calendar') . '&redirect_uri=' . urlencode(CLIENT_REDIRECT_URL) . '&response_type=code&client_id=' . CLIENT_ID . '&access_type=offline';

        echo "<a href='" . $login_url . "' target='_blank' >Login</a>";

        $code = Input::get('code');

        if (isset($code)) {

            try {

                // Get the access token
                $data = GoogleCalendarApi::GetAccessToken(CLIENT_ID, CLIENT_REDIRECT_URL, CLIENT_SECRET, $code);

        

                echo $data['access_token'];
                exit();
            } catch (Exception $e) {
                echo $e->getMessage();
                exit();
            }
        }

以下是會呼叫到的程式庫

<?php

class GoogleCalendarApi
{
	public static function GetAccessToken($client_id, $redirect_uri, $client_secret, $code) {	
		$url = 'https://accounts.google.com/o/oauth2/token';			
		
		$curlPost = 'client_id=' . $client_id . '&redirect_uri=' . $redirect_uri . '&client_secret=' . $client_secret . '&code='. $code . '&grant_type=authorization_code';
		$ch = curl_init();		
		curl_setopt($ch, CURLOPT_URL, $url);		
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);		
		curl_setopt($ch, CURLOPT_POST, 1);		
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);	
		$data = json_decode(curl_exec($ch), true);
		$http_code = curl_getinfo($ch,CURLINFO_HTTP_CODE);		
		if($http_code != 200) 
			throw new Exception('Error : Failed to receieve access token');
			
		return $data;
	}

	public static function GetUserCalendarTimezone($access_token) {
		$url_settings = 'https://www.googleapis.com/calendar/v3/users/me/settings/timezone';
		
		$ch = curl_init();		
		curl_setopt($ch, CURLOPT_URL, $url_settings);		
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);	
		curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer '. $access_token));	
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);	
		$data = json_decode(curl_exec($ch), true); //echo '<pre>';print_r($data);echo '</pre>';
		$http_code = curl_getinfo($ch,CURLINFO_HTTP_CODE);		
		if($http_code != 200) 
			throw new Exception('Error : Failed to get timezone');

		return $data['value'];
	}

	public static function GetCalendarsList($access_token) {
		$url_parameters = array();

		$url_parameters['fields'] = 'items(id,summary,timeZone)';
		$url_parameters['minAccessRole'] = 'owner';

		$url_calendars = 'https://www.googleapis.com/calendar/v3/users/me/calendarList?'. http_build_query($url_parameters);
		
		$ch = curl_init();		
		curl_setopt($ch, CURLOPT_URL, $url_calendars);		
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);	
		curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer '. $access_token));	
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);	
		$data = json_decode(curl_exec($ch), true); //echo '<pre>';print_r($data);echo '</pre>';
		$http_code = curl_getinfo($ch,CURLINFO_HTTP_CODE);		
		if($http_code != 200) 
			throw new Exception('Error : Failed to get calendars list');

		return $data['items'];
	}

	public static function CreateCalendarEvent($calendar_id,$attendees,$location, $description, $summary, $all_day, $event_time, $event_timezone, $access_token) {
		$url_events = 'https://www.googleapis.com/calendar/v3/calendars/' . $calendar_id . '/events';

		$curlPost = array('summary' => $summary);
		if($all_day == 1) {
			$curlPost['start'] = array('date' => $event_time['event_date']);
			$curlPost['end'] = array('date' => $event_time['event_date']);
		}
		else {
			$curlPost['start'] = array('dateTime' => $event_time['start_time'], 'timeZone' => $event_timezone);
			$curlPost['end'] = array('dateTime' => $event_time['end_time'], 'timeZone' => $event_timezone);
		}

		$curlPost['attendees'] = $attendees;
		$curlPost['location'] = $location;
		$curlPost['description'] = $description;
		$curlPost['sendUpdates'] = "all";


		$ch = curl_init();		
		curl_setopt($ch, CURLOPT_URL, $url_events);		
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);		
		curl_setopt($ch, CURLOPT_POST, 1);		
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer '. $access_token, 'Content-Type: application/json'));	
		curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($curlPost));	
		$data = json_decode(curl_exec($ch), true);
		$http_code = curl_getinfo($ch,CURLINFO_HTTP_CODE);		
		if($http_code != 200) {
			return $data;
			throw new Exception('Error : Failed to create event');
		}
		

		return $data['id'];
	}

	public static function getCalendarEvent($calendar_id, $event_id,  $access_token) {
		$url_events = 'https://www.googleapis.com/calendar/v3/calendars/' . $calendar_id . '/events/'.$event_id;

		$ch = curl_init();		
		curl_setopt($ch, CURLOPT_URL, $url_events);		
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);	
		curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer '. $access_token));	
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);	
		$data = json_decode(curl_exec($ch), true);
		$http_code = curl_getinfo($ch,CURLINFO_HTTP_CODE);		
		if($http_code != 200) {
			return $data;
			throw new Exception('Error : Failed to create event');
		}
		

		return $data;
	}

	public static function updateCalendarEvent($calendar_id,$event_id,$attendees,$location, $description,$summary, $all_day, $event_time, $event_timezone, $access_token) {
		$url_events = 'https://www.googleapis.com/calendar/v3/calendars/' . $calendar_id . '/events/'.$event_id;

		$curlPost = array('summary' => $summary);
		if($all_day == 1) {
			$curlPost['start'] = array('date' => $event_time['event_date']);
			$curlPost['end'] = array('date' => $event_time['event_date']);
		}
		else {
			$curlPost['start'] = array('dateTime' => $event_time['start_time'], 'timeZone' => $event_timezone);
			$curlPost['end'] = array('dateTime' => $event_time['end_time'], 'timeZone' => $event_timezone);
		}

		$curlPost['attendees'] = $attendees;
		$curlPost['location'] = $location;

		$curlPost['description'] = $description;
		$curlPost['sendUpdates'] = "all";

	
		$ch = curl_init();		
		curl_setopt($ch, CURLOPT_URL, $url_events);		
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);		
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");		
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer '. $access_token, 'Content-Type: application/json'));	
		curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($curlPost));	
		$data = json_decode(curl_exec($ch), true);
		$http_code = curl_getinfo($ch,CURLINFO_HTTP_CODE);		
		if($http_code != 200) {
			return $data;
			throw new Exception('Error : Failed to create event');
		}
		

		return $data['id'];
	}


	
}

?>

新增一個事件的做法

    $access_token = "xxxx";

        $calendar_id = "xxxx";

        $summary = "test event from api";
        $event_timezone = "Asia/Taipei";
        $event_time['start_time'] = "2021-07-27T19:00:00+08:00";
        $event_time['end_time'] = "2021-07-27T20:00:00+08:00";
        $all_day = 0;

        $attendees = array('email' => "[email protected]");
        $location = "zoom";
        $description = " ";
        
        $list = GoogleCalendarApi::CreateCalendarEvent($calendar_id,  $attendees, $location, $description , $summary, $all_day, $event_time, $event_timezone, $access_token);

        print_r($list);

其他用法可以參考程式庫,目前沒有刪除功能,有需要的人可以試試自己來寫 。

參考google API說明

https://developers.google.com/calendar/api/guides/overview