我正在尝试从 GA4 API 库获取给定页面路径的浏览次数。我已经能够使用 Ruby GA4 API 客户端 gem
google-analytics-data
来完成此操作,但由于 GA4 查询资源管理器和我的 Ruby API 代码之间的结果存在显着差异,我想使用基本 REST 请求来比较结果。有些路径会产生相同的计数,但大多数不会。
我不断收到错误消息
/var/lib/gems/2.7.0/gems/googleauth-1.11.0/lib/googleauth/service_account.rb:87:in `unescape': undefined method `gsub' for nil:NilClass (NoMethodError)
此错误是由以下行生成的:
credentials = Google::Auth::ServiceAccountCredentials.make_creds(
scope: claims[:scope],
json_key: private_key
)
我的代码中的
gsub
行不相关,因为即使删除 gsub
也会生成错误。
这是我的完整代码。
#!/usr/bin/ruby
require 'googleauth'
require 'net/http'
require 'json'
require 'time'
require './environment'
error_message = nil
module GoogleAnalytics
def self.make_ga4_rest_request(body)
# Define GA4 Reporting API endpoint URL
endpoint = "https://analyticsreporting.googleapis.com/v4/reports:batchGet"
key_data = JSON.parse(File.read(SERVICE_ACCOUNT_KEY_FILE))
private_key = key_data['private_key'].gsub("\n", "")
puts private_key.inspect
claims = {
iss: SERVICE_ACCOUNT_EMAIL,
scope: AUDIENCE,
aud: AUDIENCE,
exp: (Time.now + 60 * 60).to_i # JWT expires in 1 hour
}
credentials = Google::Auth::ServiceAccountCredentials.make_creds(
scope: claims[:scope],
json_key: private_key
)
jwt = credentials.authorization.id_token
headers = {
"Content-Type": "application/json",
"Authorization": "Bearer #{jwt}"
}
headers["Authorization"] = "Bearer #{private_key}"
# Prepare the Net::HTTP request object
uri = URI(endpoint)
https = Net::HTTP.new(uri.host, uri.port)
https.use_ssl = true
request = Net::HTTP::Post.new(uri)
# request.set_header!(*headers) newer ruby versions
headers.each do |key, value|
request.add_field(key, value)
end
request.body = body.to_json
# Send the request and handle response
response = https.request(request)
if response.is_a?(Net::HTTPSuccess)
JSON.parse(response.body)
else
error_message = "Error making GA4 request: #{response.code} - #{response.message}"
puts "Error message: #{error_message}"
puts "Response object: #{response.body}" # Print thend
end
end
end
为了完整性,这里是我的查询的正文
body = {
"reportRequests": [
{
"property": "properties/#{PROPERTY_ID}",
"dateRanges": [{"startDate": report_start_date, "endDate": report_end_date}],
"metrics": [{"expression": "ga:screenPageViews"}],
"dimensions": [{"name": "ga:pagePath"}],
"filters": [{"field": "ga:pagePath", "operator": "REGEXP_CONTAINS", "value": page}],
}
]
}
首先,请确保您是Google Analytics帐户的管理员,否则您需要管理员启用权限。
其次,您需要在您的帐户中启用Google Analytics的API。
第三,身份验证 Google Cloud Platform 服务遵循本指南 https://cloud.google.com/ruby/docs/reference/google-analytics-data/latest/AUTHENTICATION .
require "google/analytics/data"
Google::Analytics::Data.configure do |config|
config.credentials = "path/to/keyfile.json"
end
client = Google::Analytics::Data.analytics_data