barryhennessy / google-api-php-client

Automatically exported from code.google.com/p/google-api-php-client
Apache License 2.0
0 stars 0 forks source link

Problem in refreshing access token #94

Closed GoogleCodeExporter closed 8 years ago

GoogleCodeExporter commented 8 years ago
Hi,

I am facing problem in refreshing the access token. Can you please tell me what 
code I need to implement for refreshing the token? OR the api itself refreshes 
it. Please clarify.

Thanks,
Chitrangada

Original issue reported on code.google.com by chitrang...@gmail.com on 5 Mar 2012 at 5:36

GoogleCodeExporter commented 8 years ago
The client library does indeed refresh the access token for you. What type of 
issue are you seeing?

Original comment by chirags@google.com on 5 Mar 2012 at 4:46

GoogleCodeExporter commented 8 years ago
Thank you Chirag.

I want to refresh the token in certain condition. Now I have used the code at 
corresponding place. But can you please tell me when the library refreshes it?

Original comment by chitrang...@gmail.com on 6 Mar 2012 at 4:18

GoogleCodeExporter commented 8 years ago
The client library will refresh the access token (if needed) *before* making an 
authenticated API request.
This happens if the access token is older than 3600 seconds.

Original comment by chirags@google.com on 9 Mar 2012 at 9:14

GoogleCodeExporter commented 8 years ago
[deleted comment]
GoogleCodeExporter commented 8 years ago
I think library isn't refreshes the token for me. If it does so then why I am 
getting this error?

ERROR: Fatal error: Uncaught exception 'apiAuthException' with message 'Error 
fetching OAuth2 access token, message: 'invalid_grant''.......

Original comment by chitrang...@gmail.com on 10 Mar 2012 at 4:44

GoogleCodeExporter commented 8 years ago
You'll get the invalid_grant error when you try to use the same authorization 
code. (You get this code when you're redirected from google back to your 
application)

The sample applications show how you can use the authorization code only once.
if (isset($_GET['code'])) {
  $client->authenticate();
  $_SESSION['access_token'] = $client->getAccessToken();
  header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']); // Strip the authorization code
}

The full example is available here:
http://code.google.com/p/google-plus-php-starter/

Original comment by chirags@google.com on 10 Mar 2012 at 4:57

GoogleCodeExporter commented 8 years ago
Hey Chirag,

you exactly included the piece of code which I think will not work, when served 
from https !
Sent it to Chris before, rewrote it to:

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

 if(isset($_SERVER['HTTPS'])){ $_PROT = 'Location: https://'; } else { $_PROT = 'Location: http://'; } 
  header($_PROT . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}

Original comment by sebila...@googlemail.com on 25 Mar 2012 at 6:37

GoogleCodeExporter commented 8 years ago
i'm having the same issue. i'm using the HelloAnalyticsApi.php tutorial 
(https://developers.google.com/analytics/resources/tutorials/hello-analytics-api
), and have everything working great. The script successfully requests the 
permission from Google, returns a code, exchanges it for an access token, and 
then i'm able to query the service and receive data for my application.

However, when the browser is closed or session cleared, I have to 
re-authenticate everytime. I added the following to the HelloAnalyticsApi.php:
$client->setAccessType('offline');

