title: Google API Refresh Token
body: <p>I have been trying for the last few hours to print my refresh_token from the initial Google API call (even after de-authorizing and re-authorizing as others have suggested doing) but I still am not having any luck...the API works as expected but I want to set up refreshing functionality so my user does not lose access after token expires (resulting in errors).</p>
  
  <p>Currently, the below code sets $_SESSION['refresh_token'] to null.</p>
  
  <p>Any help would be greatly appreciated as I have been banging my head against the keyboard for quite some time...</p>
  
  <pre><code>private function googleAnalyticsClient(){
      App::import('Vendor', 'google-api-php-client', array('file' =&gt; 'autoload.php'));
      $client = new Google_Client();
      $client-&gt;setAuthConfigFile(__DIR__ . '/client_secrets.json'); 
      $client-&gt;setAccessType('offline');
      $client-&gt;setApprovalPrompt('force');
      $client-&gt;addScope('https://www.googleapis.com/auth/analytics.readonly');
  
      if (isset($_SESSION['access_token']) &amp;&amp; $_SESSION['access_token']) {
          $client-&gt;setAccessToken($_SESSION['access_token']);
          $analytics = new Google_Service_Analytics($client);
          return $analytics;
      } else {
        $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/dashboard/oauthcallbacks';
        header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
      }
  }
  
  public function getOauth()
  {
      App::import('Vendor', 'google-api-php-client', array('file' =&gt; 'autoload.php'));
  
      // Create the client object and set the authorization configuration
      // from the client_secrets.json you downloaded from the Developers Console.
      $client = new Google_Client();
      $client-&gt;setAuthConfigFile(__DIR__ . '/client_secrets.json');
      $client-&gt;setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/dashboard/oauthcallbacks');
      $client-&gt;addScope(Google_Service_Analytics::ANALYTICS_READONLY);
  
      // Handle authorization flow from the server.
      if (! isset($_GET['code'])) {
        $auth_url = $client-&gt;createAuthUrl();
        header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
      } else {
        $client-&gt;authenticate($_GET['code']);
        $_SESSION['access_token'] = $client-&gt;getAccessToken();
        $_SESSION['refresh_token'] = $client-&gt;getRefreshToken();
        $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/dashboard/tpstats';
        header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
      }
  }
  </code></pre>