Google drive api 无法将子帐户与Google服务帐户一起使用

Google drive api 无法将子帐户与Google服务帐户一起使用,google-drive-api,google-oauth,google-api-php-client,Google Drive Api,Google Oauth,Google Api Php Client,我需要创建一个脚本,将生成的屏幕截图上传到GoogleDrive 我希望我能以我的谷歌用户身份登录,但这似乎。。。更努力?所以我放弃了这种策略。接下来,我转到服务帐户。现在这对我的服务帐户很有效,但当我尝试指定用户$auth->sub时,请求中会出现未经授权的客户端或作用域 function buildService($userEmail) { $DRIVE_SCOPE = 'https://www.googleapis.com/auth/drive'; $SERVICE_ACCOUNT

我需要创建一个脚本,将生成的屏幕截图上传到GoogleDrive

我希望我能以我的谷歌用户身份登录,但这似乎。。。更努力?所以我放弃了这种策略。接下来,我转到服务帐户。现在这对我的服务帐户很有效,但当我尝试指定用户$auth->sub时,请求中会出现未经授权的客户端或作用域

function buildService($userEmail) {
  $DRIVE_SCOPE = 'https://www.googleapis.com/auth/drive';
  $SERVICE_ACCOUNT_EMAIL = 'notsupplied@developer.gserviceaccount.com';
  $SERVICE_ACCOUNT_PKCS12_FILE_PATH = 'pathtofile.p12';

  $key = file_get_contents($SERVICE_ACCOUNT_PKCS12_FILE_PATH);
  $auth = new Google_Auth_AssertionCredentials(
    $SERVICE_ACCOUNT_EMAIL,
    array($DRIVE_SCOPE),
    $key);
  $auth->sub = 'myuser@gmail.com';
  $client = new Google_Client();
  $client->setAssertionCredentials($auth);
  return new Google_Service_Drive($client);
}

我很想放弃这个服务帐户,只要和我的普通谷歌用户进行身份验证就行了。或者在api设置中如何解决?我可以保证myuser@gmail.com可以使用。

刷新\u令牌是此处的关键。在网络浏览器中,使用此链接批准您的google用户:

https://accounts.google.com/AccountChooser?service=lso&continue=https%3A%2F%2Faccounts.google.com%2Fo%2Foauth2%2Fauth%3Fresponse_type%3Dcode%26scope%3Dhttps%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdrive%26redirect_uri%3Dhttps%3A%2F%2Fwww.example.com%2Foauth2callback%26access_type%3Doffline%26client_id%3D<CLIENT_ID>%26hl%3Den%26from_login%3D1%26as%3D34eac985232ba748&btmpl=authsub&hl=en&approval_prompt=force&access_type=offline
它将返回一个URL,如

然后发布代码=&client\u id=&client\u secret=&redirect\u uri=&grant\u type=授权\u代码到

这将返回一个刷新令牌参数。保存这个。非常重要。如果你没有得到一个,你必须去撤销你的应用程序的权限

获得刷新令牌后,您就可以开始了:

$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->addScope("https://www.googleapis.com/auth/drive");
$client->setAccessType('offline');
$token = $client->refreshToken('<YOUR_REFRESH_TOKEN>');
$service = new Google_Service_Drive($client);