无法通过Google Analytics(分析)API提取分析数据

时间:2019-08-17 21:49:17

标签: ruby-on-rails ruby google-analytics-api

我有一个问题,使用Google Analytics(分析)API时我根本无法获得客户端数据。该应用程序需要通过Google身份验证获取每个用户的每月页面浏览量。这是一种辅助分析工具。

宝石文件

# Google API
gem 'omniauth-google-oauth2'
gem 'google-api-client', '~> 0.11', require: 'google/apis/analyticsreporting_v4'

apps / views / websites / new.html.erb

<%= link_to google_auth_redirect_path do %>
  <div class="btn">
    <span>Authenticate with Google</span>
  </div>
<% end %>

apps / controllers / google_auth_controller.rb

class GoogleAuthController < ApplicationController
  def callback
    analytics = Google::Apis::AnalyticsreportingV4::AnalyticsReportingService.new
    analytics.authorization = current_user.token

    date_range = Google::Apis::AnalyticsreportingV4::DateRange.new(start_date: '30DaysAgo', end_date: 'today')
    metric = Google::Apis::AnalyticsreportingV4::Metric.new(expression: 'ga:sessions', alias: 'sessions')
    dimension = Google::Apis::AnalyticsreportingV4::Dimension.new(name: 'ga:browser')

    request = Google::Apis::AnalyticsreportingV4::GetReportsRequest.new(
      report_requests: [Google::Apis::AnalyticsreportingV4::ReportRequest.new(
        view_id: 'VIEW_ID_FROM_ANALYTICS_PROPERTY',
        metrics: [metric],
        dimensions: [dimension],
        date_ranges: [date_range]
      )]
    )

    response = analytics.batch_get_reports(request)
    response.reports    
  end

  def redirect
    client = Signet::OAuth2::Client.new(SyncAnalyticsService::CLIENT_OPTIONS)
    redirect_to client.authorization_uri.to_s
  end    
end

apps / services / sync_analytics_services.rb

class SyncAnalyticsService
  CLIENT_OPTIONS = {
    client_id: Rails.application.credentials.google[:client_id],
    client_secret: Rails.application.credentials.google[:client_secret],
    authorization_uri: 'https://accounts.google.com/o/oauth2/auth',
    token_credential_uri: 'https://www.googleapis.com/oauth2/v4/token',
    scope: [Google::Apis::AnalyticsreportingV4::AUTH_ANALYTICS_READONLY],
    redirect_uri: Rails.application.routes.url_helpers.google_auth_callback_url,
    additional_parameters: {prompt:'consent'}
  }
end

我无法获取分析数据...

pry(#<GoogleAuthController>)> analytics
=> #<Google::Apis::AnalyticsreportingV4::AnalyticsReportingService:0x007fd77b327c60
@base_path="",
@batch_path="batch",
@client_options=
  #<struct Google::Apis::ClientOptions
  application_name="unknown",
  application_version="0.0.0",
  proxy_url=nil,
  open_timeout_sec=nil,
  read_timeout_sec=nil,
  send_timeout_sec=nil,
  log_http_requests=false,
  transparent_gzip_decompression=true>,
@request_options=
  #<struct Google::Apis::RequestOptions
  authorization=nil,
  retries=0,
  header=nil,
  normalize_unicode=false,
  skip_serialization=false,
  skip_deserialization=false,
  api_format_version=nil>,
@root_url="https://analyticsreporting.googleapis.com/",
@upload_path="upload/">

0 个答案:

没有答案