When checking the access token, it does indeed include a refresh token. I've 
got all the pieces here but just need to put it together. I found the following 
explanation of how to use the refresh token 
(https://developers.google.com/accounts/docs/OAuth2WebServer#refresh) but this 
doesn't include instructions on how to use it with the google-api-php-client.

Original comment by MBStrate...@gmail.com on 26 Aug 2012 at 6:30

GoogleCodeExporter commented 8 years ago
this turned out to be more simple than i had anticipated. starting with the 
hello analytics api, i added the following code and it appears to be able to 
connect now without re-authenticating.

// begin custom code
$client->setAccessType('offline');

if (isset($_SESSION['token'])) {
    // echo $_SESSION['token'];
    echo '<br />';
    echo '<br />';
    $authObj = json_decode($_SESSION['token']);
    $accessToken = $authObj->access_token;
    $refreshToken = $authObj->refresh_token;
    $tokenType = $authObj->token_type;
    $expiresIn = $authObj->expires_in;
    echo 'access_token = ' . $accessToken;
    echo '<br />';
    echo 'refresh_token = ' . $refreshToken;
    echo '<br />';
    echo 'token_type = ' . $tokenType;
    echo '<br />';
    echo 'expires_in = ' . $expiresIn;
    echo '<br />';
    echo '<br />';
}

$refreshToken = '1/ewPvNg6_2toqDtCaw2bdIUhgQpGF7koqLAIurSpo4Uk';
$client->refreshToken($refreshToken);
// end custom code

Original comment by MBStrate...@gmail.com on 26 Aug 2012 at 7:39

GoogleCodeExporter commented 8 years ago
In my case : $authObj = json_decode($_SESSION['token']);
return all indicated vars but no "refresh_token" in json decoded session.

See src/auth/apiOAuht2.php function authenticate line :: 84 refresh token not 
setted 

Could you help me to have the refresh token which permit me to execute  
$client->refreshToken($refreshToken);

Original comment by ckha...@gmail.com on 3 Nov 2012 at 9:40

GoogleCodeExporter commented 8 years ago
I've been trying to use the google analytics php api with the hello api 
tutorial and there seems to be a few inconsistencies with the latest library 
(classes changed name and locations).

I've gotten my code to run up to the $client->authenticate(); call but I never 
receive a response from the authenticate function. Is the library functional? 
(version google-api-php-client-0.6.0.tar.gz)

Original comment by patricba...@gmail.com on 7 Nov 2012 at 3:01

GoogleCodeExporter commented 8 years ago
you need to set your application to $client->access_type(offline); check this 
link out for more info :
https://developers.google.com/accounts/docs/OAuth2WebServer

Original comment by karimrit...@gmail.com on 21 Nov 2012 at 2:21

GoogleCodeExporter commented 8 years ago
Hi Chirag,
Is there some way I can just destroy the token, once the user logs in. So that 
I am faced with absolutely no problems.

Thanks,
Rajat

Original comment by raj...@healthhiway.com on 22 Nov 2012 at 1:21

GoogleCodeExporter commented 8 years ago
Hi 

i am also getting same sort of error but using Google Drive API.
Please help me how can i solve it

Slim Application Error

The application could not run because of the following error:
Details
Type: ErrorException
Code: 8
Message: Use of undefined constant tokens - assumed 'tokens'
File: D:\wamp\www\PieCloud\google-api-php-client-master\dredit\utils.php
Line: 37

Original comment by cogniter...@gmail.com on 7 May 2014 at 7:21

GoogleCodeExporter commented 8 years ago
I have following issue with Google Prediction API in the server environment but 
App is perfectly working within localhost environment.

what would be the issue(s)?

Fatal error: Uncaught exception 'Google_Auth_Exception' with message 'Error 
refreshing the OAuth2 token, message: '{ "error" : "invalid_grant" }'' in 
/home/predict/public_html/predict/Google/Auth/OAuth2.php:335 Stack trace: #0 
/home/predict/public_html/predict/Google/Auth/OAuth2.php(294): 
Google_Auth_OAuth2->refreshTokenRequest(Array) #1 
/home/predict/public_html/predict/index.php(40): 
Google_Auth_OAuth2->refreshTokenWithAssertion(Object(Google_Auth_AssertionCreden
tials)) #2 {main} thrown in 
/home/predict/public_html/predict/Google/Auth/OAuth2.php on line 335

Thanks
W.P.Roshan

Original comment by SunO...@gmail.com on 18 Aug 2014 at 1:16

Attachments:

GoogleCodeExporter commented 8 years ago
Google API made us crazy, many errors in API .

Original comment by binoto8...@gmail.com on 26 Nov 2014 at 4:49

GoogleCodeExporter commented 8 years ago
after Refreshing a code the entire data remove and showing the error (Error 
fetching OAuth2 access token, message: 'invalid_grant: Code was already 
redeemed.')? how to solve this problem?

Original comment by mrhushik...@gmail.com on 18 Jun 2015 at 11:03

GoogleCodeExporter commented 8 years ago
if( Input::has('code') )
        {
            $code = Input::get('code');
            $token = $this->ga->login($code); // This goes to src/GATervice page->login function.
            $this->ga->accountsInfo();
            $report = $this->report(); // this class report function

            return view('frontend.report', compact('report'));
        }
        else{

              header('Location:'.filter_var(Config::get('ga_credentials.redirect_uri'),FILTER_SANITIZE_URL));
            //If you click on cancel button then this message will  display
            return "Invalid request parameters";    
            }
    }

$tokens = json_decode($this->client->authenticate($code));

                $user_id = Session::all()['user_id'];
                $data['access_token'] = $tokens->access_token;
                if (isset($tokens->refresh_token)) $data['refresh_token'] = $tokens->refresh_token;
                $data['expires_in'] = $tokens->expires_in;
                $data['token_type'] = $tokens->token_type;
                // $data['id_token'] = $tokens->id_token;
                $data['created'] = $tokens->created;
                $data['user_id'] = $user_id;
                $tokensObject = new gaTokens;
                $user_id = Session::all()['user_id'];

                $access_token = $tokensObject->getAccessTokenFromDb($user_id);
                if(!$access_token) $tokensObject->insert_tokens($data);

                /*if($this->client->getAuth()->isAccessTokenExpired())
                  {
                      $this->client->getAuth()->refreshTokenWithAssertion($cred);
                  }*/
                    /*dd($tokens);*/
      //header('Location:'.filter_var(Config::get('ga_credentials.redirect_uri'),FILTER_SANITIZE_URL));
                   return $data['access_token'];

Original comment by mrhushik...@gmail.com on 18 Jun 2015 at 11:17