简体   繁体   中英

Google Drive API (PHP) can't list files

I'm programming an app to retrieve files from Google Drive (in my own drive account).

I've created a Google Service Account to avoid the OAuth process because I'm using my own Google Drive account.

Then I've taken this code example from Google:

function buildService() {

$SERVICE_ACCOUNT_EMAIL = 'xxxx@developer.gserviceaccount.com'; 
$SERVICE_ACCOUNT_PKCS12_FILE_PATH = 'xxx-privatekey.p12';

  $key = file_get_contents($SERVICE_ACCOUNT_PKCS12_FILE_PATH);
  $auth = new Google_AssertionCredentials(
      $SERVICE_ACCOUNT_EMAIL,
      array('https://www.googleapis.com/auth/drive'),
      $key);
  $client = new Google_Client();
  $client->setUseObjects(true);
  $client->setAssertionCredentials($auth);

  return new Google_DriveService($client);
}



function retrieveAllFiles($service) {

  $result = array();
  $pageToken = NULL;

  do {
    try {
      $parameters = array();
      if ($pageToken) {
        $parameters['pageToken'] = $pageToken;
      }

      $files = $service->files->listFiles($parameters);


      $result = array_merge($result, $files->getItems());
      $pageToken = $files->getNextPageToken();
    } catch (Exception $e) {
      print "An error occurred: " . $e->getMessage();
      $pageToken = NULL;
    }
  } while ($pageToken);
  return $result;
}


$service = buildService();

$allFiles = retrieveAllFiles($service);

print_r($allFiles);

It returns an empty array when I've there files and folders:

Array
(
)

In the configuration the email and the private key are OK, provided by Google itself; what I'm doing wrong?

Try to change code like here https://developers.google.com/drive/delegation :

  function buildService($userEmail) {

   $SERVICE_ACCOUNT_EMAIL = 'xxxx@developer.gserviceaccount.com'; 
   $SERVICE_ACCOUNT_PKCS12_FILE_PATH = 'xxx-privatekey.p12';

   $key = file_get_contents($SERVICE_ACCOUNT_PKCS12_FILE_PATH);
   $auth = new Google_AssertionCredentials(
     $SERVICE_ACCOUNT_EMAIL,
     array('https://www.googleapis.com/auth/drive'),
     $key);
   $auth->sub = $userEmail;
   $client = new Google_Client();
   $client->setUseObjects(true);
   $client->setAssertionCredentials($auth);

   return new Google_DriveService($client);
 }

 //... function retrieveAllFiles($service) 

 $service = buildService("some@mail");
 $allFiles = retrieveAllFiles($service);
 print_r($allFiles);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM