PHP使用service account和google drive api 访问google drive 的范例
安装库
composer require google/apiclient
范例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); //サビースアカウントキーの設定 $client->setAuthConfig('borg-230303-6fb36bebedae.json'); // delegate domain-wide authority to a service accoun、When you prepare to make authorized API calls, you specify the user to impersonate. //サビースアカウントが偽装するユーザのメールアドレス //借用或者模拟G suite中用户对google drive的访问权限 $client->setSubject("w_gao@cm-group.co.jp"); return $client; } //googleドライブで父フォルダーのIDでフォルダー中のファイル情報を取得 function getFilesInParent($service, $parentId, $containName=""){ $q = "'".$parentId."' in parents "; if (!empty($containName)) { $q .= " and name contains '".$containName."'"; } $optParams = array( 'fields' => 'nextPageToken, files(id, name, parents)' ,'includeItemsFromAllDrives' => true ,'corpora' => 'drive' ,"supportsAllDrives"=>true ,"driveId" => "0AOYSqx2jksBQUk9PVA" ,'q' => $q ); $results = $service->files->listFiles($optParams); return $results->getFiles(); } //ファイルリストの出力 function printfiels($files) { if (count($files) == 0) { print "No files found.\n"; } else { print "Files:\n"; foreach ($files as $file) { printf("%s %s \n", $file->getName(), $file->getId); } } } // Get the API client and construct the service object. $client = getClient(); $service = new Google_Service_Drive($client); $files = getFilesInParent($service, "1vmhxCGWnLJTQ-ufMdZ7aja4Am5S_nDYy"); printfiels($files);
使用命令行进行测试
php quickstart.php
参考资料:
认证参考:
Using OAuth 2.0 to Access Google APIs
https://developers.google.com/identity/protocols/oauth2/service-account#delegatingauthority
google drive api的使用参考:
https://developers.google.com/drive/api/v3/reference/files/list
其他使用service account访问google drive 的范例
https://qiita.com/yu9penguin/items/47d5fb502b8ec2e60013
//此范例的共有方式应该是直接将drive文件共有给service account账户
而上面的范例的共有方式是通过G Suite,并借用G Suite内某个用户对google drive的访问权限