我无法将这两个部分连接在一起:我能够验证我的服务帐户,并且我知道如何为我需要从 API 检索的信息形成请求,但我不知道如何使该请求使用令牌进行身份验证。
这将从我为服务帐户获得的凭据文件中构建一个对象并成功生成令牌:
需要'googleauth'
require 'google/apis/webmasters_v3'
website = "https://example.com"
scope = 'https://www.googleapis.com/auth/webmasters'
authorizer = Google::Auth::ServiceAccountCredentials.make_creds(
json_key_io: File.open('service-account.json'),
scope: scope)
token = authorizer.fetch_access_token!
最后的请求就像
wt_service.query_search_analytics(website, {
"startDate"=> "2019-12-01",
"endDate"=> "2019-12-02",
"dimensions"=> [
"query"
]
})
但是网站管理员工具 API 端点的对象不接受任何参数:
wt_service = Google::Apis::WebmastersV3::WebmastersService.new
但是我需要以某种经过身份验证的方式构建它,即使用令牌 - 但是如果我不能添加参数怎么办?!
如何使用令牌构建对象?
=====
查德维克伍德的回应解决了这个问题。有一个后续问题,因为 Google API 使用的变量名称不一致,所以我在下面粘贴了完整的工作代码(在将服务用户添加到域的网站管理员工具用户列表后工作)
require 'googleauth'
require 'google/apis/webmasters_v3'
website = "https://example.com"
scope = 'https://www.googleapis.com/auth/webmasters'
authorizer = Google::Auth::ServiceAccountCredentials.make_creds(json_key_io: File.open('service-account.json'),scope: scope)
token = authorizer.fetch_access_token!
wt_service = Google::Apis::WebmastersV3::WebmastersService.new
wt_service.authorization = authorizer
wt_service.authorization.apply(token)
request_object = {
start_date: "2019-02-01",
end_date: "2020-02-28",
dimensions: ["query"]
}
params = Google::Apis::WebmastersV3::SearchAnalyticsQueryRequest.new(request_object)
res = wt_service.query_search_analytics(website, params)