How to display google analytics embeded reports without being logged in into google

瘦欲@ 提交于 2019-12-08 06:45:35

问题


I have following code and it works just fine:

<script>
(function(w,d,s,g,js,fjs){
  g=w.gapi||(w.gapi={});g.analytics={q:[],ready:function(cb){this.q.push(cb)}};
  js=d.createElement(s);fjs=d.getElementsByTagName(s)[0];
  js.src='https://apis.google.com/js/platform.js';
  fjs.parentNode.insertBefore(js,fjs);js.onload=function(){g.load('analytics')};
}(window,document,'script'));
</script>



<script>


gapi.analytics.ready(function() {


 var CLIENT_ID = 'my client id goes here';

   gapi.analytics.auth.authorize({
    container: 'auth-button',
    clientid: CLIENT_ID,
  });


  /**
   * Creates a new DataChart instance showing sessions over the past 30 days.
   * It will be rendered inside an element with the id "chart-1-container".
   */
  var dataChart1 = new gapi.analytics.googleCharts.DataChart({
    query: {
      'ids': 'ga:105112893', // The Demos & Tools website view.
      'start-date': '30daysAgo',
      'end-date': 'yesterday',
      'metrics': 'ga:sessions,ga:users',
      'dimensions': 'ga:date'
    },
    chart: {
      'container': 'chart-1-container',
      'type': 'LINE',
      'options': {
        'width': '100%'
      }
    }
  });
  dataChart1.execute();

</script>

It works only if I'm logged in into google. But what I want is this to be working even if I'm not logged in. How to implement that? Could you please provide a step by step approach on how to handle that?


回答1:


The Google Analytics Demos & Tools site provides a step-by-step approach on how to do that in the Embed API's server-side authorization demo:
https://ga-dev-tools.appspot.com/embed-api/server-side-authorization/




回答2:


<?php    

// Load the Google API PHP Client Library.
require_once 'google-api-php-client/src/Google/autoload.php';

// Start a session to persist credentials.
session_start();

// Create the client object and set the authorization configuration
// from the client_secretes.json you downloaded from the developer console.
$client = new Google_Client();
$client->setAuthConfigFile('client_secrets.json');
$client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);


// If the user has already authorized this app then get an access token
// else redirect to ask the user to authorize access to Google Analytics.
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
  // Set the access token on the client.
   $client->setAccessToken($_SESSION['access_token']);

  // Create an authorized analytics service object.
  $analytics = new Google_Service_Analytics($client);



  // Get the results from the Core Reporting API and print the results.

} else {
  $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php';
  header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}


//get the access token
$myToken = json_decode($client->getAccessToken());
?>



回答3:


you can solve this by adding an acces_token to gapi.analytics.auth.authorize() we can get access_token by creating a service account in google analytics. https://ga-dev-tools.appspot.com/embed-api/server-side-authorization/

by running a bellow java code you will get the access token

public static String getToken() throws FileNotFoundException, IOException
{
    GoogleCredential credential = GoogleCredential
            .fromStream(new FileInputStream("/path-to-file/xxx-246d0882d022.json"))
            .createScoped(Collections.singleton(AnalyticsScopes.ANALYTICS_READONLY));
        credential.refreshToken();
         access_token=credential.getAccessToken();
         System.out.println(access_token);
    return access_token;
}

after creating service account you will get a service account mail id, you have to add this mail id in User Managment ,and you have to enable google analytics api in your account.



来源:https://stackoverflow.com/questions/32754370/how-to-display-google-analytics-embeded-reports-without-being-logged-in-into-goo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!