【问题标题】:Google Drive PHP API: Delete shows Insufficient PermissionGoogle Drive PHP API:删除显示权限不足
【发布时间】:2018-08-20 10:54:24
【问题描述】:

我一直在努力删除我的 Google 云端硬盘中的一个文件,但我无法成功。我已将我的范围从 $client->setScopes(Google_Service_Drive::DRIVE_METADATA_READONLY); 更改为 $client->setScopes(Google_Service_Drive::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_METADATA_READONLY);
  $client->setScopes(Google_Service_Drive::DRIVE);
  //$client->setScopes(Google_Service_Drive::DRIVE_APPDATA);
  //$client->setScopes(Google_Service_Drive::DRIVE_FILE);
  //$client->setAuthConfig('credentials.json');
  $client->setAccessType('offline');

  // Load previously authorized credentials from a file.
  $credentialsPath = 'token.json';
  if (file_exists($credentialsPath)) {
    $accessToken = json_decode(file_get_contents($credentialsPath), true);
  } 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);

    // Check to see if there was an error.
    if (array_key_exists('error', $accessToken)) {
        throw new Exception(join(', ', $accessToken));
    }

    // Store the credentials to disk.
    if (!file_exists(dirname($credentialsPath))) {
        mkdir(dirname($credentialsPath), 0700, true);
    }
    file_put_contents($credentialsPath, json_encode($accessToken));
    printf("Credentials saved to %s\n", $credentialsPath);
}
$client->setAccessToken($accessToken);

// Refresh the token if it's expired.
if ($client->isAccessTokenExpired()) {
    $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
    file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
}
    return $client;
}


// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Drive($client);

/*Get Files under hourly_backup*/
$hourly_backup_id = '1Y3cGEwXy9gLcw9WO0isqwtwtysU0g_bK';

$optParams = array(
  //'pageSize' => 20,
  'fields' => 'nextPageToken, files(id,name,size,parents,createdTime)',
  'q' => "'".$hourly_backup_id."' in parents"
);
$results = $service->files->listFiles($optParams);

if (count($results->getFiles()) == 0) {
    print "No files found.\n";
} else {
    foreach ($results->getFiles() as $file) {
        if(strtotime(date('Y-m-d H:i:s', strtotime($file->getcreatedTime()))) <= strtotime('-48 hours')){
            try {
                return $service->files->delete($file->getId());
            } catch (Exception $e) {
                print "An error occurred: " . $e->getMessage();
            }
            return NULL;
        } else {
           print "weh \n";
        }
    }
}

如果满足条件并运行删除代码,这就是我得到的:

An error occurred: {
 "error": {
   "errors": [
   {
    "domain": "global",
    "reason": "insufficientPermissions",
    "message": "Insufficient Permission"
   }
  ],
  "code": 403,
  "message": "Insufficient Permission"
 }
}

更新:

我也在 API Explorer 中进行了尝试,它没有任何问题。

我正在使用的谷歌驱动器是我的,我可以直接删除文件而没有任何问题。我的代码中可能缺少什么?

【问题讨论】:

  • 你拿到token成功保存到token.json了吗?
  • @RinsadAhmed 我想是的。因为我能够得到我的文件列表。只是删除不起作用。

标签: php google-api google-drive-api google-api-php-client


【解决方案1】:

“权限不足”

仅表示当前已通过身份验证的用户无权执行您尝试执行的操作。

你说你改变了范围。但是您是否重新验证了应用程序?该应用程序将弹出并请求驱动器帐户的权限。如果您仍在使用仍然具有只读访问权限的旧访问令牌或刷新令牌运行,您将无法删除该文件。

【讨论】:

  • 仍在使用过时的令牌似乎是合理的,而文档甚至没有列出 403: developers.google.com/drive/api/v3/handle-errors
  • “权限不足”是所有 Google API 的默认错误消息。它不会出现在云端硬盘特定的错误消息页面下。
【解决方案2】:

是的! 为我工作只更改为:

$client->setScopes(Google_Service_Drive::DRIVE);

您需要重新启动会话。 查找文件:

token.json

在您的目录中,删除此 token.json 文件并再次尝试 quickstart.php。 您要求提供新的凭据,现在您已完成上传文件的访问权限。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-18
    • 2016-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-25
    • 1970-01-01
    相关资源
    最近更新 更多