Search code examples
phpoauth-2.0google-api-php-clientgoogle-client

Unable to get the refresh_token from google Oauth response


I am new to google client auth. I am trying to upload a file to my google drive using this php google client downloaded from here https://github.com/google/google-api-php-client

public function oauth2callback(){
        set_include_path(get_include_path() . PATH_SEPARATOR . ROOT .DS. "vendors");
        require_once 'Google/Client.php';
        $client = new Google_Client();

        $client->setClientId('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');
        $client->setClientSecret('xxxxxxxxxxxxxxxxx');
        $client->setRedirectUri('http://example.com/auth/oauth2callback');
        $client->setScopes(array('https://www.googleapis.com/auth/drive'));
        $client->setState('offline');
        $authUrl = $client->createAuthUrl();
        if (isset($_GET['code'])) {
                $authCode = trim($_GET['code']); 
                $accessToken = $client->authenticate($authCode);
                print_r($accessToken);
                $client->setAccessToken($accessToken);
        }
        if ($client->getAccessToken()) {
            // To do
        }else{
            $authUrl = $client->createAuthUrl();
            echo "<a href='$authUrl'>Login Now</a>";
        }
    }

In the response, i only recieve this

{"access_token":"ya29.eQAeXvi4c5CAGRwAAAAKr55Tljr6z_GpdfjyY0xbrD15XGikNRL-D724Hx1L_g","token_type":"Bearer","expires_in":3600,"created":1410085058}

without any refresh token.

I just want to get the refresh token from the response for later use.

I also followed this question

Set the state to offline, revoked all the previous access that belonged to this app, even tried with fresh new account/apps.. but never received refresh token..

Please guys help me out...


Solution

  • I was missing the access_type=offline..

    So, adding

    $client->setAccessType('offline');
    

    fixed the problem.