更新Google API V3脚本以允许使用刷新令牌

时间:2014-10-23 08:36:50

标签: php oauth google-api

我正在使用以下代码,该代码在本教程中基本取消 - http://www.daimto.com/google-oauth2-php/

我添加了一行client->setAccessType("offline");,以便从Google收到一个刷新令牌,我可以从print "Access from google: " . $_SESSION['token'];看到。

我很难理解如何使用刷新令牌来获得授权。我理想的是将此脚本更新为   - 如果可用,则使用刷新令牌,或   - 介绍现有的" Connect Me"链接,如果一个不是

我计划最终将刷新令牌存储在数据库中,但为了让它最初工作,我只需要硬编码。

非常感谢任何帮助!

<?php        
set_include_path('src');
require_once 'Google/Client.php';     
require_once 'Google/Service/Calendar.php';

session_start();      
$client = new Google_Client();
    $client->setApplicationName("Client_Library_Examples");
    $client->setDeveloperKey("XXXXXXXXXXXXXXXXXXXX");  
    $client->setClientId('XXXXXXXXXXXXXXXXXXXX');
    $client->setClientSecret('XXXXXXXXXXXXXXXXXXXX');
    $client->setRedirectUri('XXXXXXXXXXXXXXXXXXXX');
    $client->setAccessType("offline");
    $client->setScopes(array('https://www.googleapis.com/auth/calendar'));

    //For loging out.
    if ($_GET['logout'] == "1") {
    unset($_SESSION['token']);
       }   

    // Step 2: The user accepted your access now you need to exchange it.
    if (isset($_GET['code'])) {
        $client->authenticate($_GET['code']);  
        $_SESSION['token'] = $client->getAccessToken();
        $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
        header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
    }

    // Step 1:  The user has not authenticated we give them a link to login    
    if (!$client->getAccessToken() && !isset($_SESSION['token'])) {
        $authUrl = $client->createAuthUrl();
        print "<a class='login' href='$authUrl'>Connect Me!</a>";
        }        

    // Step 3: We have access we can now create our service
    if (isset($_SESSION['token'])) {
        print "<a class='logout' href='".$_SERVER['PHP_SELF']."?logout=1'>LogOut</a><br>";
        $client->setAccessToken($_SESSION['token']);   
        $service = new Google_Service_Calendar($client); 
    }
 print "<br>";

 print "Access from google: " . $_SESSION['token']; 
 print "<br><br>";
 require_once 'calendar_app.php';

?>

0 个答案:

没有答案