我又跟着这个教程从我的远程服务器上传文件在谷歌驱动器,使用PHP,直接:所以我从谷歌API控制台,使驱动器API服务创造了新的API项目,请OAuth用户端ID和客户端密钥,把它们写在脚本,然后一起上传谷歌API客户端库PHP文件夹,这个http://www.MYSERVER.com/script1.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('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我允许授权并获得验证码,我可以在第二个脚本编写。 然后,我把它上传到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上传我的谷歌驱动器和token.json文件的结构是一个排序:
{"access_token":"XXX","token_type":"Bearer","expires_in":3600,"refresh_token":"YYY","created":1365505148}
现在,你可以想像我可以打电话script2.php和上传文件,直到一定的时间。 最后,想说的是:我不想令牌到期,我不希望允许授权每次它到期(回顾script1.php):我需要在白天定期调用script2.php,上传我的自动文件, 而无需用户交互 。 那么,什么是自动刷新令牌永远在这种情况下最好的方法是什么? 我需要另一个脚本? 我可以添加一些代码来script2.php? 或修改token.json文件? 和我在哪里可以阅读剩余令牌到期前的时间? 谢谢!
你不必定期要求一个访问令牌。 如果你有一个refresh_token,PHP客户端将自动获取你一个新的访问令牌。
为了获取一个refresh_token,你需要ACCESS_TYPE设置为“脱机”,并要求离线访问权限:
$drive->setAccessType('offline');
一旦你得到一个code
,
$_GET['code']= 'X/XXX';
$drive->authenticate();
// persist refresh token encrypted
$refreshToken = $drive->getAccessToken()["refreshToken"];
对于未来的要求,确保刷新令牌始终设置:
$tokens = $drive->getAccessToken();
$tokens["refreshToken"] = $refreshToken;
$drive->setAccessToken(tokens);
如果你想有一个强制访问令牌刷新,可以通过调用做到这一点refreshToken
:
$drive->refreshToken($refreshToken);
当心, refresh_token
将只在第一个返回$drive->authenticate()
您需要永久保存它。 为了得到一个新的refresh_token,你需要撤销现有的令牌,并再次启动身份验证过程。
离线访问详细进行解释谷歌的OAuth 2.0文档 。
搞乱了很多后,我得到了这个工作。 我使用一个文件/脚本来获取离线令牌,然后一类做的东西与API:
require_once 'src/Google/autoload.php'; // load library
session_start();
$client = new Google_Client();
// Get your credentials from the console
$client->setApplicationName("Get Token");
$client->setClientId('...');
$client->setClientSecret('...');
$client->setRedirectUri('...'); // self redirect
$client->setScopes(array('https://www.googleapis.com/auth/drive.file'));
$client->setAccessType("offline");
$client->setApprovalPrompt('force');
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
$client->getAccessToken(["refreshToken"]);
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
return;
}
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
if (isset($_REQUEST['logout'])) {
unset($_SESSION['token']);
$client->revokeToken();
}
?>
<!doctype html>
<html>
<head><meta charset="utf-8"></head>
<body>
<header><h1>Get Token</h1></header>
<?php
if ($client->getAccessToken()) {
$_SESSION['token'] = $client->getAccessToken();
$token = json_decode($_SESSION['token']);
echo "Access Token = " . $token->access_token . '<br/>';
echo "Refresh Token = " . $token->refresh_token . '<br/>';
echo "Token type = " . $token->token_type . '<br/>';
echo "Expires in = " . $token->expires_in . '<br/>';
echo "Created = " . $token->created . '<br/>';
echo "<a class='logout' href='?logout'>Logout</a>";
file_put_contents("token.txt",$token->refresh_token); // saving access token to file for future use
} else {
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Connect Me!</a>";
}
?>
</body>
</html>
您可以从文件加载更新凭证,并用它作为必要的离线访问:
class gdrive{
function __construct(){
require_once 'src/Google/autoload.php';
$this->client = new Google_Client();
}
function initialize(){
echo "initializing class\n";
$client = $this->client;
// credentials from google console
$client->setClientId('...');
$client->setClientSecret('...');
$client->setRedirectUri('...');
$refreshToken = file_get_contents(__DIR__ . "/token.txt"); // load previously saved token
$client->refreshToken($refreshToken);
$tokens = $client->getAccessToken();
$client->setAccessToken($tokens);
$this->doSomething(); // go do something with the api
}
}
这里更多: https://github.com/yannisg/Google-Drive-Uploader-PHP