客户端未经授权使用此方法检索访问令牌,或未授权客户端使用任何请求的范围

问题描述 投票:2回答:1

你能帮我解决这个问题吗?

我使用的是PHP GOOGLE API V2.2.2

我的代码使用为它创建的gserviceaccount,但是,当我尝试操作我的个人GOOGLE DRIVE上的文件时,我有这个错误...

我尝试按照此处显示的步骤操作:Github issue 801

它很好,我的项目显示在我的authorized client list

这是我在google驱动器中创建文件夹的代码:

  function NovaPasta() {


    require_once APPPATH . 'third_party/google-api-php-client-2.2.2/vendor/autoload.php';

    putenv('GOOGLE_APPLICATION_CREDENTIALS='. APPPATH . 'third_party/google-api-php-client-2.2.2/Asist-428f3540df9a.json');
    $client = new Google_Client();
    $client->useApplicationDefaultCredentials();
    //$client->setAuthConfig(APPPATH . 'third_party/google-api-php-client-2.2.2/Asist-428f3540df9a.json');
    $client->addScope("https://www.googleapis.com/auth/drive");
    $client->setSubject('[email protected]');

    $driveService = new Google_Service_Drive($client);

    $fileMetadata = new Google_Service_Drive_DriveFile(array(
        'name' => 'new folder name',
        'mimeType' => 'application/vnd.google-apps.folder'));
    $file = $driveService->files->create($fileMetadata, array(
        'fields' => 'id'));
    printf("Folder ID: %s\n", $file->id);
}

这是错误:

遇到未被捕获的异常类型:Google_Service_Exception

消息:{“error”:“unauthorized_client”,“error_description”:“客户端未经授权使用此方法检索访问令牌,或未授权客户端使用任何请求的范围。” }

php google-api google-drive-sdk google-api-php-client
1个回答
0
投票

如果要使用服务帐户,则取消注释$ client-> setAuthConfig指向json文件并删除行$ client-> useApplicationDefaultCredentials();

https://github.com/googleapis/google-api-php-client/tree/master/examples上查看更多示例

$client = new Google_Client();
$client->setAuthConfig('service-account.json');
$client->setScopes(['https://www.googleapis.com/auth/drive']);
$service = new Google_Service_Drive($client);
$fileMetadata = new Google_Service_Drive_DriveFile(array('name' => 'Google_Service_Folder','mimeType' => 'application/vnd.google-apps.folder'));
$file = $service->files->create($fileMetadata, array('fields' => 'id'));
© www.soinside.com 2019 - 2024. All rights reserved.