LoginSignup
0

More than 3 years have passed since last update.

Google Calendar APIとPHPで予定を取得

Last updated at Posted at 2021-02-01

Google Calendar APIにを利用して簡易的に予定を取得

公式サイトのPHP Quickstartを元にGoogle Calendar APIとPHPで予定を取得します。

GitHubのリポジトリにコードをプッシュしているので参考にしてみてください。(vendorディレクトリや認証ファイルの中身はプッシュしていません)ただし、公式サイトのコードは定期的にアップデートされるので、基本的には公式サイトのコードを参考にしてください。

前提条件

  1. コマンドラインインターフェイス(CLI)とJSON拡張機能がインストールされたPHP5.4以降
  2. Composerがインストールされている
  3. Googleカレンダーが有効になっているGoogleアカウント

「ステップ1」 Google Calendar APIをオン

  1. 公式サイトのステップ1のEnable the Google Calendar APIボタンを押下
  2. Quickstartを選択し、NEXTボタンを押下
  3. Desktop appを選択し、CREATEボタンを押下
  4. Download client configurationボタンを押下し、credentials.json(認証ファイル)をダウンロード

スクリーンショット 2021-02-01 17.04.26.png

スクリーンショット 2021-02-01 17.04.52.png

スクリーンショット 2021-02-01 17.06.32.png

「ステップ2」 Googleクライアントライブラリをインストール

ターミナルでcalendarディレクトリを作成

$ mkdir calendar   
$ cd calendar

calendarディレクトリ直下でライブラリをインストール

$ composer require google/apiclient:^2.0

1.でダウンロードしたcredentials.jsonをcalendarディレクトリ直下に配置

スクリーンショット 2021-02-01 17.16.06.png

「ステップ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
  1. ターミナルでURLが返却されるので、ブラウザにコピペして実行
  2. アカウントを選択し、許可ボタンを押下
  3. 認証コードがブラウザに表示される
  4. 認証コードをターミナルのcodeの部分に入力し実行
  5. ターミナルで10件の予定を取得

スクリーンショット 2021-02-01 18.52.16.png

スクリーンショット 2021-02-01 18.52.47.png

スクリーンショット 2021-02-01 18.53.01.png

参考記事

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
0