Google API Oauth php永久访问

hop*_*ies 16 php google-api access-token oauth-2.0

我正在使用谷歌日历API.这就是我想要的,一旦你给予应用程序许可,我总是可以使用该应用程序,而无需每天访问.我一直听说我需要保存访问令牌或使用刷新令牌来做我想做的事情.这就是问题,你是怎么做到的?代码如何?我已经尝试将令牌保存在cookie中,但一小时后,访问令牌已过期.如何让用户保持登录状态?

PS:请给我解释代码示例.

这是我的代码(使用CakePHP):

$client = new Google_Client();

    $client->setApplicationName("Wanda3.0 Agenda");

    $cal = new Google_CalendarService($client);

    if (isset($_GET['code'])) {

        $client->authenticate($_GET['code']);


        $_SESSION['token'] = $client->getAccessToken();


        header('Location: http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']);

    }

    if (isset($_SESSION['token'])) { $client->setAccessToken($_SESSION['token']); }

if ($client->getAccessToken()) {
        /************* Code entry *************/


    }else{
        /************* Not connected to google calendar code *************/
        $authUrl = $client->createAuthUrl();

        $returnArr = array('status' => 'false', 'message' => "<a class='login' href='$authUrl'>Connect Me!</a>");

        return $returnArr;

    }
Run Code Online (Sandbox Code Playgroud)

hop*_*ies 15

好的,等了好几天后,Terry Seidler的建议(下面的评论)让这一切都成真了!这是我的一段代码,关于如何自动刷新访问令牌,而不是每次都使用cookie进行验证.

(注意:在数据库中保存刷新令牌更安全)

这是神奇的(使用cookies):

$client = new Google_Client();

    $client->setApplicationName("Wanda3.0 Agenda");

    $cal = new Google_CalendarService($client);

    $client->setAccessType('offline');

    if (isset($_GET['code'])) {

        $client->authenticate($_GET['code']);

        $_SESSION['token'] = $client->getAccessToken();

        header('Location: http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']);

    }

    //Where the magic happends
    if (isset($_SESSION['token'])) {

        //Set the new access token after authentication
        $client->setAccessToken($_SESSION['token']);

        //json decode the session token and save it in a variable as object
        $sessionToken = json_decode($_SESSION['token']);

        //Save the refresh token (object->refresh_token) into a cookie called 'token' and make last for 1 month
        $this->Cookie->write('token', $sessionToken->refresh_token, false, '1 month');
    }

    //Each time you need the access token, check if there is something saved in the cookie.
    //If $cookie is empty, you are requested to get a new acces and refresh token by authenticating.
    //If $cookie is not empty, you will tell the client to refresh the token for further use,
    // hence get a new acces token with the help of the refresh token without authenticating..
    $cookie = $this->Cookie->read('token');

    if(!empty($cookie)){
        $client->refreshToken($this->Cookie->read('token'));
    }
Run Code Online (Sandbox Code Playgroud)

就是这样!如果您有任何疑问,请随时在下面留言,我会尽我所能回答.古德勒克和干杯!