这是我的serivice.php文件:
putenv('GOOGLE_APPLICATION_CREDENTIALS=service-account.json');
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->setSubject('user@mydomain.com');
$client->setScopes('https://www.googleapis.com/auth/drive.file');
$service = new Google_Service_Drive($client);
//Create a new drive file
$file = new Google_Service_Drive_DriveFile();
$file->setName('example');
$file->setMimeType('application/vnd.google-apps.file');
$data = file_get_contents('exapmle.txt');
//Upload the file to google docs
$createdFile = $service->files->create($file, array(
'data' => $data,
'mimeType' => $mimeType,
'uploadType' => 'multipart'
));
我在同一工作目录中有service-account.json文件。
但是我收到了这个错误:
PHP Fatal error: Uncaught Google_Service_Exception: {
"error": "unauthorized_client",
"error_description": "Client is unauthorized to retrieve access tokens using this method."
}
in \vendor\google\apiclient\src\Google\Http\REST.php:118
我也启用了G Suite域范围的代表团。
答案 0 :(得分:1)
将我的笔记放在完整的上下文中:
在代码中定义了Drive.file范围:
$client->setScopes('https://www.googleapis.com/auth/drive.file');
但在安全>下的管理控制台中高级> 管理API客户端访问,范围列表授权以下域范围授权。
https://googleapis.com/auth/drive
如https://developers.google.com/identity/protocols/OAuth2ServiceAccount#delegatingauthority所示,
由于请求的范围与授权客户端ID的范围列表中的范围不匹配,因此授权被拒绝,并且提供了403错误。