LoginSignup
3
1

More than 3 years have passed since last update.

PHP Quickstartを使用したGoogleDriveAPIの導入手順

Posted at

GoogleDriveAPIを使用することがあったので備忘録

Quickstartを使用して接続の設定

Google Client Libraryのインストール

  • 下記をコマンドラインで入力
composer require google/apiclient:^2.0

認証情報をダウンロード

※すでにOAuth 2.0 クライアントの設定を済ませている場合
(未設定の場合は先にOAuth 2.0 クライアントの設定を行う)

  • Google Cloudプラットフォームから「認証情報」を押下し、認証情報画面を開く
  • OAuth 2.0 クライアント ID 一覧の中から、作成したIDの右端のダウンロードボタンを押下し、ファイルをダウンロードする

サンプルプログラムの作成

PHP Quickstart | Google Drive API | Google Developers
https://developers.google.com/drive/api/v3/quickstart/php

  • Google Drive API のドキュメント内から、PHP Quickstart のページを開く
  • Step 3: Set up the sample に記載されている quickstart.php をコピーする
  • OAuth 同意画面で設定したアプリケーション名をsetApplicationName()に指定、ダウンロードした認証情報のパスをsetAuthConfig()に指定する
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 Drive API PHP Quickstart'); // 設定したアプリケーション名を指定
    $client->setScopes(Google_Service_Drive::DRIVE_METADATA_READONLY);
    $client->setAuthConfig('credentials.json'); // ここに取得した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);
    }

サンプルプログラムの実行

  • 下記をコマンドラインから実行
php quickstart.php

接続の同意

  • サンプルプログラム実行後、URLが表示されるのでコピーし、ブラウザからアクセスする
  • アクセスすると、OAuth 2.0の同意画面が表示され、画面に従って許可を行う
    • アクセスし、「このアプリは確認されていません。」と表示された場合は、左下の「詳細」から「〇〇(安全ではないページ)に移動」から移動する
  • 許可を行い、「このコードをコピーし、アプリケーションに切り替えて貼り付けてください。」と書かれた下のコードをコピーする
  • コマンドライン上のEnter verification code: に貼り付け実行する
[hoge@hogehoge hoge]$ php quickstart.php
Open the following link in your browser:
https://accounts.google.com/o/oauth2/auth?response_type........
Enter verification code: 
3
1
0

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
3
1