Search code examples
rubygoogle-analytics-apigoogle-api-clientgoogle-api-ruby-client

Google analytics api integration issue


I'm using signet and google-api-ruby-client to integrate with Google Analytics api,

wrote the following code:

require 'signet/oauth_2/client'
require 'google/apis/analytics_v3'


class GoogleController < ApplicationController
   skip_before_action :ensure_json_request


def analytics_login
  client = initialize_client
  redirect_to(client.authorization_uri.to_s)
end

def analytics_callback
  client = initialize_client
  client.code = params['code']
  authorization = client.fetch_access_token!
  anal = Google::Apis::AnalyticsV3::AnalyticsService.new
  anal.authorization= authorization
  accounts = anal.list_account_summaries(max_results: 100, options:   {authorization: authorization})
  pp accounts.items.first.web_properties.first.profiles.first.id


  redirect_to('http://0.0.0.0:3000')
end

private

def initialize_client
  Signet::OAuth2::Client.new(
    :authorization_uri => 'https://accounts.google.com/o/oauth2/auth',
    :token_credential_uri => 'https://www.googleapis.com/oauth2/v3/token',
    :client_id => '*******.apps.googleusercontent.com',
  :client_secret => '******',
  :scope => Google::Apis::AnalyticsV3::AUTH_ANALYTICS,
  :redirect_uri => 'http://localhost:3000/ga/callback'
)
end

end

I'm getting to the callback and getting an Google::Apis::AuthorizationError at /ga/callback error as response from calling list_account_summaries.

Am I missing anything?


Solution

  • After digging a little bit more found a working sample here