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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15905104/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 10:10:15  来源:igfitidea点击:

Automatically refresh token using google drive api with php script

phpgoogle-apigoogle-drive-apigoogle-api-php-client

提问by Huxley

I followed again THIS TUTORIALto upload a file on Google Drive with php, directly from my REMOTE SERVER: so I have created new API Project from Google API Console, enabled Drive API service, requested OAuth Client ID and Client Secret, wrote them in a script, then upload it together with Google APIs Client Library for PHPfolder to this http://www.MYSERVER.com/script1.php, to retrieve Auth code:

我再次按照本教程使用 php 在 Google Drive 上直接从我的远程服务器上传文件:所以我从 Google API 控制台创建了新的 API 项目,启用了 Drive API 服务,请求了 OAuth 客户端 ID 和客户端密钥,将它们写在一个脚本,然后将其与PHP文件夹的Google API 客户端库一起上传到此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);

?>

When I visit http://www.MYSERVER.com/script1.phpI allow authorizationand get the Auth code that I can write in a second script. Then I upload it to http://www.MYSERVER.com/script2.php, who looks like:

当我访问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);

?>

Well, now the file drive.txt is uploaded on my Google Drive and structure of token.json file is a sort of:

好吧,现在文件 drive.txt 已上传到我的 Google Drive 并且 token.json 文件的结构是一种:

{"access_token":"XXX","token_type":"Bearer","expires_in":3600,"refresh_token":"YYY","created":1365505148}

Now, as you can imagine I can call script2.php and upload file until a certain time. Finally, the point is: I don't wantthe token to expire, I don't want to allow authorizationeach time it expire (recalling script1.php): I need to call the script2.php periodically during the day, to upload my file automatically, without user interaction. So, what's the best way to automatically refreshthe token forever in this context? Do I need another script? Can I add some code to script2.php? or modify the token.json file? And where can I read the time remaining before the token expire? Thanks!

现在,您可以想象我可以调用 script2.php 并上传文件,直到某个时间。最后,重点是:我不希望令牌过期,我不想每次过期都允许授权(回忆script1.php):我需要在白天定期调用script2.php,进行上传我的文件自动,无需用户交互。那么,在这种情况下永远自动刷新令牌的最佳方法是什么?我需要另一个脚本吗?我可以在script2.php 中添加一些代码吗?或修改 token.json 文件?我在哪里可以读取令牌到期前的剩余时间?谢谢!

回答by Burcu Dogan

You don't have to periodically ask for an access token. If you have a refresh_token, PHP client will automatically acquire a new access token for you.

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

In order to retrieve an refresh_token, you need to set access_type to "offline" and ask for offline access permissions:

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

$drive->setAccessType('offline');

Once you get a code,

一旦你得到一个code

$_GET['code']= 'X/XXX';
$drive->authenticate();

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

For future requests, make sure that refreshed token is always set:

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

$tokens = $drive->getAccessToken();
$tokens["refreshToken"] = $refreshToken;
$drive->setAccessToken(tokens);

If you want a force access token refresh, you can do it by calling refreshToken:

如果您想要强制访问令牌刷新,可以通过调用refreshToken

$drive->refreshToken($refreshToken);

Beware, refresh_tokenwill be returned only on the first $drive->authenticate(), you need to permanently store it. In order to get a new refresh_token, you need to revoke your existing token and start auth process again.

当心,refresh_token只会在第一次返回$drive->authenticate(),您需要永久存储它。为了获得新的 refresh_token,您需要撤销现有的令牌并再次启动身份验证过程。

Offline access is explained in detail on Google's OAuth 2.0 documentation.

Google 的 OAuth 2.0 文档中详细解释了离线访问。

回答by Yannis Giovanos

After messing a lot I got this to work. I am using one file/script to get the offline token and then a class to do stuff with the api:

在搞砸了很多之后,我得到了这个工作。我正在使用一个文件/脚本来获取离线令牌,然后使用一个类来处理 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>

You can load refresh token from file and use it as necessary for offline access:

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

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       
    }
}

More here: https://github.com/yannisg/Google-Drive-Uploader-PHP

更多信息:https: //github.com/yannisg/Google-Drive-Uploader-PHP