Automatyczne odświeżanie tokena za pomocą Google drive api ze skryptem php

Ponownie śledziłem ten TUTORIAL aby przesłać plik na Dysk Google z php, bezpośrednio z mojego zdalnego serwera: więc stworzyłem nowy projekt API z Google API Console, włączyłem usługę Drive API, poprosiłem OAuth Client ID i Client Secret, napisałem je w skrypcie, a następnie przesłałem go razem z Google API Client Library for PHP folder do tego http://www.MYSERVER.com/script1.php , Aby pobrać kod 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);

?>
Kiedy odwiedzam http://www.MYSERVER.com/script1.php i zezwalam na autoryzację i otrzymuję Kod Auth, który mogę napisać w drugim skrypcie. Następnie wgram go do http://www.MYSERVER.com/script2.php , który wygląda jak:
<?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);

?>
Teraz napęd plików.txt jest przesyłany na mój dysk Google i strukturę tokena.plik json jest rodzajem:
{"access_token":"XXX","token_type":"Bearer","expires_in":3600,"refresh_token":"YYY","created":1365505148}

Teraz, jak możesz sobie wyobrazić, mogę nazwać script2.php i przesłać plik do określonego czasu. W końcu chodzi o to, że ja[14]}nie chcesz token wygaśnie, ja nie chcę zezwalać na autoryzację za każdym razem, gdy wygaśnie (przypominając skrypt1.php): muszę wywołać skrypt2.php okresowo w ciągu dnia, aby przesłać mój plik automatycznie, BEZ interakcji użytkownika. Jaki jest najlepszy sposób, aby automatycznie odświeżyć token na zawsze w tym kontekście? Czy potrzebuję innego scenariusza? Czy Mogę dodać jakiś kod do script2.php? lub zmodyfikować token.plik json? A gdzie mogę odczytać czas pozostały do wygasa token? Dzięki!

Author: Huxley, 2013-04-09

2 answers

Nie musisz okresowo prosić o token dostępu. Jeśli masz refresh_token, klient PHP automatycznie uzyska dla Ciebie nowy token dostępu.

Aby pobrać refresh_token, musisz ustawić access_type na "offline" i poprosić o uprawnienia dostępu offline:

$drive->setAccessType('offline');

Gdy otrzymasz code,

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

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

Dla przyszłych żądań upewnij się, że odświeżony token jest zawsze ustawiony:

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

Jeśli chcesz odświeżyć token force access, możesz to zrobić poprzez wywołanie refreshToken:

$drive->refreshToken($refreshToken);

Uwaga, refresh_token zostaną zwrócone tylko w pierwszym $drive->authenticate(), musisz je na stałe przechowywać. Aby uzyskać nowy refresh_token, musisz odwołać istniejący token i ponownie rozpocząć proces auth.

Dostęp Offline jest szczegółowo wyjaśniony na dokumentacji Google OAuth 2.0.
 30
Author: Burcu Dogan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-04-09 15:29:35

Po zamieszaniu mam to do pracy. Używam jednego pliku / skryptu, aby uzyskać token offline, a następnie klasę do robienia rzeczy z 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>

Możesz załadować token refresh z pliku i użyć go w razie potrzeby do dostępu offline:

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

Więcej tutaj: https://github.com/yannisg/Google-Drive-Uploader-PHP

 1
Author: Yannis Giovanos,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-08-06 13:56:14