The OAuth Google+ API stores and retrieves tokens after the first login and authorization

I read the documentation, examples and guides on using the Google API, I already have a mini-application that shows your latest actions and information, but I use sessions to store the token.

My question is, how can I store and retrieve a token from the database, so that when a user (who has already registered) clicks "login", he can immediately use the API without re-authorization? Note that I used this example as a starting point for my gadget.

Here's the code snippet:

$client = new apiClient();
$client->setApplicationName(APP_NAME);
$client->setClientId(CLIENT_ID);
$client->setClientSecret(CLIENT_SECRET);
$client->setRedirectUri(REDIRECT_URL);
$client->setDeveloperKey(DEV_KEY);

$plus = new apiPlusService($client);
$google_userinfo = new apiOauth2Service($client);

$message = "";

// In a real application this would be stored in a database, and not in the session!
if (isset($_SESSION['token']))
  $client->setAccessToken($_SESSION['token']);

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

if (isset($_GET['code'])) {
   $client->authenticate();
  // In a real application this would be stored in a database, and not in the session!
  $_SESSION['token'] = $client->getAccessToken();
  header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}
...
 //Somewhere here, I added a function that ties $_SESSION['token'] to the user info.
...
<form action="" method="post" id="form1" name="form1">
   <fieldset>
      <div id="main-url-section" style="width: 50%;margin: 0px auto;text-align: center;">
         <?php
            $authUrl = $client->createAuthUrl();
            print "<p><a class='login' href='$authUrl'>Log me in!</a></p>";
         ?>                                 
      </div>
    </fieldset>
</form>

Thank you so much for your help!

Hi,

John

+5
source share
2 answers

, Google , , :

$client->setAccessType("online");
$client-> setApprovalPrompt("auto");

: , OAuth. , Google , , . .

PHP . . , OAuth refresh, . . PHP .

. . , , . , , . , .

+9

, , .

, Google Auth, Auth. , , Google.

, , ( , ), , , , .

, (, , ) - , php: $client->setAccessType("offline");.

, , , , .

, , .

, , Amos

0

All Articles