さぁ、始まりました!使ってみたシリーーーズ
今回はGoogle Calendar APIで予定(日本の休日)を取得してみる。
準備
- Google Cloud Platformにアカウントを作ってログインする。
- プロジェクトを作成する。
- [APIとサービス]-[ライブラリ]で
Google Calendar API
を選択して[有効にする]をクリックする。 - 認証情報を作成で
サービス アカウント
を選択する。 - キーを作成でキータイプJSONを選択して[作成]をクリックする。
サービスアカウントのJSONファイルがダウンロードされる。
Google Client Libraryをインストール
composerがインストールされていない場合はインストールする。
$ brew install composer
プロジェクトフォルダを作成してGoogle Client Libraryをインストールする。
$ mkdir myproject; cd myproject
$ composer require google/apiclient:^2.0
vendor
フォルダとcomposer.json
、composer.lock
ファイルが作成される。
実装
日本の祝日カレンダーを取得する。
require_once 'vendor/autoload.php';
$timeMin = new DateTime('-1 month');
$timeMax = new DateTime('+1 month');
$credentials = 'credentials.json'; # サービスアカウントのJSONファイル
$calendarId = 'ja.japanese#holiday@group.v.calendar.google.com';
$client = new Google_Client();
$client->setApplicationName('My App');
$client->setScopes(Google_Service_Calendar::CALENDAR_READONLY);
$client->setAuthConfig($credentials);
$service = new Google_Service_Calendar($client);
$optParams = array(
'orderBy' => 'startTime'
, 'singleEvents' => true
, 'timeMin' => $timeMin->format('c')
, 'timeMax' => $timeMax->format('c')
);
$events = $service->events->listEvents($calendarId, $optParams);
foreach ($events->getItems() as $event) {
echo $event->start->date . ': ' . $event->getSummary();
}