我正在尝试开发一个 ruby 脚本来使用服务帐户凭据查询 Google Adwords API。我知道 json 凭据文件在另一个不是 ruby 的脚本中工作,但我无法在此 ruby 脚本中获得过去的授权。我找不到任何使用这种模式的例子。我不想使用 OAuth2
。我知道这个脚本没有很好地开发,但我只是想了解基础知识。我在这里做错了什么?
我的公司有一个 G Suite 帐户,我有完整的管理员权限。
这是我的代码:
#!/usr/bin/ruby
require 'googleauth'
require 'fileutils'
require 'adwords_api'
API_VERSION = :v201809
scopes = ["https://www.googleapis.com/auth/adwords"]
credential_file = File.open('credentials/adwords-production.json')
prn = "adwords@mycompany.com"
authorizer = Google::Auth::ServiceAccountCredentials.make_creds(json_key_io: credential_file, scope: scopes, prn: prn)
def get_report_fields(report_type)
adwords = AdwordsApi::Api.new
report_def_srv = adwords.service(:ReportDefinitionService, API_VERSION)
# Get report fields.
fields = report_def_srv.get_report_fields(report_type)
if fields
puts "Report type '%s' contains the following fields:" % report_type
fields.each do |field|
puts ' - %s (%s)' % [field[:field_name], field[:field_type]]
puts ' := [%s]' % field[:enum_values].join(', ') if field[:enum_values]
end
end
end
begin
report_type = 'ACCOUNT_PERFORMANCE_REPORT'
get_report_fields(report_type)
end
最佳答案
来自谷歌文档 here :
All AdWords API calls must be authorized through OAuth2. OAuth2 enables your AdWords API client app to access a user's Google Ads account without having to handle or store the user's login info.
看来您必须使用 OAuth2
身份验证。
进一步阅读 here证实这一点:
Your app will need to access user data and contact other Google services on your behalf. Authentication via OAuth2 allows your app to operate on behalf of your account.
To enable your app to access the API, you need an OAuth2 client ID and client secret.
您说您在其他地方可以使用 JSON 文件的地方完成了此操作,所以我稍微查看了一下源代码。
Ruby API 的来源是 here和 here .看起来真的没有其他方法来管理凭据,至少在 Ruby API 中是这样。看这里:
# Retrieve correct soap_header_handler.
#
# Args:
# - auth_handler: instance of an AdsCommon::Auth::BaseHandler subclass to
# handle authentication
# - version: intended API version
# - header_ns: header namespace
# - default_ns: default namespace
#
# Returns:
# - SOAP header handler
#
def soap_header_handler(auth_handler, version, header_ns, default_ns)
auth_method = @config.read('authentication.method', :OAUTH2)
handler_class = case auth_method
when :OAUTH2, :OAUTH2_SERVICE_ACCOUNT
AdsCommon::SavonHeaders::OAuthHeaderHandler
else
raise AdsCommon::Errors::AuthError,
"Unknown auth method: %s" % auth_method
end
return handler_class.new(@credential_handler, auth_handler, header_ns,
default_ns, version)
end
请注意,除非使用 OAuth,否则它会抛出错误。确实没有其他方法可以进行身份验证。即使您设法通过其他方式进行身份验证并尝试将其传递给凭证管理器,它也会拒绝它。
简短的回答:如果不以某种方式破解它,这在 Ruby API 中是不可能的。
关于ruby - Google adwords api 如何通过服务帐户模拟进行授权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55364683/