[英]How to connect to a Google Drive API and get the AccessToken
我在这里遇到了一个小问题,使用凭据 json 文件将我的脚本与 Google Drive API 连接起来。
这是我的代码:
$oauth_credentials = __DIR__.'\credentials.json';
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
$client = new Google\Client();
$client->setAccessType('offline');
$client->setAuthConfig($oauth_credentials);
$client->setRedirectUri($redirect_uri);
$client->addScope("https://www.googleapis.com/auth/drive");
if (isset($_GET['code'])) {
$token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
var_dump($token);
}
显然我使用composer将google apiclient项目添加到我的脚本中,我使用google的云控制台启用驱动器API并为此创建凭据,我使用了从Google控制台下载的credentials.json文件。
一切显然都很好,我添加了一个测试帐户并使用此帐户接受使用驱动器 API 的权限。
使用操场,在此 URL https://developers.google.com/oauthplayground中,我测试了我的凭据并获得了创建刷新令牌和访问令牌的授权码,但是当我在脚本中使用此授权码时,结果是这个: ””
'error' => string 'invalid_grant' (length=13)
'error_description' => string 'Bad Request' (length=11)
有什么建议吗? 此代码与 Google 示例中的代码完全相同。
我的问题是焦点是错误的方式,我创建了一个服务帐户并生成 json 凭据文件,我使用此代码上传文件:
putenv('GOOGLE_APPLICATION_CREDENTIALS=credentials.json');
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->setScopes(['https://www.googleapis.com/auth/drive.file']);
try {
$service = new Google_Service_Drive($client);
$file_path = 'example.txt';
$file = new Google_Service_Drive_DriveFile();
$file->setName('example.txt');
$file->setParents([$this->folder_id]);
$file->setDescription('Example description text');
$result = $service->files->create($file,[
'data' => file_get_contents($file_path),
'mimeType' => 'text/plain',
'uploadType' => 'text'
]);
echo '<a href="https://drive.google.com/open?id='.$result->id.'" target="_blank">Link to the uploaded file</a>';
}
catch(Google_Service_Exception $gs)
{
$m = json_decode($gs->getMessage());
echo $m->error->message;
}
catch(Exception $e)
{
echo $e->getMessage();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.