Постоянный доступ к API Google Oauth php

Я использую Google Calendar 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;

    }

Ответы

Ответ 1

Хорошо, после ожидания нескольких дней предложение Терри Сейдлера (комментарии ниже) заставило все это произойти! Вот мой кусок кода о том, как автоматически обновлять токен доступа, не определяя каждый раз использование файлов cookie.

(ВНИМАНИЕ: безопаснее сохранять токен обновления в базе данных)

Это волшебство (использование файлов cookie):

$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'));
    }

И вот оно! Если у вас есть какие-либо вопросы, не стесняйтесь оставить комментарий ниже, и я отвечу на все, что могу. Goodluck и Cheers!

Ответ 2

Вместо использования файлов cookie и сеансов вы должны сохранить их в базе данных и использовать.

Аналогичная реализация для сайта drupal находится в песочнице Google OAuth2 в http://drupal.org/sandbox/sadashiv/1857254 Этот модуль позволяет обрабатывать аутентификацию из интерфейса администратора drupal, Затем вы можете использовать выбранный токен доступа из Google, а затем использовать функцию api для google_oauth2_account_load или google_oauth2_client_get, чтобы получить Google_Client и нести свой api-вызов.

Ответ 3

Во многом то же самое, что и в индустрии надежды, но после тестирования я только хотел обновить токен, когда мне пришлось. Полный источник просто меняет клавиши и т.д. Вверху:

require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_CalendarService.php';
session_start();
$client = new Google_Client();
$client->setApplicationName("Google Calendar PHP Starter Application");
// Visit https://code.google.com/apis/console?api=calendar to generate your
// client id, client secret, and to register your redirect uri.
$client->setClientId('your_id');
$client->setClientSecret('your_secret');
$client->setRedirectUri("http://localhost/your_redirect.php");
$client->setDeveloperKey('your_key');

$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'] . $query_string);
}

if (isset($_SESSION['token'])) {
    $client->setAccessToken($_SESSION['token']);//update 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
    if (isset($sessionToken->refresh_token)) { //refresh token is only set after a proper authorisation
        $number_of_days = 30 ;
        $date_of_expiry = time() + 60 * 60 * 24 * $number_of_days ;
        setcookie('token', $sessionToken->refresh_token, $date_of_expiry);
    }
}
else if (isset($_COOKIE["token"])) {//if we don't have a session we will grab it from the cookie
    $client->refreshToken($_COOKIE["token"]);//update token
}

if ($client->getAccessToken()) {
    $calList = $cal->calendarList->listCalendarList();
    print "<h1>Calendar List</h1><pre>" . print_r($calList, true) . "</pre>";
    $_SESSION['token'] = $client->getAccessToken();
} else {
    $authUrl = $client->createAuthUrl();
    print "<a class='login' href='$authUrl'>Select a calendar!</a>";
}