Ich arbeite mit Google Analytics, um mein Projekt hinzuzufügen. Ich habe bereits einen Account erstellt und den Js-Code zu meinem Anwendungsfußbereich hinzugefügt. Jetzt möchte ich Besucherinformationen wie Graf, Geo usw. abrufen. Ich brauche sehr spezifische und einfache Lösung darüber.Ruby on Rails erhalten Google Analytics Besucher zählen und speichern in meiner App db.
0
A
Antwort
0
In app/services/google_analytics.rb Datei,
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 do |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
und in Ihrem Controller # Aktion, fügen Sie Code wie folgt:
ga = ::GoogleAnalytics.new()
@total_visits, @countries, @sources = ga.visitors(start_date, end_date, @user.site_url)
Es funktioniert.