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的访问权限
分类:
google
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
2019-03-18 vagrant 同时设置多个同步目录