使用v3和C#的Google Analytics报告数据

时间:2013-12-24 19:36:35

标签: c#-4.0 google-analytics-api

我正在尝试使用API​​ v3

访问Google Analytics信息
        // This is the physical path to the key file you downloaded when you created your Service Account
    String key_file = @"C:\Users\path\XXXXX-privatekey.p12";

    // Is the "Email Address", not the "Client ID" one!!!
    String client_id = "0000000-xxxxx@developer.gserviceaccount.com";

    // Probably the password for all is "notasecret"
    String key_pass = "notasecret";


       private void button1_Click(object sender, System.EventArgs e)
    {
        try
        {
            String scope_url = "https://www.googleapis.com/auth/" + Google.Apis.Analytics.v3.AnalyticsService.Scopes.Analytics.ToString().ToLower();
            //scope_url = "https://www.googleapis.com/auth/analytics";
            //scope_url = "https://www.googleapis.com/auth/analytics.readonly";

            AuthorizationServerDescription desc = GoogleAuthenticationServer.Description;
            X509Certificate2 key = new X509Certificate2(key_file, key_pass, X509KeyStorageFlags.Exportable);

            AssertionFlowClient client = new AssertionFlowClient(desc, key) { ServiceAccountId = client_id, Scope = scope_url };
            OAuth2Authenticator<AssertionFlowClient> auth = new OAuth2Authenticator<AssertionFlowClient>(client, AssertionFlowClient.GetState);                
            AnalyticsService gas = new AnalyticsService(auth);

            // Creating our query
            DataResource.GaResource.GetRequest r = gas.Data.Ga.Get("ga:1983192", "2013-11-01", "2013-11-30", "ga:visits,ga:pageviews");
            //r.Dimensions = "ga:date";                

            //d: Execute and fetch the results of our query
            GaData d = r.Fetch();

            // At this point, d should contain the number of visitors you got between dates
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

    }

但我总是得到下一个错误

  

Google.Apis.Requests.RequestError   用户没有任何Google Analytics帐户。 [403]   错误[       消息[用户没有任何Google Analytics帐户。]位置[ - ]原因[insufficientPermissions]域[global]   ]

我在https://cloud.google.com/console中创建了应用 你可以看到创建凭据 在控制台上拥有有效的Google Analytics帐户和API授权部分。

会发生什么?

1 个答案:

答案 0 :(得分:1)

最后!!答案就在这里!!! Google Analytics throws 403 error

如果您使用网络界面登录Google Analytics,您会在网址中看到以下模式:

/a12345w654321p9876543/

p后面的数字是AccountID,所以

DataResource.GaResource.GetRequest r = gas.Data.Ga.Get("ga:9876543", "2013-11-01", "2013-11-30", "ga:visits,ga:pageviews");