Google Calendar APIにを利用して簡易的に予定を取得
公式サイトのPHP Quickstartを元にGoogle Calendar APIとPHPで予定を取得します。
GitHubのリポジトリにコードをプッシュしているので参考にしてみてください。(vendorディレクトリや認証ファイルの中身はプッシュしていません)ただし、公式サイトのコードは定期的にアップデートされるので、基本的には公式サイトのコードを参考にしてください。
前提条件
- コマンドラインインターフェイス(CLI)とJSON拡張機能がインストールされたPHP5.4以降
- Composerがインストールされている
- Googleカレンダーが有効になっているGoogleアカウント
「ステップ1」 Google Calendar APIをオン
- 公式サイトのステップ1のEnable the Google Calendar APIボタンを押下
- Quickstartを選択し、NEXTボタンを押下
- Desktop appを選択し、CREATEボタンを押下
- Download client configurationボタンを押下し、credentials.json(認証ファイル)をダウンロード
「ステップ2」 Googleクライアントライブラリをインストール
ターミナルでcalendarディレクトリを作成
$ mkdir calendar
$ cd calendar
calendarディレクトリ直下でライブラリをインストール
$ composer require google/apiclient:^2.0
1.でダウンロードしたcredentials.jsonをcalendarディレクトリ直下に配置
「ステップ3」 コードを記述
calendarディレクトリ直下でquickstart.phpを作成
$ touch quickstart.php
下記のコードをquickstart.phpに記述
calendar/quickstart.php
<?php
require __DIR__ . '/vendor/autoload.php';
if (php_sapi_name() != 'cli') {
throw new Exception('This application must be run on the command line.');
}
/**
* Returns an authorized API client.
* @return Google_Client the authorized client object
*/
function getClient()
{
$client = new Google_Client();
$client->setApplicationName('Google Calendar API PHP Quickstart');
$client->setScopes(Google_Service_Calendar::CALENDAR_READONLY);
$client->setAuthConfig('credentials.json');
$client->setAccessType('offline');
$client->setPrompt('select_account consent');
// Load previously authorized token from a file, if it exists.
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
$tokenPath = 'token.json';
if (file_exists($tokenPath)) {
$accessToken = json_decode(file_get_contents($tokenPath), true);
$client->setAccessToken($accessToken);
}
// If there is no previous token or it's expired.
if ($client->isAccessTokenExpired()) {
// Refresh the token if possible, else fetch a new one.
if ($client->getRefreshToken()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
} else {
// Request authorization from the user.
$authUrl = $client->createAuthUrl();
printf("Open the following link in your browser:\n%s\n", $authUrl);
print 'Enter verification code: ';
$authCode = trim(fgets(STDIN));
// Exchange authorization code for an access token.
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
$client->setAccessToken($accessToken);
// Check to see if there was an error.
if (array_key_exists('error', $accessToken)) {
throw new Exception(join(', ', $accessToken));
}
}
// Save the token to a file.
if (!file_exists(dirname($tokenPath))) {
mkdir(dirname($tokenPath), 0700, true);
}
file_put_contents($tokenPath, json_encode($client->getAccessToken()));
}
return $client;
}
// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Calendar($client);
// Print the next 10 events on the user's calendar.
$calendarId = 'primary';
$optParams = array(
'maxResults' => 10,
'orderBy' => 'startTime',
'singleEvents' => true,
'timeMin' => date('c'),
);
$results = $service->events->listEvents($calendarId, $optParams);
$events = $results->getItems();
if (empty($events)) {
print "No upcoming events found.\n";
} else {
print "Upcoming events:\n";
foreach ($events as $event) {
$start = $event->start->dateTime;
if (empty($start)) {
$start = $event->start->date;
}
printf("%s (%s)\n", $event->getSummary(), $start);
}
}
「ステップ4」 コードを実行
ターミナルでcalendarディレクトリで下記のファイルを実行
$ php quickstart.php
- ターミナルでURLが返却されるので、ブラウザにコピペして実行
- アカウントを選択し、許可ボタンを押下
- 認証コードがブラウザに表示される
- 認証コードをターミナルの
code
の部分に入力し実行 - ターミナルで10件の予定を取得