google analytics custom plugin getting error invalid grant

$client = new Google_Client();
            $client->setAuthConfigFile(plugin_dir_url( __FILE__ ) . '/client_secrets.json');
            $client->setRedirectUri('urn:ietf:wg:oauth:2.0:oob');
            $client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);
            $client->setIncludeGrantedScopes(true);
            $client->setAccessType('offline');
            $client->revokeToken();
            $auth_url = $client->createAuthUrl();

using a popup authentication with javascript and then

if (!isset($_SESSION['access_token'])) {
        //$client->authenticate($_GET['code']);
      
        if($client->isAccessTokenExpired()){
            $client->authenticate($this->options['authenication_code']);
            
            $refreshToken = $client->getRefreshToken();
            $client->refreshToken( $refreshToken );
            $accessToken = $client->getAccessToken();
        }
        $_SESSION['access_token'] = $accessToken ? $accessToken : $refreshToken;
    }

After authenticating It is giving the result ,but while using another session to get the data it is showing errors different error in different circumstances no clear idea

Read More

Google_Auth_Exception’ with message ‘Error fetching OAuth2 access
token, message: ‘invalid_grant: Invalid code.’

Google_Auth_Exception’ with message ‘Error fetching OAuth2 access
token, message: ‘invalid_grant’ if checked after some time

Google_Auth_Exception’ with message ‘Error fetching OAuth2 access
token, message: ‘invalid_grant: Code was already redeemed.’ authenticated closed the browser and try with another browser

This is my 4th week on this but still unable to get things correctly.

I have gone through certain posts but no luck

1.Unable to refresh OAuth2 token in PHP, invalid grant

2.authenticate() accepts invalid tokens

3.Getting “invalid_grant” error on token refresh

4.Problem in refreshing access token

5.Why do I keep catching a Google_Auth_Exception for invalid_grant?

6.How to refresh token with Google API client?

7.Google OAuth2 – access token & refresh token -> invalid_grant/Code was already redeemed

8.Use OAuth Refresh Token to Obtain New Access Token – Google API

9.Using refresh_token for Google OAuth 2.0 returns http 400 bad request

and some more if I need to post more codes or anything else please let me know.

full code

Related posts