Skip to content

Instantly share code, notes, and snippets.

@mtowers mtowers/README.md
Last active Apr 20, 2019

Embed
What would you like to do?
Google Analytics Website Visitor Count Widget for Dashing with OAuth2 Authentication

Description

A Dashing widget for displaying the number of visitors to your website over a specified timeframe, as reported by Google Analytics

screen shot

Dependencies

google-api-ruby-client

Add it to dashing's gemfile:

gem 'google-api-client'

and run bundle install.

Usage

To use this widget, you'll first need to set up a Google API project and attach it to the Google Analytics profile you wish to monitor.

1. Create and download a new private key for Google API access.

  1. Go to https://code.google.com/apis/console
  2. Click 'Create Project'
  3. Enable 'Analytics API' service and accept both TOS's
  4. Click 'API Access' in the left-hand nav menu
  5. Click 'Create an OAuth 2.0 Client ID'
  6. Enter a product name (e.g. Dashing Widget) - logo and url are optional
  7. Click 'Next'
  8. Under Application Type, select 'Service Account'
  9. Click 'Create Client ID'
  10. Click 'Download private key' NOTE: This will be your only opportunity to download this key.
  11. Note the password for your new private key ('notasecret')
  12. Close the download key dialog
  13. Find the details for the service account you just created and copy it's email address which will look something like this: 210987654321-3rmagherd99kitt3h5@developer.gserviceaccount.com - you'll need it in your ruby code later

2. Attach your Google API service account to your Google Analytics profile

Note: you will need to be an administrator of the Google Analytics profile

  1. Log in to your Google Analytics account: http://www.google.com/analytics/
  2. Click 'Admin' in the upper-right corner
  3. Select the account containing the profile you wish to use
  4. Select the property containing the profile you wish to use
  5. Select the profile you wish to use
  6. Click the 'Users' tab
  7. Click '+ New User'
  8. Enter the email address you copied from step 13 above
  9. Click 'Add User'

3. Locate the ID for your Google Analytics profile

  1. On your Google Analytics profile page, click the 'Profile Settings' tab
  2. Under 'General Information' copy your Profile ID (e.g. 654321) - you'll need it in your ruby code later

4. Start coding (finally)

  1. Copy the visitor_count.rb file in to your dashing jobs\ folder.
  2. Update the service_account_email, key_file, key_secret and profileID variables
    service_account_email = '[YOUR SERVICE ACCOUTN EMAIL]' # Email of service account
    key_file = 'path/to/your/keyfile.p12' # File containing your private key
    key_secret = 'notasecret' # Password to unlock private key
    profileID = '[YOUR PROFILE ID]' # Analytics profile ID.
  1. Add the widget HTML to your dashboard
    <li data-row="1" data-col="1" data-sizex="1" data-sizey="1"> 
        <div data-id="visitor_count" data-view="Number" data-title="Visitors This Month"></div> 
    </li>

Notes

If you want to modify this plugin to pull other data from Google Analytics, be sure to check out the Google Analytics Query Explorer.

<li data-row="1" data-col="1" data-sizex="1" data-sizey="1">
<div data-id="visitor_count" data-view="Number" data-title="Visitors This Month"></div>
</li>
require 'google/api_client'
require 'date'
# Update these to match your own apps credentials
service_account_email = '[YOUR SERVICE ACCOUNT EMAIL]' # Email of service account
key_file = 'path/to/your/keyfile.p12' # File containing your private key
key_secret = 'notasecret' # Password to unlock private key
profileID = '[YOUR PROFILE ID]' # Analytics profile ID.
# Get the Google API client
client = Google::APIClient.new(:application_name => '[YOUR APPLICATION NAME]',
:application_version => '0.01')
# Load your credentials for the service account
key = Google::APIClient::KeyUtils.load_from_pkcs12(key_file, key_secret)
client.authorization = Signet::OAuth2::Client.new(
:token_credential_uri => 'https://accounts.google.com/o/oauth2/token',
:audience => 'https://accounts.google.com/o/oauth2/token',
:scope => 'https://www.googleapis.com/auth/analytics.readonly',
:issuer => service_account_email,
:signing_key => key)
# Start the scheduler
SCHEDULER.every '1m', :first_in => 0 do
# Request a token for our service account
client.authorization.fetch_access_token!
# Get the analytics API
analytics = client.discovered_api('analytics','v3')
# Start and end dates
startDate = DateTime.now.strftime("%Y-%m-01") # first day of current month
endDate = DateTime.now.strftime("%Y-%m-%d") # now
# Execute the query
visitCount = client.execute(:api_method => analytics.data.ga.get, :parameters => {
'ids' => "ga:" + profileID,
'start-date' => startDate,
'end-date' => endDate,
# 'dimensions' => "ga:month",
'metrics' => "ga:visitors",
# 'sort' => "ga:month"
})
# Update the dashboard
# Note the trailing to_i - See: https://github.com/Shopify/dashing/issues/33
send_event('visitor_count', { current: visitCount.data.rows[0][0].to_i })
end
@marcus

