iT邦幫忙

2021 iThome 鐵人賽

DAY 23
0
Software Development

Laravel 新手初見 API系列 第 23

Day23-介接 API(一)Google Calendar(I)啟用 API 與 Events——Create

大家好~
接著一起來介接 API 吧!
今天先從 Google Calendar API 開始~


上圖擷取自 Google Calendar API 的官方文件
官方將我們能使用的資源分成八個類型,
該篇主要會以使用 Events 的 CRUD 為主,
其他資源的使用,
不會介紹到喔~

前言

Composer

使用 Composer 下載 google-api-php-client

composer require google/apiclient:^2.0

據官方表示,
該 Repo 內有超過200個的 Google 服務,
如果想清除其他不會用到的部分,
可以藉由修改 composer.json 來保留

{
    "require": {
        "google/apiclient": "^2.11"
    },
    "scripts": {
        "pre-autoload-dump": "Google\\Task\\Composer::cleanup"
    },
    "extra": {
        "google/apiclient-services": [
            "Calendar",
            "Sheets"
        ]
    }
}

extra 內放你要保留的服務。

rm -r vendor/google/apiclient-services

刪除 apiclient-services 的資料夾,

composer update

再用 composer update 重新下載,
這樣就會只保留在 extra 內指定的那些服務囉。

專案建立與啟用 API

在 GCP 上新增專案。

建立完專案後,
啟用 Google Calendar API。

之後會看到如下圖之提醒。

然後點擊同列右側的建立憑證

建立憑證

下一步

建立服務帳戶#1

建立服務帳戶#2

建立金鑰

選擇建立 JSON 類型的金鑰。

專案的新增與金鑰建立差不多就是這樣的流程,
基本上只要跟著網站給的流程走就能完成囉!
也可以參考下面這篇官方文件:
Create a project and enable the API

新增日曆

在 Google Calendar 頁面新增一個日曆。

ironman2021 這個日曆選擇設定和共用

將剛剛建立的服務帳戶加進共用日曆。

等等會用到的 日曆ID 也在這個頁面喔~

Google Calendar Events 實作篇

金鑰放專案內的話,
記得要加進 .gitignore 喔~
另外下面範例是把 日曆ID金鑰位置 加到 .env

先實例 Client 和 Calendar 吧~

use Google\Client;
use Google\Service\Calendar;
use Google\Service\Calendar\Event;
use Google\Service\Calendar\EventDateTime;
protected $client;
protected $googleCalendar;
protected $calendarId;
    
public function __construct()
{
    $this->client = new Client();
    $this->client->setAuthConfig(env('CLIENT_CREDENTIALS_PATH'));
    $this->client->addScope(Calendar::CALENDAR_EVENTS);
    $this->googleCalendar = new Calendar($this->client);
    $this->calendarId = env('GOOGLE_CALENDAR_ID');
}

Google Calendar Events-Create

public function insert(Request $request)
{
    $calendarEvent = new Event();

    $calendarEvent->setSummary($request->summary);

    $calendarEvent->setDescription($request->description);

    $startTime = new EventDateTime();
    $startTime->setDateTime($request->startTime);

    $endTime = new EventDateTime();
    $endTime->setDateTime($request->endTime);

    $calendarEvent->setStart($startTime);

    $calendarEvent->setEnd($endTime);

    $response = $this->googleCalendar->events->insert($this->calendarId, $calendarEvent);

    return $response->getHtmlLink();
}

event 在成功建立後會返回一個 Events resource,
另外 DateTim 的時間格式要用 RFC3339 喔~

成果預覽:

用 Postman 測試一下。

成功~

那麼明天再來繼續 Events 的 Read、Update、Delete 吧~
大家明天見!
若文章有任何問題,
還請大家不吝賜教!


上一篇
Day22-部署篇(四)Domain name、TLS
下一篇
Day24-介接 API(二)Google Calendar(II)Events——Read、Update、Delete
系列文
Laravel 新手初見 API30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言