使用带有php脚本的google驱动器api自动刷新令牌

时间:2013-04-09 14:46:57

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

我再次跟踪THIS TUTORIAL直接从我的REMOTE SERVER上传了一个带有php的Google云端硬盘上的文件:所以我从Google API控制台创建了新的API项目,启用了Drive API服务,请求了OAuth客户端ID和客户端秘密,在脚本中写下它们,然后将它与Google APIs Client Library for 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时,允许授权并获取我可以在第二个脚本中编写的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云端硬盘上,而且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文件?在令牌到期之前,我在哪里可以读取剩余的时间?谢谢!

2 个答案:

答案 0 :(得分:30)

您无需定期询问访问令牌。如果您有refresh_token,PHP客户端将自动为您获取新的访问令牌。

要检索refresh_token,您需要将access_type设置为“offline”并要求离线访问权限:

$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,您需要撤销现有令牌并再次启动身份验证过程。

Google's OAuth 2.0 documentation详细说明了离线访问。

答案 1 :(得分:1)

经过多次搞乱后,我得到了这个工作。我使用一个文件/脚本来获取脱机令牌,然后使用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