Laravel 使用 Google Calendar API

2022/08/02閱讀時間約 4 分鐘

1. 使用composer安裝

$ composer require spatie/laravel-google-calendar

2. publish the configuration

$ php artisan vendor:publish --provider="Spatie\GoogleCalendar\GoogleCalendarServiceProvider"
  • 在config資料夾中會多出一個google-calendar.php

3. 取得Google API credentials

(1) 到Google Cloud Platform頁面,選擇專案。
(2) 點選+啟用API和服務
(3) 找到Google Calendar API啟用:
(4) 新增憑證:
(5) 輸入服務帳戶詳細資料: 直接按完成,可省略2, 3步驟。
(6) 建立private金鑰並下載
(7) 在config/google-calendar.php設定金鑰位置

4. 設定Google日曆: 與剛剛新增的服務帳戶共用

5. 往下滑找到整合日曆,將日曆ID設定至config

可在.env file中設定:
GOOGLE_CALENDAR_ID=XXX

後記:
  • 如果是要新增日曆的話: 須將權限調整為「變動活動」才能寫入。

Example:
  • 新增事件
use Spatie\GoogleCalendar\Event;
use Carbon\Carbon;
$event = new Event;
$event->name = 'XXXX活動';
$event->description = '活動描述測試~~';
$event->startDateTime = Carbon::now();
$event->endDateTime = Carbon::now()->addHour();
$event->location = '高雄市XXX';
$event->save();

2024/01/02 後記: 「如何建立多個日曆」
關鍵在於new Event之前,把config中的calendar_id改掉
use Config;
...
private function changeCalendar($name){
        switch ($name) {
            case 'main':
                Config::set('google-calendar.calendar_id', env('GOOGLE_CALENDAR_ID'));
                break;
            case 'wh':
                Config::set('google-calendar.calendar_id', env('WH_GOOGLE_CALENDAR_ID'));
                break;
        }
}
為什麼會看到廣告
20會員
161內容數
留言0
查看全部
發表第一個留言支持創作者!