0

Following a sample which is here: https://gist.github.com/joost/5344705

The latest version of the google-api-client gem throws an error on:

key = Google::APIClient::PKCS12.load_key(key_file, 'notasecret')
#=> Uninitialized constant Google::APIClient(name error)

What is the new method for loading the P12/JSON file?

FYI, refactored error-prone code:

# you need to set this according to your situation/needs
SERVICE_ACCOUNT_EMAIL_ADDRESS = 'xxx@developer.gserviceaccount.com' # looks like 12345@developer.gserviceaccount.com
PATH_TO_KEY_FILE              = '/home/arjun/rails/learn/xxx.p12' # the path to the downloaded .p12 key file
PROFILE                       = 'ga:xxx' # your GA profile id, looks like 'ga:12345'


require 'google/apis/analytics_v3'
require 'googleauth/stores/file_token_store'

Analytics = Google::Apis::AnalyticsV3
# set up a client instance
client = Analytics::AnalyticsService.new

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_ADDRESS,
  # :signing_key          => OpenSSL::PKey.load_key(PATH_TO_KEY_FILE, 'notasecret')

  # Not working = throws []': no implicit conversion of Symbol into Integer (TypeError)
  :signing_key          => Google::Auth::Stores::FileTokenStore.new(PATH_TO_KEY_FILE.to_i)
).tap { |auth| auth.fetch_access_token! }

api_method = client.discovered_api('analytics','v3').data.ga.get


# make queries
result = client.execute(:api_method => api_method, :parameters => {
  'ids'        => PROILE,
  'start-date' => Date.new(1970,1,1).to_s,
  'end-date'   => Date.today.to_s,
  'dimensions' => 'ga:pagePath',
  'metrics'    => 'ga:pageviews',
  'filters'    => 'ga:pagePath==/url/to/user'
})

puts result.data.rows.inspect
Eric Platon
  • 9,819
  • 6
  • 41
  • 48
arjun
  • 1,594
  • 16
  • 33

1 Answers1

1

for version 0.9.18 of the google-api-client gem, the signing_key part should change to:

require 'google/api_client/auth/key_utils'

signing_key: Google::APIClient::KeyUtils::load_from_pkcs12(keypath, 'notasecret')

yachi
  • 1,489
  • 1
  • 8
  • 4