簡體   English   中英

Ruby Google Analytics API錯誤

[英]Error with Ruby Google Analytics API

我正在嘗試使用其Ruby文件為的Ruby Google Analytics API Dashing小部件

require 'google/api_client'
require 'date'


    # Update these to match your own apps credentials
    service_account_email = '[YOUR SERVICE ACCOUNT EMAIL]' # Email of service account
    key_file = 'path/to/your/keyfile.p12' # File containing your private key
    key_secret = 'notasecret' # Password to unlock private key
    profileID = '[YOUR PROFILE ID]' # Analytics profile ID.

    # Get the Google API client
    client = Google::APIClient.new(:application_name => '[YOUR APPLICATION NAME]', 
      :application_version => '0.01')

    # Load your credentials for the service account
    key = Google::APIClient::KeyUtils.load_from_pkcs12(key_file, key_secret)
    client.authorization = Signet::OAuth2::Client.new(
      :token_credential_uri => 'https://accounts.google.com/o/oauth2/token',
      :audience => 'https://accounts.google.com/o/oauth2/token',
      :scope => 'https://www.googleapis.com/auth/analytics.readonly',
      :issuer => service_account_email,
      :signing_key => key)

    # Start the scheduler
    SCHEDULER.every '1m', :first_in => 0 do

      # Request a token for our service account
      client.authorization.fetch_access_token!

      # Get the analytics API
      analytics = client.discovered_api('analytics','v3')

      # Start and end dates
      startDate = DateTime.now.strftime("%Y-%m-01") # first day of current month
      endDate = DateTime.now.strftime("%Y-%m-%d")  # now

      # Execute the query
      visitCount = client.execute(:api_method => analytics.data.ga.get, :parameters => { 
        'ids' => "ga:" + profileID, 
        'start-date' => startDate,
        'end-date' => endDate,
        # 'dimensions' => "ga:month",
        'metrics' => "ga:visitors",
        # 'sort' => "ga:month" 
      })

      # Update the dashboard
      send_event('visitor_count',   { current: visitCount.data.rows[0][0] })
    end

但是,我在第二行的Undefined method '[]' for nil:NilClass遇到錯誤Undefined method '[]' for nil:NilClass 任何人都可以對這里發生的事情有所了解嗎?

編輯:我現在知道visitCount.data是NIL對象的數組。 我可以執行任何診斷以確保API正確連接嗎? 誰能說出發生這種情況的可能原因?

在直播活動之前嘗試一下

if visitCount.data.rows[0].empty?
  # assign some default
  output = -1
else
  output = visitCount.data.rows[0][0] 
end

# Update the dashboard
send_event('visitor_count',   { current: output })

好的,結果是給了我錯誤的配置文件ID。 不會出現類似“此配置文件ID不存在”之類的錯誤消息,這令人感到驚訝。 那本來會更有幫助的。 無論如何,我現在擁有正確的個人資料ID,它可以正常工作。 如果有人想知道,要找到配置文件ID,請導航至您感興趣的分析配置文件,URL的末尾帶有類似pXXXXXXXX的名稱,其中X是您的配置文件ID。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM