LoginSignup
2

More than 3 years have passed since last update.

Google Calendar APIを使ってみた

Posted at

さぁ、始まりました!使ってみたシリーーーズ
今回はGoogle Calendar APIで予定(日本の休日)を取得してみる。

準備

  • Google Cloud Platformにアカウントを作ってログインする。
  • プロジェクトを作成する。
  • [APIとサービス]-[ライブラリ]でGoogle Calendar APIを選択して[有効にする]をクリックする。
  • 認証情報を作成でサービス アカウントを選択する。
  • キーを作成でキータイプJSONを選択して[作成]をクリックする。

サービスアカウントのJSONファイルがダウンロードされる。

Google Client Libraryをインストール

PHPクイックスタート

composerがインストールされていない場合はインストールする。

$ brew install composer

プロジェクトフォルダを作成してGoogle Client Libraryをインストールする。

$ mkdir myproject; cd myproject
$ composer require google/apiclient:^2.0

vendorフォルダとcomposer.jsoncomposer.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();
}

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2