简体   繁体   English

如何获取访问令牌以获取谷歌分析数据?

[英]How can I get the access token to get google analytics Data?

I am using Google Analytics to get the data for my website.我正在使用 Google Analytics 来获取我网站的数据。 I have tested the queries on query explorer.我已经在查询资源管理器上测试了查询。 But I am unable to implement it in the code with OAuth.但是我无法使用 OAuth 在代码中实现它。 I need a access token to run my query, but my problem is I am unable to get the access token.我需要一个访问令牌来运行我的查询,但我的问题是我无法获得访问令牌。 Can anyone guide me through this.任何人都可以指导我完成这个。 Can anyone explain the relation between google developer console's to analytics account.谁能解释谷歌开发者控制台与分析帐户之间的关系。 Please refer to some implementation documents.请参考一些实现文档。

Assuming this is your own data that you want to access and you have access to the Google Analytics account website.假设这是您要访问的自己的数据,并且您可以访问 Google Analytics 帐户网站。 I recommend you use a service account.我建议您使用服务帐户。 Hello Analytics API Java 你好分析 API Java

The Google Developer console is where you register your application with Google it has no relation to your Google Analytics account what so ever.谷歌开发者控制台是你向谷歌注册你的应用程序的地方,它与你的谷歌分析帐户没有任何关系。

Again I recommend you go with a service account and create service account credentials on the Google Developer console.我再次建议您使用服务帐户并在 Google Developer Console 上创建服务帐户凭据。 Take the service account email address add it as a user on your google analytics admin section at the account level give it read access it must be at the account level.将服务帐户电子邮件地址添加为帐户级别的 google 分析管理部分的用户,授予它读取权限,它必须在帐户级别。 This will allow the service account to read your google analytics data.这将允许服务帐户读取您的谷歌分析数据。

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;

import com.google.api.services.analytics.Analytics;
import com.google.api.services.analytics.AnalyticsScopes;
import com.google.api.services.analytics.model.Accounts;
import com.google.api.services.analytics.model.GaData;
import com.google.api.services.analytics.model.Profiles;
import com.google.api.services.analytics.model.Webproperties;

import java.io.File;
import java.io.IOException;


/**
 * A simple example of how to access the Google Analytics API using a service
 * account.
 */
public class HelloAnalytics {


  private static final String APPLICATION_NAME = "Hello Analytics";
  private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
  private static final String KEY_FILE_LOCATION = "/path/to/your.p12";
  private static final String SERVICE_ACCOUNT_EMAIL = "<SERVICE_ACCOUNT_EMAIL>@developer.gserviceaccount.com";
  public static void main(String[] args) {
    try {
      Analytics analytics = initializeAnalytics();

      String profile = getFirstProfileId(analytics);
      System.out.println("First Profile Id: "+ profile);
      printResults(getResults(analytics, profile));
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  private static Analytics initializeAnalytics() throws Exception {
    // Initializes an authorized analytics service object.

    // Construct a GoogleCredential object with the service account email
    // and p12 file downloaded from the developer console.
    HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    GoogleCredential credential = new GoogleCredential.Builder()
        .setTransport(httpTransport)
        .setJsonFactory(JSON_FACTORY)
        .setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
        .setServiceAccountPrivateKeyFromP12File(new File(KEY_FILE_LOCATION))
        .setServiceAccountScopes(AnalyticsScopes.all())
        .build();

    // Construct the Analytics service object.
    return new Analytics.Builder(httpTransport, JSON_FACTORY, credential)
        .setApplicationName(APPLICATION_NAME).build();
  }


  private static String getFirstProfileId(Analytics analytics) throws IOException {
    // Get the first view (profile) ID for the authorized user.
    String profileId = null;

    // Query for the list of all accounts associated with the service account.
    Accounts accounts = analytics.management().accounts().list().execute();

    if (accounts.getItems().isEmpty()) {
      System.err.println("No accounts found");
    } else {
      String firstAccountId = accounts.getItems().get(0).getId();

      // Query for the list of properties associated with the first account.
      Webproperties properties = analytics.management().webproperties()
          .list(firstAccountId).execute();

      if (properties.getItems().isEmpty()) {
        System.err.println("No Webproperties found");
      } else {
        String firstWebpropertyId = properties.getItems().get(0).getId();

        // Query for the list views (profiles) associated with the property.
        Profiles profiles = analytics.management().profiles()
            .list(firstAccountId, firstWebpropertyId).execute();

        if (profiles.getItems().isEmpty()) {
          System.err.println("No views (profiles) found");
        } else {
          // Return the first (view) profile associated with the property.
          profileId = profiles.getItems().get(0).getId();
        }
      }
    }
    return profileId;
  }

  private static GaData getResults(Analytics analytics, String profileId) throws IOException {
    // Query the Core Reporting API for the number of sessions
    // in the past seven days.
    return analytics.data().ga()
        .get("ga:" + profileId, "7daysAgo", "today", "ga:sessions")
        .execute();
  }

  private static void printResults(GaData results) {
    // Parse the response from the Core Reporting API for
    // the profile name and number of sessions.
    if (results != null && !results.getRows().isEmpty()) {
      System.out.println("View (Profile) Name: "
        + results.getProfileInfo().getProfileName());
      System.out.println("Total Sessions: " + results.getRows().get(0).get(0));
    } else {
      System.out.println("No results found");
    }
  }
}

Code ripped directly from Hello Analytics API: Java quickstart for service accounts直接从Hello Analytics API 中提取的代码:服务帐户的 Java 快速入门

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM