如何在未登录谷歌的情况下显示谷歌分析嵌入式报告

时间:2015-09-24 06:00:15

标签: javascript google-analytics

我有以下代码,它的工作正常:

<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>

仅在我登录Google时才有效。但我想要的就是即使我没有登录也能工作。如何实现? 你能否提供一步一步的处理方法?

3 个答案:

答案 0 :(得分:1)

Google Analytics演示&amp;工具站点提供了有关如何在Embed API的服务器端授权演示中执行此操作的分步方法:
https://ga-dev-tools.appspot.com/embed-api/server-side-authorization/

答案 1 :(得分:1)

<?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());
?>

答案 2 :(得分:0)

您可以通过向gapi.analytics.auth.authorize()添加acces_token来解决此问题。我们可以通过在Google Analytics中创建服务帐户来获取access_token。 https://ga-dev-tools.appspot.com/embed-api/server-side-authorization/

通过运行波纹管java代码,您将获得访问令牌

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;
}

创建服务帐户后,您将获得服务帐户邮件ID,您必须在用户管理中添加此邮件ID,并且必须在您的帐户中启用google analytics api。