使用google drive API PHP V3权限错误删除文件

时间:2018-01-07 20:00:26

标签: php google-drive-api

谷歌驱动PHP API V3存在问题我尝试使用以下代码从驱动器中删除文件:

这是我使用的代码:

<?php

require_once __DIR__ . '/vendor/autoload.php';

define('APPLICATION_NAME', 'Google Drive API PHP');
define('CREDENTIALS_PATH', '/root/.credentials/drive-php.json');
define('CLIENT_SECRET_PATH', __DIR__ . '/client_secret.json');
define('SCOPES', implode(' ', array(
    Google_Service_Drive::DRIVE_METADATA_READONLY
)
));

if (php_sapi_name() != 'cgi-fcgi') {
    throw new Exception('This application must be run on the command line.');
}

function getClient() {
    $client = new Google_Client();
    $client->setApplicationName(APPLICATION_NAME);
    $client->setScopes(SCOPES);
    $client->setAuthConfig(CLIENT_SECRET_PATH);
    $client->setAccessType('offline');
    $accessToken = json_decode(file_get_contents(CREDENTIALS_PATH), true);
    $client->setAccessToken($accessToken);
    // Refresh the token if it's expired.
    if ($client->isAccessTokenExpired()) {
        $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
        file_put_contents(CREDENTIALS_PATH, json_encode($client->getAccessToken()));
    }
    return $client;
}

$client = getClient();
$service = new Google_Service_Drive($client);

$optParams = array(
    'fields' => 'files(id, createdTime)'
);
$results = $service->files->listFiles($optParams);

if (count($results->getFiles()) != 0) {
    foreach ($results->getFiles() as $file) {
        $service->files->delete($file['id']);
    }
}

一切正常我可以获取文件的ID但是当我尝试删除它时,我得到以下错误。 知道为什么好吗?

由于

PHP Fatal error:  Uncaught Google_Service_Exception: {
     "error": {
      "errors": [
       {
        "domain": "global",
        "reason": "insufficientPermissions",
        "message": "Insufficient Permission"
       }
      ],
      "code": 403,
      "message": "Insufficient Permission"
     }
    }

1 个答案:

答案 0 :(得分:1)

Google_Service_Drive::DRIVE_METADATA_READONLY不能用于使用Drive API删除文件。那么如何使用Google_Service_Drive::DRIVE作为范围?

修改范围后,请删除drive-php.json处的/root/.credentials/文件,然后再次运行该脚本。这样,访问令牌和刷新令牌反映了可以检索修改后的范围。

然后,请确认是否再次启用了Drive API。

如果这对你没用,我很抱歉。

相关问题