Rails谷歌api客户端加载P12 / JSON文件方法

时间:2016-09-11 20:56:55

标签: ruby-on-rails ruby-on-rails-4 google-analytics google-analytics-api google-api-ruby-client

点击此处的示例:https://gist.github.com/joost/5344705

最新版本的google-api-client gem会在以下位置引发错误:

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

加载P12 / JSON文件的新方法是什么?

仅供参考,重构易出错的代码:

# 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

1 个答案:

答案 0 :(得分:0)

对于google-api-client gem的版本0.9.18,signing_key部分应更改为:

require 'google/api_client/auth/key_utils'

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