我为我的rails 3.2.6 app设置了shopify auth(omniauth-shopify-oauth2 gem)。
从网页(到以下控制器#动作)路由时,它可以正常工作
class ShopifyController < ApplicationController
...
def login
redirect_to "/auth/shopify?shop=#{current_retailer.primary_host_name}"
end
它将我重定向到商店登录,一旦我登录,重定向回成功回调。一切都很好(参见下面的SERVER LOG SUCCESS)。
但是当我尝试从rails控制台做同样的事情时:
irb(main):001:0> RestClient.get 'http://localhost:3000/auth/shopify?shop=vinehillposters.myshopify.com'
我明白了:
RestClient::Unauthorized: 401 Unauthorized: <?xml version="1.0" encoding="UTF-8"?>
<hash>
<errors>[API] Invalid API key or access token (unrecognized login or wrong password)</errors>
</hash>
请参阅
下面的SERVER LOG FAIL
服务器日志成功:
Processing by ShopifyController#login as HTML
... AR stuff snipped ...
Redirected to http://localhost:3000/auth/shopify?shop=vinehillposters.myshopify.com
Completed 302 Found in 93ms (ActiveRecord: 1.6ms)
(shopify) Setup endpoint detected, running now.
(shopify) Request phase initiated.
"https://vinehillposters.myshopify.com/admin/oauth/authorize?response_type=code&client_id=44dd9799fbc268c36ef609f0c2386b8c&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fauth%2Fshopify%2Fcallba
ck&scope=read_orders"
Started GET "/auth/shopify?shop=vinehillposters.myshopify.com" for 127.0.0.1 at 2012-10-30 11:24:21 +0000
(shopify) Setup endpoint detected, running now.
(shopify) Callback phase initiated.
Started GET "/auth/shopify/callback?code=c8c6696ed347e37324d2d62ec203457b&shop=vinehillposters.myshopify.com×tamp=1351596261&signature=e6324b041d6a6ed1e07719a8909d70f7" for 127.0.0.1 at
2012-10-30 11:24:21 +0000
Processing by ShopifyController#auth_callback as HTML
...
服务器日志失败:
(shopify) Setup endpoint detected, running now.
(shopify) Request phase initiated.
"https://vinehillposters.myshopify.com/admin/oauth/authorize?response_type=code&client_id=44dd9799fbc268c36ef609f0c2386b8c&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fauth%2Fshopify%2Fcallback&scope=read_orders"
Started GET "/auth/shopify?shop=vinehillposters.myshopify.com" for 127.0.0.1 at 2012-10-30 11:24:54 +0000
您可能已经注意到我在重定向到shopify之前打印了request_phase网址(在(shopify) Request phase initiated.
之后)。两种情况都是一样的。除了在一种情况下它返回成功,在另一种情况下它是401。
那么,我做错了什么?
答案 0 :(得分:2)
我认为你的问题令人困惑,你正在关注错误的部分。您需要做的是在用户登录后从shopify回调中获取有关它们的一些信息。
def shopify
shopify_domain = params[:shop]
@your_shop_object = your_finds_or_initializes_shop_or_auth_object_with shopify_domain, token
if @your_shop_object.persisted?
redirect_to root_url
else
# something went wrong :/
session['devise.shopify_data'] = request.env['omniauth.auth']
redirect_to auth_index_url
end
end
private
def token
request.env['omniauth.auth']['credentials']['token']
end
现在,您可以使用该持久化的商店对象数据来设置授权会话
session = ShopifyAPI::Session.new(domain, authentication_token)
if session.valid?
ShopifyAPI::Base.activate_session(session)
# Now you can make api calls for that shop (domain)
else
Rails.logger.error "[Shop] Could not create a valid session for '#{domain}'"
end