This comment has been minimized.

Copy link

commented Jul 18, 2013

Wow. Thanks for such detailed instructions. I don't know that I'd have made it through the Google API gauntlet without them.

For anyone who comes along later who is using the google api_client gem along with Ocotokit, here's a version that works for this widget and has a Faraday version compatible with Octokit:

gem 'google-api-client', '~> 0.6', :require => 'google/api_client'

@Caleezy

This comment has been minimized.

Copy link

commented Jul 27, 2013

I keep on getting an undefined method []' for nil:NilClass /Users/'mycomputername'/sweet_dashing_project/jobs/visitor_count.rb:47:inblock in <top (required)>'

@cbushell

This comment has been minimized.

Copy link

commented Jul 30, 2013

Great plugin, and write up. Would be great to see an implementation using OAuth, but this is a great starting point for me to work with.

@dbro

This comment has been minimized.

Copy link

commented Aug 20, 2013

When specifying the keyfile, be sure to include to full path to the file. I got the following error when running "dashing start" if I used the relative path from the /jobs directory:

/var/lib/gems/1.9.1/gems/google-api-client-0.6.4/lib/google/api_client/auth/key_utils.rb:88:in `rescue in load_key': Invalid keyfile or passphrase (ArgumentError)

@rafaelmagu

This comment has been minimized.

Copy link

commented Aug 21, 2013

@dbro You can use relative paths, but make sure they are relative to dashing's root folder (ie, the parent folder to /jobs).

@alexminnaar

This comment has been minimized.

Copy link

commented Nov 20, 2013

I am getting the same error as @Caleezy

@TimSmith714

This comment has been minimized.

Copy link

commented Dec 18, 2013

I think I've followed the instructions but I'm getting the following message when I try to start my Dashing Server (rackup -p 3030 -s puma)
/usr/lib/ruby/1.9.1/rubygems/custom_require.rb:36:in 'require': cannot load such file -- google-api-client (load error)
I've got
require 'google-api-client'
in the visitor_count.rb file and followed the instructions to include it in the Gemfile.
Typing
gem install google-api-ruby-client
gives the Error 'Could not find a valid gem 'google-api-ruby-client' (>= 0) in any repository
I've tried
sudo gem install google-api-client
which does install something but the same error appears when I try to start the server.
Ubuntu 32bit Ruby installed with RVM

@jamesgiroux

This comment has been minimized.

Copy link

commented Dec 24, 2013

I'm getting the same error as Tim Smith. Tried all the same steps. Will continue to try and debug.

@TimSmith714

This comment has been minimized.

Copy link

commented Dec 30, 2013

Well it looks like maybe I should have followed the instructions more closely. I tried
require 'google/api_client'
and it worked.
Now to find the correct profile IDs!

@F5pweb

This comment has been minimized.

Copy link

commented Jan 14, 2014

Hmm, i am running in to some troubles when starting dashing:
scheduler caught exception:
undefined method []' for nil:NilClass /home/martijn/dashing/social_dashboard/jobs/visitor_count.rb:47:inblock in <top (required)>'

When i check with gem list i see the google-api-client, and also with bundle show google-api-client but it looks like it can't find the api :( Does anyone has a solution for this problemen?

@andrewfraley

This comment has been minimized.

Copy link

commented Jan 24, 2014

If anyone is looking to use the GA realtime API try:

visitCount = client.execute(:api_method => analytics.data.realtime.get, :parameters => { 
    'ids' => "ga:" + profileID, 
    'dimensions' => 'ga:medium',
    'metrics' => "ga:activeVisitors" 
  })

  # Update the dashboard
  send_event('visitor_count',   { current: visitCount.data.totalsForAllResults["ga:activeVisitors"] })
@ben-ole

This comment has been minimized.

Copy link

commented Feb 26, 2014

Just had the same issue like @F5pweb or @Caleezy :

[]' for nil:NilClass /Users/'mycomputername'/sweet_dashing_project/jobs/visitor_count.rb:47:in

solution: pick the correct Profile ID - the documentation wasn't clear to me: the correct ID is under
ADMIN => VIEW => VIEW SETTINGS => VIEW ID.

cheers

@pachtymichuk

This comment has been minimized.

Copy link

commented Mar 21, 2014

@elchbenny, this error can occur for other reasons as well. try printing out the responsive adding
p visitCount. You might be getting a 403. In which case you need to enable your google API service or something.

@SamLevene

This comment has been minimized.

Copy link

commented Sep 18, 2014

I get an "Authorization failed. Server message: { "error" : "invalid_grant" }" error, but I followed these instructions to the letter. Anyone else having this problem?

@EwanValentine

This comment has been minimized.

Copy link

commented Oct 14, 2014

Getting invalid grant, also...

@ghost

This comment has been minimized.

Copy link

commented Nov 3, 2014

Same here... This Grant Guy shows up...

@dyscribe

This comment has been minimized.

Copy link

commented Nov 3, 2014

I found a solution that worked for my on the invalid_grant issue: https://stackoverflow.com/questions/26142850/gem-error-on-remote-machine/26722989#26722989

@jbayntun

This comment has been minimized.

Copy link

commented May 4, 2015

We had an issue on line 42 of visitor_count.rb. Changed it to:

'metrics' => "ga:visits", # was visitors before

and now it works

@capncodewash

This comment has been minimized.

Copy link

commented Aug 4, 2015

@jbayntun - it seems like that line should now be:

'metrics' => "ga:sessions",

Also, I was confused as to how to find the profile ID. For reference, it's not the same as the tracking code. You need to go to Admin ==> [[select the profile from the right, under the 'View' header]] ==> View Settings.

The ID displayed next to 'View ID'. It will be an integer.

Also, I got stuck a few times and wanted to debug the data coming back from GA. Insert this line before the send_event line to print the GA data to the shell:
puts visitCount.data.inspect

This lets you see 403 (etc.) errors more easily.

@ivanderos

This comment has been minimized.

Copy link

commented Dec 30, 2015

I have some problem but, I will solve it.

@CharlesSellers

This comment has been minimized.

Copy link

commented Aug 10, 2016

We tried to set this up recently and there is an issue with the new gem not being supported. After hunting around this appeared to fix this issue. I included the following code within our Gemfile.

gem 'google-api-client', '<0.9'

Credit to this thread (not related to dashing) gimite/google-drive-ruby#167

@mhetreramesh

This comment has been minimized.

Copy link

commented Nov 9, 2016

Great plugin and write up!

@Mike781

This comment has been minimized.

Copy link

commented Dec 1, 2016

No idea what happened here, I tried this and got this error when i try to start Dashing:

scheduler caught exception:
Authorization failed. Server message:
{
"error" : "invalid_client",
"error_description" : "The OAuth client was not found."
}

Pretty sure I followed the instructions to the letter, so I have no idea.

@Mike781

This comment has been minimized.

Copy link

commented Dec 1, 2016

Ignore that! I figured it out. It was a typo on my part.

@garyhoulihan

This comment has been minimized.

Copy link

commented Jan 18, 2017

Hi all, I have a quick question on this and the .json file I've generated from step 12.
The "key secret" data I don't seem to have..
I have:
"project_id": "
"private_key_id": "
"private_key":
"client_email":
"client_id":
"auth_uri":
"token_uri":
"auth_provider_x509_cert_url":
"client_x509_cert_url":

Is my Key Secret one of the above?

@ghost

This comment has been minimized.

Copy link

commented Jan 26, 2017

I believe, that when you use the option of authentication with .json file you are not ought to use "key secret" file to see the key, where as you use "key secret" which is just and with no hesitation 'notasecret' when choosing the option .p12 authentication.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.