Google Drive SDK: Empty array of files returned fr

2019-08-05 08:09发布

问题:

I'm having some trouble with Drive SDK. I am trying to get all files from my Google Drive account into my app. I feel like I am doing everything that the Drive SDK documentation tells me to do, but every time I go to grab files, I get an empty array returned ... and no errors. I'm using the SDK as a service account, so the set up is a bit different. My site is running drupal by the way. Here is my code:

1) first off, I build the service (this is the body of a function named buildService():

$key = PATH_TO_KEY_FILE;
if (file_exists($key)) {

    try {
        $auth = new Google_AssertionCredentials(
                        SERVICE_ACCOUNT_EMAIL,
                        array(DRIVE_SCOPE),
                        $key);

        $client = new Google_Client();
        $client->setUseObjects(true);
        $client->setAssertionCredentials($auth);

    } catch (Exception $e) {
        print "An error occurred: " . $e->getMessage();
    }

    return new Google_DriveService($client);

}
else{
   return "can't find key file';
}

This block is completely fine, I get an object from Google_DriveService

2) the other side, I grab the service object, and attempt to list Drive files:

$parameters = array();
$service = buildService();  //my function from step 1
$files = retrieveAllFiles($service, $parameters);

3) Here is the the retrieveAllFiles function (straight from the SDK documentation):

function retrieveAllFiles($service, $parameters) {

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

    do {
        try { 
            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;

} 

As I said, I am getting an empty result returned, no errors, nothing.

Any Ideas as to why my result is empty?

Any help or suggestions are greatly appreciated.

回答1:

In the code you have provided you are accessing the Google Drive of the Service Account itself and not the Google Drive of a particular user on your domain. It is likely that the Google Drive of the Service Account is empty so getting an empty array of file is the expected result.

If you are trying to access the Google Drive of a particular user on your domain and have followed the documentation explaining how to setup Google Apps domain-wide delegation of Authority you are missing one line:

$auth->prn = $userEmail;

This is where you setup the email fo the user of the domain you are trying to impersonate. Then you will be accessing that user's Google Drive data.