从google drive 下载文件范例
テストから見ると、トークンの有効期間切れでも、トークンファイルがあれば、自動的に新しいアクセストークンを取得できます。(トークンファイルの中ではリフレッシュトークンがあります。)
それで、トークンの有効期間切れで処理が動かない、ということが発生しないと思います。
トークンファイルのデータ:
{ "access_token": "ya29.a0AfH6SMBuzys-jdPhjP7imCWzuGlivXqVepyA8TI8sXSdiF7DYcCVtpeSwkyaXe9xCXONGxFukOCDskUj3-rzJAAMEWjBE3p3KxPoqCigXAyiKQz3K-b93tfDqsT2GVeUDkDN_n8CWJmlU_0P2DpYRzb3c38Ua79MhLTjs8CMAwA", "expires_in": 3599, "refresh_token": "1//0ezI2B9MKJ6DdCgYIARAAGA4SNwF-L9Ir3Cz15fhACf4OA9WP_3mCWk4yYh39CKDY3FuZt256UiG_IB5JCWTb87c54qGUaRaTGIs", "scope": "https://www.googleapis.com/auth/drive", "token_type": "Bearer", "created": 1608607167 }
參照
https://developers.google.com/people/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('People API PHP Quickstart'); $client->setScopes(Google_Service_PeopleService::CONTACTS_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_PeopleService($client); // Print the names for up to 10 connections. $optParams = array( 'pageSize' => 10, 'personFields' => 'names,emailAddresses', ); $results = $service->people_connections->listPeopleConnections('people/me', $optParams); if (count($results->getConnections()) == 0) { print "No connections found.\n"; } else { print "People:\n"; foreach ($results->getConnections() as $person) { if (count($person->getNames()) == 0) { print "No names found for this connection\n"; } else { $names = $person->getNames(); $name = $names[0]; printf("%s\n", $name->getDisplayName()); } } }
认证用token文件生成范例
<?php //google driveへアクセス用のトークンファイルを作成 $autoloadPath = __DIR__ . '/../../../vendor/autoload.php'; require $autoloadPath; if (php_sapi_name() != 'cli') { throw new Exception('This application must be run on the command line.'); } $envArr = ["dev", "stg", "prd"]; if ($argc !== 2 || !in_array($argv[1], $envArr) ) { echo "以下のコマンドを実行してください。\n"; echo "ロカールの場合:php createAuthToken.php dev \n"; echo "STGの場合:php createAuthToken.php stg \n"; echo "本番の場合:php createAuthToken.php prd \n"; exit; }; $client = new Google_Client(); $client->setApplicationName('Google Drive API PHP Quickstart'); $client->setScopes(Google_Service_Drive::DRIVE); $client->setAuthConfig('credentials_'.$argv[1].'.json'); $client->setAccessType('offline'); $client->setPrompt('select_account consent'); $tokenPath = 'driveAuthToken.json'; // 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()));
从google drive下载文件范例
<?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('credentials3.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; } function getFilesInParent($service, $parentId){ $optParams = array( //'pageSize' => 1000, 'fields' => 'nextPageToken, files(id, name, parents)' // ,'q' => "'1RORMSsy0qnC-XPS29a3vfwCB21l0jL_B' in parents" // ,'q' => "'root' in parents" ,'q' => "'".$parentId."' in parents" ); $results = $service->files->listFiles($optParams); return $results->getFiles(); }; //$pathはフォルダまで、指定したフォルダ内のファイルリストを取得 function getFileListFromPath($service, $path) { $folders = explode("/", $path); $files = getFilesInParent($service, "root"); $parentId = ""; for($i=0; $i<count($folders); $i++) { foreach($files as $file) { if($folders[$i] == $file->getName()) { $parentId = $file->getId(); break; } } $files = getFilesInParent($service, $parentId); } return $files; } //$pathはファイル名まで、指定したファイルをダウンロード function getFileFromPath($service, $path) { $folders = explode("/", $path); $files = getFilesInParent($service, "root"); $parentId = ""; for($i=0; $i<count($folders); $i++) { foreach($files as $file) { if($folders[$i] == $file->getName()) { $parentId = $file->getId(); break; } } if ($i < count($folders) - 1) { $files = getFilesInParent($service, $parentId); } } return $file; } // $results = $service->files->listFiles(); //ファイルリストの出力 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); } } } //ファイルリストのダウンロード function downloadFiles($service,$files){ foreach($files as $file) { download($service,$file); } } //ファイルのダウンロード function download($service,$file) { $response = $service->files->get($file->getId(), array( 'alt' => 'media')); $content = $response->getBody()->getContents(); $filename = $file->getName(); file_put_contents($filename, $content); } // Get the API client and construct the service object. $client = getClient(); $service = new Google_Service_Drive($client); //$files = getFileListFromPath($service, "testfile"); $files = getFileListFromPath($service, "root"); // $files = getFilesInParent($service, "share"); printfiels($files); // downloadFiles($service,$files); // $file = getFileFromPath($service, "testfile/excel2.xlsm"); // // download($service,$file); // // var_dump(stat("excel2.xlsm")); // chown("excel2.xlsm", "test"); // rename("#117_検討資料3.xlsx", "#117_検討資料4.xlsx"); // $file = fopen("./検討資料4.xlsx","r"); // print_r(stat("./検討資料4.xlsx")); // fclose($file);
从共享驱动(share drive)获取文件列表范例
public static function getFilesInParent($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' => 'allDrives' ,"supportsAllDrives"=>true ,'q' => $q ); $results = self::$service->files->listFiles($optParams); return $results->getFiles(); }