1

I am using google api to get access token and refresh token. but my question is how to use this refresh token to get new access token then i can again update users detail. I have all credentials and i'm getting first access token and refresh token which i stored into database. i want to get new access token and again i have to store into database. how can i do this. i'm trying this..i don't know it is correct or not..

 if (isset($_GET['code'])) {
 $client->setAccessType('offline');

$client->authenticate($_GET['code']);
$gClient->setAccessType('offline');
$_SESSION['token'] = $client->getAccessToken();


$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
 header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
return;
}

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

if($client->isAccessTokenExpired()) 
{
$client->setAccessType('offline');

   if (isset($_GET['code'])) 
   {
   $client->authenticate();
   $_SESSION['access_token'] = $client->getAccessToken();
   }

  if (isset($_REQUEST['logout']))
  {
  unset($_SESSION['token']);
  $client->revokeToken();
  }
  ?>
   <!doctype html>
   <html>
  <head><meta charset="utf-8"></head>
   <body>
   <header><h1>Get Token</h1></header>
   <?php
   if ($client->getAccessToken()) {
    $_SESSION['token'] = $client->getAccessToken();
    $token = json_decode($_SESSION['token']);

    echo "Access Token = " . $token->access_token . '<br/>';
    echo "Refresh Token = " . $token->refresh_token . '<br/>';
    echo "Token type = " . $token->token_type . '<br/>';
    echo "Expires in = " . $token->expires_in . '<br/>';
    echo "ID Token = " . $token->id_token . '<br/>';
    echo "Created = " . $token->created . '<br/>';
    echo "<a class='logout' href='?logout'>Logout</a>";
    } else {
    $authUrl = $client->createAuthUrl();
    print "<a class='login' href='$authUrl'>Connect Me!</a>";
  }
  ?>
 </body>
 </html>

will i write another file for refresh the access token or i can do on a single file.

sakura14
  • 29
  • 6
  • What did you try so far getting your goal? any code? error? effort? Please post you complete code. – Keep Coding Mar 30 '15 at 11:28
  • possible duplicate of [How to refresh token with Google API client?](http://stackoverflow.com/questions/9241213/how-to-refresh-token-with-google-api-client) – Jigar Mar 30 '15 at 11:31
  • just check now..updated,,using this i'm getting access token and refresh token using this code..but access token expired after sometimes so i have to refresh access token using refresh token.. – sakura14 Mar 30 '15 at 11:34
  • jigar i'm not getting any solution thats why i'm asking..if u have any solution thn suggest me. – sakura14 Mar 30 '15 at 11:39
  • @neha what problem you are facing?? Not getting the refresh token or you want o generate the refresh token in the same page?? – Nishant Solanki Mar 30 '15 at 12:07
  • no nishant..i'm getting both refresh token n access token but access token expire after sometime ,i want to get new access token and i don't know how to generate new access token through refresh token,if u have any idea or code then tell me..it's very great for me if it will be done on another seprate php file. – sakura14 Mar 30 '15 at 12:15

2 Answers2

1

After getting token first time :

$code = FIRST_TIME_TOKEN;

$client = new Google_Client();
                $client->setClientId(self::OAUTH2_CLIENT_ID);
                $client->setClientSecret(self::OAUTH2_CLIENT_SECRET);
                $client->setScopes(SCOPE_URL);
                $client->setAccessType('offline');
                $redirect = filter_var(REDIRECT_URL,
                  FILTER_SANITIZE_URL);
                $client->setRedirectUri($redirect);

                $youtube = new Google_Service_YouTube($client); // You can change it

                if (isset($code)) {

                      if (strval($_SESSION['state']) !== strval($_GET['state'])) {
                        throw new \Exception('Session expired , Please refresh the page');
                      }

                      $client->authenticate($code);
                      $_SESSION['token'] = $client->getAccessToken();
                      header('Location: ' . $redirect);
                }

                $completeYoutubeResponse=json_decode($_SESSION['token']); 
                if(!isset($completeYoutubeResponse->access_token) || !isset($completeYoutubeResponse->refresh_token)) { 

                    throw new \Exception('This youtube account is used by some other user');
                } else {

$accessToken=$completeYoutubeResponse->access_token;   // We need to save it in db

$refreshToken=$completeYoutubeResponse->refresh_token;   // We need to save it in db

                     return (isset($completeYoutubeResponse) ? $completeYoutubeResponse : null);
parveen
  • 495
  • 3
  • 13
  • praveen i have 1 doubt..in $code object..what i have to write thier..my old code where i'm getting aceess token or user's access token only their. – sakura14 Mar 30 '15 at 12:49
  • Welcome , and do accept answer so that it helps other :) – parveen Mar 31 '15 at 05:33
  • but parveen it showing me error.. Notice: Undefined index: state in /opt/lampp/htdocs/google/access_token.php on line 26 Notice: Undefined index: state in /opt/lampp/htdocs/google/access_token.php on line 26 Fatal error: Uncaught exception 'Google_AuthException' with message 'Error fetching OAuth2 access token, message: 'invalid_grant'' in /opt/lampp/htdocs/google/src/auth/Google_OAuth2.php:113 Stack trace: #0 /opt/lampp/htdocs/google/src/Google_Client.php(131): Google_OAuth2->authenticate(Array, 'ya29.RwGuDqqTIu...') #1 /opt/lampp/htdocs/google/access_token.php(30): Google_Client->authentic – sakura14 Mar 31 '15 at 05:37
  • actually if i comment $code line and replace your (if (isset($code))), to this (if (isset($_GET['code']) then i'm getting access token..so that token is generated from refresh token or this is a first time access token..i didnt understand.. – sakura14 Mar 31 '15 at 05:48
  • i don't have enough reputation,so thats why i can't vote sorry..:-) – sakura14 Apr 01 '15 at 10:14
0

Use:

$token = json_decode($_SESSION['token']);
$client->refreshToken($token->refresh_token);
$_SESSION['token'] = $client->getAccessToken();
Hans Z.
  • 41,402
  • 9
  • 80
  • 105
  • thanks Hans for ur reply..actually problem is that,i'm storing refresh token and access token in database so that i can update the users details anytime..thats why i have need to refresh the token ..can you give me detail about how to generate access token in seperate php file. – sakura14 Mar 30 '15 at 12:30
  • what do you want to generate? – Hans Z. Mar 30 '15 at 12:32
  • hans ..i want to get new access token n also refresh token. – sakura14 Mar 30 '15 at 12:50
  • 1
    edited the code so it shows how to access the newly obtained access token and store it in the session.; you can't generate a new refresh token, you have to use the one that was returned to you in the first call, until the end user revokes access for your app and re-allows it – Hans Z. Mar 30 '15 at 13:24