[英]Ruby example to access google shopping api using GAN publisher id
[英]Trouble authenticating with Google Content API for Shopping
我正在嘗試將OAuth2用於服務器到服務器應用程序 ,並結合Google的Content API for Shopping使用google-api-client gem和Ruby on Rails 3.2.5。 此外,我已按照Content API文檔中的規定設置了我的商家帳戶。
這是我發現能夠:
使用此示例中的第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
一切似乎都運行良好 - 身份驗證,身份驗證令牌的處理 - 直到我嘗試實際添加一個項目,當我這樣做時,我得到以下內容:
<errors xmlns='http://schemas.google.com/g/2005'>
<error>
<domain>GData</domain>
<code>ServiceForbiddenException</code>
<internalReason>Could not find authenticated customer</internalReason>
</error>
</errors>
有任何想法嗎?
經過多次痛苦和精神上的辛勞,我終於解決了我的問題!
由於我使用的是OAuth 2服務器到服務器身份驗證,因此hjblok給出的建議不適用(感謝給它一個鏡頭,但是!)。
我只是將與我的服務帳戶密鑰相關聯的電子郵件地址從Google API控制台(例如XXXXXXXXXXXX@developer.gserviceaccount.com
)添加到我的Google Merchant帳戶(商家管理頁面上的Settings > Users
),並且它有效。
如果需要任何澄清,請隨時發表評論!
Google Content API文檔說明您需要在Google Merchant Center的“設置”頁面中進行設置:
https://developers.google.com/shopping-content/getting-started/usingapi-products
在深入了解Google的API文檔后, EDIT重寫了答案
您是否已嘗試使用Google的OAuth 2.0游樂場 ? 我能夠成功訪問https://content.googleapis.com/content/v1/#{MERCHANT_ID}/items/products/generic
。
GET
請求到https://content.googleapis.com/content/v1/1234567/items/products/generic
。 由於1234567
不是有效的MERCHANT_ID
因此返回錯誤。 但錯誤消息包含實際屬於您的帳戶的MERCHANT_ID
。 MERCHANT_ID
。 返回HTTP/1.1 200 OK
,包含正文中的請求項。 此外,我不確定,但Google API是否期望授權標頭與access_token
( $gp_token
)一起出現? 在OAuth 2.0操場中,此Authorization標頭用於發送access_token
。
我還找到了結構化內容API演示頁面(https://google-content-api-tools.appspot.com/demo/demo.html),該頁面更適用於Content API for Shopping。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.