John Smith
John Smith

Reputation: 75

(PHP) Is there a way to access refresh token from access token?

I am using console.cloud.google. I generated client id and secret, saved it to json but it seems I can't access refresh token.

/**
 * @Route("/oauth2callback", name="oauth2-callback")
 * @Method("GET")
 */
public function index(Request $request)
{
    $code = $request->query->get('code');

    $client = new Google\Client();
    $client->setAuthConfig(__DIR__ . '/../AdsApi/client_secrets.json');
    $client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback');
    $client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);

    // Handle authorization flow from the server.
    if (! isset($code)) {
        $auth_url = $client->createAuthUrl();
        header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
    } else {
       $client->authenticate($code);

       $_SESSION['access_token'] = $client->getAccessToken();
       $_SESSION['refresh_token'] = $client->getRefreshToken();
       $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/';
       header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
    }

    return new Response();
}

The function getAccessToken returns an array, but getRefreshToken returns null. Is there a way to fix it?

Thanks.

Upvotes: 1

Views: 248

Answers (1)

John Smith
John Smith

Reputation: 75

Okay, found the problem. Google will not send another refresh token if it has been already sent (first time). Created a new project and it is working.

Upvotes: 1

Related Questions