お世話になっております。
Google Analytics APIを使って、月次のPVデータを取得したいと考えています。現在、認証をしているにも関わらず、clientのデータが取得できずに困っています。
こちらの記事を参考にして作っているのですが、どうしてもcallbackした後にユーザーデータを拾うことができません。
Gemfile
Ruby
1# Google API 2gem 'omniauth-google-oauth2' 3gem 'google-api-client', '~> 0.11', require: 'google/apis/analyticsreporting_v4'
apps/views/wesite/new.html
Ruby
1<%= link_to google_auth_redirect_path do %> 2 <div class="btn"> 3 <span>Authenticate with Google</span> 4 </div> 5<% end %>
apps/controllers/google_auth_controller.rb
Ruby
1class GoogleAuthController < ApplicationController 2 def callback 3 analytics = Google::Apis::AnalyticsreportingV4::AnalyticsReportingService.new 4 analytics.authorization = current_user.token 5 6 date_range = Google::Apis::AnalyticsreportingV4::DateRange.new(start_date: '30DaysAgo', end_date: 'today') 7 metric = Google::Apis::AnalyticsreportingV4::Metric.new(expression: 'ga:sessions', alias: 'sessions') 8 dimension = Google::Apis::AnalyticsreportingV4::Dimension.new(name: 'ga:browser') 9 10 request = Google::Apis::AnalyticsreportingV4::GetReportsRequest.new( 11 report_requests: [Google::Apis::AnalyticsreportingV4::ReportRequest.new( 12 view_id: 'VIEW_ID_FROM_ANALYTICS_PROPERTY', 13 metrics: [metric], 14 dimensions: [dimension], 15 date_ranges: [date_range] 16 )] 17 ) 18 19 response = analytics.batch_get_reports(request) 20 response.reports 21 end 22 23 def redirect 24 client = Signet::OAuth2::Client.new(SyncAnalyticsService::CLIENT_OPTIONS) 25 redirect_to client.authorization_uri.to_s 26 end 27end
apps/services/sync_analytics_services.rb
Ruby
1class SyncAnalyticsService 2 CLIENT_OPTIONS = { 3 client_id: Rails.application.credentials.google[:client_id], 4 client_secret: Rails.application.credentials.google[:client_secret], 5 authorization_uri: 'https://accounts.google.com/o/oauth2/auth', 6 token_credential_uri: 'https://www.googleapis.com/oauth2/v4/token', 7 scope: [Google::Apis::AnalyticsreportingV4::AUTH_ANALYTICS_READONLY], 8 redirect_uri: Rails.application.routes.url_helpers.google_auth_callback_url, 9 additional_parameters: {prompt:'consent'} 10 } 11end
上記の画面で認証を許可するところまではできているのですが、 analytics
の中身を見てみると、下記のようになにも取得できていません。
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/">
Google側の設定が間違っているのでしょうか・・・。
あなたの回答
tips
プレビュー