Google API OAuth php stały dostęp
Używam Google Calendar API. To jest to, czego chcę, gdy dasz aplikacji pozwolenie, zawsze mogę korzystać z aplikacji, bez potrzeby dawania dostępu codziennie. Ciągle słyszę, że muszę zapisać token dostępu lub użyć tokenu odświeżania, aby zrobić to, co chcę zrobić.. Chodzi o to, jak ty to robisz? Jak wygląda kod? Próbowałem zapisać token w pliku cookie, ale po godzinie token dostępu wygasł. Jak utrzymać zalogowanego użytkownika?
PS: Proszę daj mi przykłady kodu z objaśnieniami.
Oto Mój kod (używając 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;
}
3 answers
Ok, po kilku dniach oczekiwania sugestia Terry ' ego Seidlera(komentarze poniżej) sprawiła, że wszystko się stało! Oto mój fragment kodu, jak automatycznie odświeżyć token dostępu bez autentykowania za każdym razem za pomocą Plików cookie.
(Uwaga: bezpieczniej jest zapisać token odświeżania w bazie danych)
This is the magic (using 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'));
}
I to wszystko! Jeśli masz jakieś pytania, zostaw komentarz poniżej, a ja odpowiem najlepiej jak potrafię. Goodluck and Zdrowie!
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
2012-09-24 07:06:12
Zamiast używania cookies i sesji należy zapisać je w bazie danych i z niej korzystać.
Podobna implementacja dla strony drupal jest w Google OAuth2 sandbox na http://drupal.org/sandbox/sadashiv/1857254 Ten moduł pozwala obsługiwać uwierzytelnianie z interfejsu administratora drupal. Możesz następnie użyć pobranego tokena dostępu z google, a następnie użyć funkcji API google_oauth2_account_load lub google_oauth2_client_get, aby uzyskać Google_Client i przenieść swój API call.
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
2012-12-24 04:23:30
Podobnie jak hope industries, ale po testach chciałem odświeżyć token tylko wtedy, gdy musiałem. Pełne źródło wystarczy zmienić klawisze itp na górze:
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>";
}
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
2014-01-25 07:53:02