Php 谷歌Api服务帐户授权
这是我的service.php文件:Php 谷歌Api服务帐户授权,php,google-api,google-api-php-client,Php,Google Api,Google Api Php Client,这是我的service.php文件: putenv('GOOGLE_APPLICATION_CREDENTIALS=service-account.json'); $client = new Google_Client(); $client->useApplicationDefaultCredentials(); $client->setSubject('user@mydomain.com'); $client->setScopes('https://www.googlea
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套件域范围的委派。将我的说明置于完整上下文中: 在代码中定义了Drive.file作用域:
$client->setScopes('https://www.googleapis.com/auth/drive.file');
但是在管理控制台中的安全高级管理API客户端访问下,作用域列表授权以下域范围的委派
https://googleapis.com/auth/drive
如所示
由于请求的范围与客户ID授权范围列表中的范围不匹配,授权被拒绝,并且出现了403错误。如果帐户配置不正确,则会发生此类错误…可能会帮助您找出遗漏的内容。请确保您已设置了服务帐户需要访问的域委派user@mydomain.comfiles.Hi@DaImTo,我已经设置了域委派。我在问题的最后一行也提到了。您好@ElmerDantas,我已经使用链接[link]()配置了帐户。我可以成功读取用户的电子邮件,但无法上载文件。我发现您的代码有三个问题:-授权错误表明DwD未配置,或者您使用了错误的作用域。代码中的作用域必须与“安全性”>“高级”>“管理API客户端访问”下的作用域完全相同。-您的代码在元数据数组中使用未定义的$mimeType变量。如果要在数组中使用$mimeType变量,请确保事先定义了该变量。-文件名似乎拼错了“exapmle.txt”而不是“example.txt”。确保文件路径正确,并且指定的文件实际存在。