Google Api服务帐户授权

时间:2017-05-15 09:27:05

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

这是我的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域范围的代表团。

1 个答案:

答案 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所示,

  1. 在“一个或多个API范围”字段中,输入应授予应用程序访问权限的范围列表。例如,如果您的应用需要对Google Drive API和Google Calendar API进行全域访问,请输入:https://www.googleapis.com/auth/drivehttps://www.googleapis.com/auth/calendar
  2. 由于请求的范围与授权客户端ID的范围列表中的范围不匹配,因此授权被拒绝,并且提供了403错误。