首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用带有php脚本的google自动刷新令牌

问使用带有php脚本的google自动刷新令牌
EN

Stack Overflow用户
提问于 2013-04-09 14:46:57
回答 2查看 31.5K关注 0票数 8

我再次跟随本教程将一个文件上传到带有php的Google上,直接从我的远程服务器上上传:因此,我从Google控制台创建了新的API,启用了Drive服务,请求了OAuth客户端ID和客户端秘密,将它们写入脚本,然后与Google客户端PHP库文件夹一起上传到这个http://www.MYSERVER.com/script1.php中,以检索Auth代码:

代码语言:javascript
复制
<?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,他看起来像:

代码语言:javascript
复制
<?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文件的结构类似于:

代码语言:javascript
复制
{"access_token":"XXX","token_type":"Bearer","expires_in":3600,"refresh_token":"YYY","created":1365505148}

现在,正如您可以想象的那样,我可以调用script2.php并上传文件直到一定的时间。最后,重点是:I不希望令牌过期,我不希望每次它过期时都允许授权(回顾script1.php):我需要在白天定期调用script2.php,以便自动上传我的文件,没有用户交互。那么,在这个上下文中,自动刷新令牌的最佳方法是什么?我需要另一个剧本吗?我可以向script2.php添加一些代码吗?还是修改token.json文件?在令牌过期之前,我可以在哪里读到剩余的时间?谢谢!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-04-09 15:07:49

您不必定期请求访问令牌。如果您有一个refresh_token,PHP将自动为您获取一个新的访问令牌。

为了检索refresh_token,需要将access_type设置为“脱机”并请求脱机访问权限:

代码语言:javascript
复制
$drive->setAccessType('offline');

一旦你得到了code,

代码语言:javascript
复制
$_GET['code']= 'X/XXX';
$drive->authenticate();

// persist refresh token encrypted
$refreshToken = $drive->getAccessToken()["refreshToken"];

对于未来的请求,请确保始终设置刷新令牌:

代码语言:javascript
复制
$tokens = $drive->getAccessToken();
$tokens["refreshToken"] = $refreshToken;
$drive->setAccessToken(tokens);

如果您希望进行强制访问令牌刷新,则可以通过调用refreshToken进行此操作。

代码语言:javascript
复制
$drive->refreshToken($refreshToken);

注意,refresh_token只会在第一个$drive->authenticate()上返回,您需要永久地存储它。为了获得一个新的refresh_token,您需要撤销现有的令牌并再次启动auth进程。

离线访问将在谷歌的OAuth 2.0文档上详细解释。

票数 31
EN

Stack Overflow用户

发布于 2015-08-06 09:09:57

我把事情搞砸了,我要把这件事做好。我使用一个文件/脚本来获取离线令牌,然后使用一个类来处理api:

代码语言:javascript
复制
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>

您可以从文件中加载刷新令牌,并根据需要使用它进行脱机访问:

代码语言:javascript
复制
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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15905104

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档