javascript - Ruby on Rails get google analytics visitors count and save into my app db. -
i working google analytics add in project. create account , added js code application footer section. want retrieve visitors information count, geo etc. need specific , simple solution that.
in app/services/google_analytics.rb file,
require 'google/api_client' require 'date' class googleanalytics def initialize @client = google::apiclient.new(:application_name => env['ga_app_name'], :application_version => '1.0') key_file = file.join('config', env['ga_key_file_name']) key = google::apiclient::pkcs12.load_key(key_file, 'notasecret') service_account = google::apiclient::jwtasserter.new( env['ga_service_account_email'], ['https://www.googleapis.com/auth/analytics.readonly', 'https://www.googleapis.com/auth/prediction'], key) @client.authorization = service_account.authorize @analytics = @client.discovered_api('analytics', 'v3') end def visitors(startdate, enddate, site_url) parameters = {'ids' => "ga:" + env['ga_view_id'], 'filters' => "ga:pagepath=~"+ site_url, 'start-date' => startdate, 'end-date' => enddate, 'dimensions' => "ga:country,ga:source", 'metrics' => "ga:sessions", 'sort' => "-ga:sessions", 'include-empty-rows' => false } results = @client.execute(api_method: @analytics.data.ga.get, parameters: parameters) if results.error? puts results.error_message return [0, {}, {}] else total_count = 0 countries = {} sources = {} results.data.rows.each |row| total_count += row[-1].to_i countries[row[0]] = countries[row[0]].to_i + row[-1].to_i sources[row[1]] = sources[row[1]].to_i + row[-1].to_i end return [total_count, countries, sources] end end end
and in controller#action, add code this:
ga = ::googleanalytics.new() @total_visits, @countries, @sources = ga.visitors(start_date, end_date, @user.site_url)
it works.
Comments
Post a Comment