Google Calendar是一款流行的在線日歷應用程序,可以使用PHP編寫一些基本的功能,例如獲取和創建日歷事件和日歷,發送提醒等功能,下面我們來介紹一下如何使用PHP與Google Calendar交互。
使用Google API獲取授權
要使用Google Calendar PHP API,你需要先獲取授權,可以通過以下步驟完成:
// 引入Google API庫 include_once 'google-api-php-client/src/Google/autoload.php'; // 創建Google客戶端對象 $client = new Google_Client(); $client->setApplicationName("YOUR_COMPANY_NAME"); $client->setClientId('YOUR_CLIENT_ID'); $client->setClientSecret('YOUR_CLIENT_SECRET'); $client->setRedirectUri('YOUR_REDIRECT_URI'); $client->setAccessType('offline'); $client->setApprovalPrompt('force'); // 通過瀏覽器重定向獲取授權 $authUrl = $client->createAuthUrl(); header('Location:' . $authUrl);
創建日歷
你可以使用以下代碼創建新的日歷:
$calendarService = new Google_Service_Calendar($client); $calendar = new Google_Service_Calendar_Calendar(); $calendar->setSummary('測試日歷'); $calendar->setTimeZone('Asia/Shanghai'); $createdCalendar = $calendarService->calendars->insert($calendar); echo $createdCalendar->getId();
創建事件
你可以使用以下代碼創建新的事件:
$calendarService = new Google_Service_Calendar($client); $event = new Google_Service_Calendar_Event(); $event->setSummary('測試事件'); $event->setDescription('這里是測試事件的描述。'); $start = new Google_Service_Calendar_EventDateTime(); $start->setDateTime('2020-07-01T10:00:00+08:00'); $event->setStart($start); $end = new Google_Service_Calendar_EventDateTime(); $end->setDateTime('2020-07-01T11:00:00+08:00'); $event->setEnd($end); $calendarId = 'primary'; $createdEvent = $calendarService->events->insert($calendarId, $event); echo $createdEvent->getId();
獲取事件列表
你可以使用以下代碼獲取某個日歷的事件列表:
$calendarService = new Google_Service_Calendar($client); $calendarId = 'primary'; $optParams = array( 'maxResults' =>20, 'orderBy' =>'startTime', 'singleEvents' =>true, 'timeMin' =>date('c'), ); $results = $calendarService->events->listEvents($calendarId, $optParams); foreach ($results->getItems() as $event) { echo $event->getSummary() . " (開始時間:" . $event->getStart()->dateTime . ")
"; }
發送提醒
你可以使用以下代碼發送一些提醒信息:
$calendarService = new Google_Service_Calendar($client); $event = $calendarService->events->get('primary', $eventId); $eventDateTime = $event->getStart()->dateTime; $now = new DateTime('now'); $eventDateTime = new DateTime($eventDateTime); $timeDiff = $now->diff($eventDateTime); if ($timeDiff->d == 0 && $timeDiff->h == 1) { $notification = array( 'type' =>'email', 'method' =>'email', 'minutes' =>'60', ); $event->setReminders(array( 'useDefault' =>FALSE, 'overrides' =>array($notification) )); $updatedEvent = $calendarService->events->update('primary', $event->getId(), $event); }
總結
Google Calendar PHP API提供了方便的方法來通過PHP與Google Calendar交互,我們可以創建日歷和事件,獲取事件列表,以及發送提醒等功能。