0

.NETアプリケーションからGoogleAnalyticsAPIに接続しようとしています。これが私が思いついたコードです:

Public Function GetData() As String   
    Dim client As AssertionFlowClient = New AssertionFlowClient(GoogleAuthenticationServer.Description,
                                                                New X509Certificate2("C:\Users\xxxxx\privatekey.p12", "notasecret",
                                                                                     X509KeyStorageFlags.Exportable Or X509KeyStorageFlags.MachineKeySet)) With {
                                                                .Scope = "analytics.readonly",
                                                                .ServiceAccountId = "xxxxx@developer.gserviceaccount.com"}
    Dim authenticator As OAuth2Authenticator(Of AssertionFlowClient) = New OAuth2Authenticator(Of AssertionFlowClient)(client, AddressOf AssertionFlowClient.GetState)
    Dim service As AnalyticsService = New AnalyticsService(authenticator)

    Dim profileId As String = "ga:xxxxx"
    Dim startDate As String = "2013-02-15"
    Dim endDate As String = "2013-02-20"
    Dim metrics As String = "ga:visitors"

    Dim request As DataResource.GaResource.GetRequest = service.Data.Ga.Get(profileId, startDate, endDate, metrics)
    Dim data As GaData = request.Fetch()

    Return data.ToString()
End Function

私の問題は、このメソッドを押すrequest.Fetch()と、「ダイレクトメッセージの送信中または応答の取得中にエラーが発生しました」という例外が表示されることです。内部例外は、「リモートサーバーがエラーを返しました:(400)不正な要求」です。

このエラーは明らかにかなりあいまいです。Googleのエラーコードのドキュメントによると、400 Bad Requestは、入力パラメータがどういうわけか意味をなさないことを示しています。誰かが私のコードのパラメータを見て問題を診断できますか?そうでなければ、どうすれば自分が間違っていることを追跡し始めることができますか?エラーに表示される情報は事実上ありません。

(少なくとも、認証段階を通過しました...私は思います。)

4

1 に答える 1

1

この答えから広範囲に借りて、私が思いついた解決策はこれです:

Imports System.Security.Cryptography.X509Certificates
Imports Google.Apis.Analytics.v3
Imports Google.Apis.Analytics.v3.Data
Imports Google.Apis.Authentication.OAuth2
Imports Google.Apis.Authentication.OAuth2.DotNetOpenAuth
Imports System.Security.Cryptography

Public Class GoogleAnalytics

    Private _profileId As String
    Private _service As AnalyticsService

    ''' <summary>
    ''' Creates an instance of the Google Analytics interface
    ''' </summary>
    ''' <param name="profileId">The Google Analytics profile ID, in the form "ga:123456789". This is *not* the same as the ID number used in the GA JavaScript to initialize the tracking! The number you want is in Google Analytics > Admin > (your profile) > Profile Settings.</param>
    ''' <param name="serviceAccountId">The e-mail address of the Service Account that will access the API. These accounts can be generated from the Google API Console and then authorized by adding the e-mail address to the list of authorized users in Google Analytics.</param>
    ''' <param name="privateKeyPath">The path to the private-key (.p12) file from Google.</param>
    ''' <param name="certificatePassword">The password for the private key. Probably "notasecret".</param>
    ''' <remarks>Once created, this GoogleAnalytics object can be used to make an arbitrary number of requests.</remarks>
    Public Sub New(profileId As String, serviceAccountId As String, privateKeyPath As String, certificatePassword As String)
        Dim cert As X509Certificate2 = New X509Certificate2(privateKeyPath, certificatePassword, X509KeyStorageFlags.Exportable Or X509KeyStorageFlags.MachineKeySet)
        Dim client As AssertionFlowClient = New AssertionFlowClient(GoogleAuthenticationServer.Description, cert) With {.Scope = "https://www.googleapis.com/auth/analytics.readonly",
                                                                                                                        .ServiceAccountId = serviceAccountId}
        Dim authenticator As OAuth2Authenticator(Of AssertionFlowClient) = New OAuth2Authenticator(Of AssertionFlowClient)(client, AddressOf AssertionFlowClient.GetState)
        _service = New AnalyticsService(authenticator)

        _profileId = profileId
    End Sub

    Public Function GetData(startDate As String, endDate As String, metrics As String, dimensions As String, Optional filters As String = Nothing) As GaData
        Dim request As DataResource.GaResource.GetRequest = _service.Data.Ga.Get(_profileId, startDate, endDate, metrics)
        request.Dimensions = dimensions

        If filters IsNot Nothing Then
            request.Filters = filters
        End If

        Return request.Fetch()
    End Function

End Class

これは、次のように使用できるスタンドアロンクラスです。

Dim analytics As New GoogleAnalytics("ga:12345678", "123456789012@developer.gserviceaccount.com", "C:\privatekey.p12", "notasecret")
Dim data as GaData = analytics.GetData(DateTime.Now.AddDays(-30).ToString("yyyy-MM-dd"),
                                       DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd"),
                                       "ga:totalEvents",
                                       "ga:eventCategory,ga:eventAction")

これで私が見つけた最大の落とし穴はプロファイルIDでした。これは、GoogleのJavascriptトラッキングコードに渡すID番号ではありません。代わりに、Google Analytics> Admin>(プロフィール)>ProfileSettingsにある番号です。これが他の誰かに役立つことを願っています!

于 2013-03-14T16:26:47.087 に答える