【发布时间】:2017-05-15 09:27:05
【问题描述】:
这是我的 service.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 域范围委派。
【问题讨论】:
-
当账户配置不正确时会发生这种错误......也许this issue可以帮助你找出你错过了什么。
-
确保您已设置域委托developers.google.com/identity/protocols/… 您的服务帐户需要访问 user@mydomain.com 文件。
-
嗨@DaImTo,我已经设置了域委托。我在问题的最后一行也提到了。
-
嗨@ElmerDantas,我已经使用链接[link](developers.google.com/identity/protocols/…)配置了帐户,我可以成功阅读用户的电子邮件,但无法上传文件。
-
我发现您的代码存在三个问题: - 授权错误表明未配置 DwD,或者您使用了错误的范围。代码中的范围必须与安全 > 高级 > 管理 API 客户端访问下的范围完全相同。 - 您的代码在元数据数组中使用了未定义的 $mimeType 变量。如果要在数组中使用 $mimeType 变量,请确保预先定义好它。 - 文件名似乎拼写错误,“exapmle.txt”而不是“example.txt”。确保文件的路径正确,并且指定的文件确实存在。
标签: php google-api google-api-php-client