2013-04-09 25 views
8

Ho seguito di nuovo THIS TUTORIAL per caricare un file su Google Drive con php, direttamente dal mio REMOTE SERVER: così ho creato un nuovo progetto API da Google API Console, abilitato servizio API Drive, richiesto ID client OAuth e client segreto, li ha scritto in uno script, quindi caricarlo insieme con la cartella Google APIs Client Library for PHP a questo http://www.MYSERVER.com/script1.php, per recuperare il codice di accesso:Aggiorna automaticamente token tramite google drive api con script 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); 

?> 

Quando visito http://www.MYSERVER.com/script1.php I permetto autorizzazione e ottenere l'Auth codice che posso scrivere in un secondo script. Poi ho caricarlo http://www.MYSERVER.com/script2.php, che sembra:

<?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); 

?> 

Bene, ora il file drive.txt viene caricato sul mio Google Drive e la struttura del file di token.json è una sorta di:

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

Ora, come puoi immaginare, posso chiamare script2.php e caricare file fino a un certo momento. Infine, il punto è: I non voglio il token che scade, I non voglio consentire l'autorizzazione ogni volta che scade (richiamando script1.php): Ho bisogno di chiamare period2 script.php durante il giorno, per caricare automaticamente il mio file, senza l'interazione dell'utente. Quindi, qual è il modo migliore per aggiornare automaticamente il token per sempre in questo contesto? Ho bisogno di un altro script? Posso aggiungere del codice a script2.php? o modificare il file token.json? E dove posso leggere il tempo rimanente prima della scadenza del token? Grazie!

risposta

30

Non è necessario richiedere periodicamente un token di accesso. Se hai un refresh_token, il client PHP acquisirà automaticamente un nuovo token di accesso per te.

Al fine di recuperare un refresh_token, è necessario impostare tipo_accesso a "offline" e chiedere permessi di accesso offline:

$drive->setAccessType('offline'); 

Una volta che si ottiene un code,

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

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

Per richieste future , assicurati che il token aggiornato sia sempre impostato:

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

Se si desidera un accesso forza token di aggiornamento, è possibile farlo chiamando refreshToken:

$drive->refreshToken($refreshToken); 

Attenzione, refresh_token verrà restituito solo il primo $drive->authenticate(), è necessario memorizzare in modo permanente. Per ottenere un nuovo refresh_token, è necessario revocare il token esistente e avviare nuovamente il processo di autenticazione.

L'accesso offline è spiegato in dettaglio su Google's OAuth 2.0 documentation.

+0

Grazie @Burcu, il punto è nelle tue parole "Se il token di accesso è scaduto": QUANDO POSSO VEDERE che il mio token di accesso è scaduto? è permanente o no? – Huxley

+0

@Huxley, genererà un 'Google_AuthException'. D'altra parte, questa libreria client aggiorna automaticamente il token di accesso se quello attuale sta per scadere. Quindi, normalmente non dovresti mai vedere un errore di autenticazione. Sto modificando la mia risposta sopra. –

+0

Ho recuperato refresh_token e access_token dalla console OAuth 2.0 Playground e l'ho memorizzato nel mio file token.json: è la stessa cosa? sono permanenti? – Huxley

1

Dopo aver fatto molti problemi, ho capito tutto.Sto usando un file/script per ottenere il token non in linea e quindi una classe per fare cose con le 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> 

È possibile caricare token di aggiornamento da file e usarlo come necessario per l'accesso 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  
    } 
} 

Maggiori informazioni qui: https://github.com/yannisg/Google-Drive-Uploader-PHP

Problemi correlati