无法通过Google Content API for Shopping进行身份验证

B. *_*ill 3 ruby-on-rails google-api oauth-2.0

我正在尝试将OAuth2用于服务器到服务器应用程序,并结合Google的Content API for Shopping使用google-api-client gem和Ruby on Rails 3.2.5.此外,我已按照Content API文档中的规定设置了我的商家帐户.

这是我发现能够:

  • 在后台创建/更新产品
  • 已创建产品属于我公司的Google产品"保护伞"
  • 当令牌过期时,不要求每个用户进行身份验证/授权

使用此示例中的第1 - 23行作为起点,我已经开始编写以下模块以用于后台作业:

require 'httparty'
require 'google/api_client'

module GoogleProducts
  GOOGLE_CONFIG = YAML.load_file(File.join(Rails.root, "config", "google.yml"))[Rails.env]

  CLIENT_ID = "XXXXXXXXXXXX@developer.gserviceaccount.com"
  MERCHANT_ID = "XXXXXXX"
  SCOPE = "https://www.googleapis.com/auth/structuredcontent"

  KEY_FILE_PATH = File.join(Rails.root, "config", "my-privatekey.p12")
  KEY_FILE_PASS = "XXXXXXXXXX"

  def self.add_item(item_id)
    self.fetch_token
    xml = self.gen_item_xml(item_id)
    headers = {"Content-type" => "application/atom+xml", "Content-Length" => xml.length.to_s}
    url = "https://content.googleapis.com/content/v1/#{MERCHANT_ID}/items/products/generic?access_token=#{$gp_token}"

    response = HTTParty.post(url, :body => xml, :headers => headers).parsed_response
  end

  def self.gen_item_xml(item_id)
    #building product xml
  end

  private
  def self.fetch_token
    api_client = Google::APIClient.new(:authorization => :oauth2)
    key = Google::APIClient::PKCS12.load_key(KEY_FILE_PATH, KEY_FILE_PASS)
    asserter = Google::APIClient::JWTAsserter.new(CLIENT_ID, SCOPE, key)

    begin
      api_client.authorization = asserter.authorize

      #todo - store in something other than a global
      $gp_token = api_client.authorization.access_token
    rescue Signet::AuthorizationError => e
      puts e.message
    ensure
      return $gp_token
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

一切似乎都运行良好 - 身份验证,身份验证令牌的处理 - 直到我尝试实际添加一个项目,当我这样做时,我得到以下内容:

<errors xmlns='http://schemas.google.com/g/2005'>
  <error>
    <domain>GData</domain>
    <code>ServiceForbiddenException</code>
    <internalReason>Could not find authenticated customer</internalReason>
  </error>
</errors>
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

B. *_*ill 6

经过多次痛苦和精神上的辛劳,我终于解决了我的问题!

由于我使用的是OAuth 2服务器到服务器身份验证,因此hjblok给出的建议不适用(感谢给它一个镜头,但是!).

我只是将与我的服务帐户密钥相关联的电子邮件地址从Google API控制台(例如XXXXXXXXXXXX@developer.gserviceaccount.com)添加到我的Google Merchant帐户(Settings > Users在商家管理页面上),然后就可以了.

如果需要任何澄清,请随时发表评论!