title: How to fetch google analytics realtime activeUsers in php?
body: <p>I downloaded API files from
  <a href="https://github.com/google/google-api-php-client" rel="noreferrer">https://github.com/google/google-api-php-client</a>
  and tried below code...</p>
  
  <pre><code>$client-&gt;setApplicationName("Analytics");
  $client-&gt;setDeveloperKey("key");
  $service = new Google_Service_Analytics($client);
  
  $optParams = array(
      'dimensions' =&gt; 'rt:medium');
  
  try {
    $results = $service-&gt;data_realtime-&gt;get(
        'ga:profileid',
        'rt:activeUsers',
        $optParams);
    // Success.
  } catch (apiServiceException $e) {
    // Handle API service exceptions.
    $error = $e-&gt;getMessage();
  }
  print_r($results);
  </code></pre>
  
  <p>It shows an error (401) Login Required'</p>
  
  <p>When i tried the call from <a href="https://console.developers.google.com/project/apps~rational-photon-578/apiui/api/analytics/method/analytics.data.realtime.get" rel="noreferrer">https://console.developers.google.com/project/apps~rational-photon-578/apiui/api/analytics/method/analytics.data.realtime.get</a></p>
  
  <p>I got the required realtime users belongs profileid.</p>
  
  <p>So how can i implement a login process (Without going to google site) in this ?</p>
  
  <p>I tried the below code...</p>
  
  <pre><code>$client_id              = 'xxxxxxxxxxxxxxx';
  $service_account_name   = 'xxxxxxxxxxxxxxxx@developer.gserviceaccount.com';
  $key_file_location      = 'location of .p12 keyfile';
  
  $client = new Google_Client();
  $client-&gt;setApplicationName("Client_Library_Examples");
  
  if (isset($_SESSION['service_token'])) {
  $client-&gt;setAccessToken($_SESSION['service_token']);
  }
  
  $key = file_get_contents($key_file_location);
  $cred = new Google_Auth_AssertionCredentials(
  $service_account_name,
  array('https://www.googleapis.com/auth/analytics'),
  $key
  );
  
  $client-&gt;setAssertionCredentials($cred);
  if($client-&gt;getAuth()-&gt;isAccessTokenExpired()) {
  $client-&gt;getAuth()-&gt;refreshTokenWithAssertion($cred);
  } 
  
  $_SESSION['service_token'] = $client-&gt;getAccessToken();
  echo $_SESSION['service_token'];
  $service = new Google_Service_Analytics($client);
  
  
  $optParams = array(
  'dimensions' =&gt; 'rt:medium');
  
  
  try {
  $results = $service-&gt;data_realtime-&gt;get(
    'ga:profileid',
    'rt:activeUsers',
    $optParams);
  // Success.
  } catch (apiServiceException $e) {
  // Handle API service exceptions.
  $error = $e-&gt;getMessage();
  }
  print_r($results);
  </code></pre>
  
  <p>Here i am getting the access_token and details...but the analytics data fetching fails because an error "Insuffient permission"</p>
  
  <p>I got the results when i made test from google console with mentioned profile id.</p>