LoginSignup
1
4

More than 3 years have passed since last update.

Google Drive APIの設定まとめ

Last updated at Posted at 2020-09-29

Google Drive APIをPHPから使用するために以下を入れたものの、
設定がよくわからなかったのでまとめ。
https://github.com/googleapis/google-api-php-client

やりたかったこと

共有ドライブに設置されたファイルをPHPで取得する

Google Drive APIの設定

APIキー、OAuth、サービスアカウントの3タイプの接続方法があり、
今回はサービスアカウントを使用しての接続をした。

DriveAPI使用許可設定

1.ログインし、以下よりGoogle APIsのページに移動してGoogle Drive APIを検索
https://console.developers.google.com/apis/library
2.Google Drive APIを押下し、有効化する
3.有効化完了

認証ファイル作成

  1. 以下のページに移動する
  2. 新しいプロジェクトを作成
    • プロジェクト名「任意のプロジェクト名」
  3. 作成後、「認証情報」ページに移動し、サービスアカウントの「サービスアカウントの管理」リンクをクリック
  4. ヘッダより「サービスアカウントを作成」
    • 名前:任意の名前
    • 説明:省略可能
    • メール:任意のサービスアカウント名@〜(これをコピーしておく※1)
  5. 次にキーを作成する「鍵を追加」→「新しい鍵を追加」
  6. 「JSON」を選択し、保存ボタンを押す
  7. 生成された鍵を保存する

グループ作成

これはファイルアップロード担当者と、DriveAPIの接続に使用します

  1. 以下に接続
  2. 「グループ」を選択
  3. 「グループを作成」リンクをクリック
  4. 以下情報を入力して保存
    • 名称:任意の名称
    • メール:任意のメールアドレス@ドメイン
    • 説明:省略可能
  5. 「メンバーを追加」で上記※1でコピーしたユーザーを追加する

PHPサンプル

サービスの設定をして、指定したディレクトリのファイルを取得する。

/**
 * Google DriveのAPI認証
 * @return Google_Client the authorized client object
 */
private function getService()
{
    $client = new Google_Client();
    $client->setApplicationName("File Upload ※任意");
    $client->setScopes(Google_Service_Drive::DRIVE_READONLY);
    $client->setAuthConfig('作成した認証ファイルのパス');
    if ($client->isAccessTokenExpired()) {
        $client->refreshTokenWithAssertion();
    }
    return new Google_Service_Drive($client);
}

/**
 * Google Driveからファイルを取得する
 *
 * @return mixed
 */
private function getFiles()
{
    $service = $this->getService();
    // 接続情報を取得
    $optParams = array(
        // ターゲットディレクトリIDを指定する
        'q'                         => "'取得元のディレクトリID' in parents",
        'includeItemsFromAllDrives' => true,
        'supportsAllDrives'         => true,
        /*
         * id:ファイルID
         * name:ファイル名
         * createdTime:ファイル作成日
         * modifiedTime:ファイル編集日
         * lastModifyingUser:最終編集者
         * size:ファイルサイズ
         */
        'fields'                    => 'nextPageToken, files(id,name,createdTime,modifiedTime,lastModifyingUser,size)',
        //'pageSize' => 10,
    );
    return $service->files->listFiles($optParams);
}
1
4
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
1
4