我再次按照本教程使用 php 在 Google Drive 上上传文件,直接从我的远程服务器:所以我从 Google API 控制台创建了新的 API 项目,启用 Drive API 服务,请求 OAuth 客户端 ID 和客户端密码,将它们写在脚本,然后将其与Google APIs Client Library for PHP文件夹一起上传到此http://www.MYSERVER.com/script1.php,以检索 Auth 代码:
<?php
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_DriveService.php';
$drive = new Google_Client();
$drive->setClientId('XXX'); // HERE I WRITE MY Client ID
$drive->setClientSecret('XXX'); // HERE I WRITE MY Client Secret
$drive->setRedirectUri('urn:ietf:wg:oauth:2.0:oob');
$drive->setScopes(array('https://www.googleapis.com/auth/drive'));
$gdrive = new Google_DriveService($drive);
$url = $drive->createAuthUrl();
$authorizationCode = trim(fgets(STDIN));
$token = $drive->authenticate($authorizationCode);
?>
当我访问http://www.MYSERVER.com/script1.php时 ,我允许授权并获得我可以在第二个脚本中编写的 Auth 代码。然后我将它上传到http://www.MYSERVER.com/script2.php,它看起来像:
<?php
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_DriveService.php';
$drive = new Google_Client();
$drive->setClientId('X'); // HERE I WRITE MY Client ID
$drive->setClientSecret('X'); // HERE I WRITE MY Client Secret
$drive->setRedirectUri('urn:ietf:wg:oauth:2.0:oob');
$drive->setScopes(array('https://www.googleapis.com/auth/drive'));
$gdrive = new Google_DriveService($drive);
$_GET['code']= 'X/XXX'; // HERE I WRITE AUTH CODE RETRIEVED AFTER RUNNING REMOTE script.php
file_put_contents('token.json', $drive->authenticate());
$drive->setAccessToken(file_get_contents('token.json'));
$doc = new Google_DriveFile();
$doc->setTitle('Test Drive');
$doc->setDescription('Document');
$doc->setMimeType('text/plain');
$content = file_get_contents('drive.txt');
$output = $gdrive->files->insert($doc, array(
'data' => $content,
'mimeType' => 'text/plain',
));
print_r($output);
?>
好吧,现在文件 drive.txt 已上传到我的 Google Drive 上,并且 token.json 文件的结构是一种:
{"access_token":"XXX","token_type":"Bearer","expires_in":3600,"refresh_token":"YYY","created":1365505148}
现在,您可以想象我可以调用 script2.php 并上传文件直到某个时间。最后,重点是:不想token过期,不想每次过期都允许授权(回忆script1.php):白天需要定时调用script2.php,进行上传我的文件自动,无需用户交互。那么,在这种情况下永久自动刷新令牌的最佳方法是什么?我需要另一个脚本吗?我可以在 script2.php 中添加一些代码吗?还是修改 token.json 文件?我在哪里可以读取令牌到期前的剩余时间?谢谢!