所以我使用破折号(基于sinatra的框架)创建仪表板,我需要从Analytics API获取数据,并将其显示在仪表板中。 所以我有以下ruby代码,oauth返回此错误:
{
"error" : "invalid_request",
"error_description" : "Required parameter is missing: grant_type"
}
这是代码:
require 'openssl'
OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE
require 'google/api_client'
require 'date'
# Update these to match your own apps credentials
service_account_email = ENV['chrezworld@dashing-project-1297.iam.gserviceaccount.com'] # Email of service account
key_file = 'key.p12' # File containing your private key
key_secret = 'notasecret' # Password to unlock private key
profileID = ENV['77142386'] # Analytics profile ID.
# Get the Google API client
client = Google::APIClient.new(
:application_name => ENV['dashing project'],
:application_version => '0.01'
)
visitors = []
# 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 '5s', :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')
# Execute the query
visitCount = client.execute(:api_method => analytics.data.realtime.get, :parameters => {
'ids' => "ga:" + profile_id,
'metrics' => "ga:activeVisitors",
})
visitors << { x: Time.now.to_i, y: visits.to_i }
# Update the dashboard
send_event('visitor_count_real_time', points: visitors)
end
答案 0 :(得分:0)
我不确定那个例子多大了。 Ruby API似乎记录得非常糟糕,因为它仍处于alpha阶段,所以它可能会有所改变。我最近做了一个快速的ruby示例,它适用于最新版本的API 0.9.6
首先,您要进入Google云端控制台,并为您的服务帐户导出JSON密钥文件。然后把它放在某处,红宝石可以读取它。你需要将它的路径传递给ENV。
require 'google/apis/analytics_v3'
require 'googleauth'
ENV['GOOGLE_APPLICATION_CREDENTIALS'] = "service_account_credentials.json"
Analytics = Google::Apis::AnalyticsV3
analytics = Analytics::AnalyticsService.new
scopes = [Analytics::AUTH_ANALYTICS_READONLY]
analytics.authorization = Google::Auth.get_application_default(scopes)
accounts = analytics.list_accounts
accounts.items.each do |a| puts a.name end
我发现这是使用服务帐户查询Ruby API的最简单方法。
另外,请确保将Google Analytics帐户的访问权限授予您的服务帐户。
从那里您可以查询记录的其他方法here。
具体来说,你可以做到:
puts analytics.get_realtime_data("ga:XXXXX", "ga:activeVisitors").totals_for_all_results