Skip to content

Instantly share code, notes, and snippets.

@willjohnson
Forked from mtowers/README.md
Last active November 27, 2019 10:04
Show Gist options
  • Save willjohnson/6232286 to your computer and use it in GitHub Desktop.
Save willjohnson/6232286 to your computer and use it in GitHub Desktop.
Google Analytics Website Visitor Count Widget for Dashing with OAuth2 Authentication (multiple profiles)

Description

This is a fork of the Google Analytics Website Visitor Count Widget for Dashing with OAuth2 Authentication to allow for multiple profiles to be shown in the same widget.

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

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: [email protected] - 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 profiles 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
    # Array of profile names and corresponding Analytics profile id
        profiles = [{name: 'site1', id: '11111111'},
                    {name: 'site2', id: '22222222'},
                    {name: 'site3', id: '33333333'},
                    {name: 'site4', id: '44444444'}]
  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="List" data-unordered="true" 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="List" data-unordered="true" 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
# Array of profile names and corresponding Analytics profile id
profiles = [{name: 'site1', id: '11111111'},
{name: 'site2', id: '22222222'},
{name: 'site3', id: '33333333'},
{name: 'site4', id: '44444444'}]
# 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 '30m', :first_in => 0 do # modified from 1m
# 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
visitors = Array.new
profiles.each do |profile|
# Execute the query
visitCount = client.execute(:api_method => analytics.data.ga.get, :parameters => {
'ids' => "ga:" + profile[:id],
'start-date' => startDate,
'end-date' => endDate,
# 'dimensions' => "ga:month",
'metrics' => "ga:visitors",
# 'sort' => "ga:month"
})
if visitCount.data.rows[0] and visitCount.data.rows[0][0] # deals with no visits
visits = visitCount.data.rows[0][0]
else
visits = 0
end
visitors.push({label: profile[:name], value: visits})
end
# Update the dashboard
send_event('visitor_count', {items: visitors})
end
@mic159
Copy link

mic159 commented Nov 28, 2014

I had some errors from the API, and added this to help in debugging when you are setting up the job:

    if visitCount.data.rows[0] and visitCount.data.rows[0][0] # deals with no visits
      visits = visitCount.data.rows[0][0]
    else
      visits = 0
      if visitCount.error?
        puts "ERROR::GoogleAnalitcs Could not get data for #{profile[:id]}. Reason: #{visitCount.error_message}"
      end
    end

@simllll
Copy link

simllll commented Feb 24, 2017

@simonstaimie
Copy link

this sounds great!
I will try this today and update my findings.... if any!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment