How to handle Shopify API connection with Shopify gem?

孤者浪人 提交于 2019-12-06 16:02:16

I approach this by storing the OAuth token that is returned by Shopify with the store (you should be doing this anyway). All you need to access the API is the token, so in your shop model you would have a method like:

def shopify_api_path
  "https://#{Rails.configuration.shopify_api_key}:#{self.shopify_token}@#{self.shopify_domain}/admin"
end

Then if you want to access the API for a particular store in a Delayed Job worker, you would simply:

begin
  ShopifyAPI::Base.site = shop.shopify_api_path
  # Make whatever calls to the API that you want here.
  products = ShopifyAPI::Product.all
ensure
  ShopifyAPI::Base.site = nil
end

Hopefully that helps a little. I find working with Sessions outside of controllers to be a bit messy, particularly since this is nice and easy.

I think there is some misunderstanding here. You do know that you are really just using Active Resource for all your API work? And therefore when you authenticate, you are probably authenticating a session? And that once authenticated, no matter how many times you actually use the API, you're not actually opening "new" connections.

You are doing it wrong if you are constantly authenticating in a single session to do more than one API call.

If you happen to be in a block of code that has no authentication (for example your App may process a WebHook from N shops) or a Delayed Job, simply pass the myshopify_domain string to those code blocks, look up the Shop in your DB, find the auth token, authenticate (once)... and away you go... it really quite simple.

Edward Ocampo-Gooding

Once your application has authenticated once, you can hold on to that computed password – it’s good until the app is uninstalled for that particular store.

In other words, authenticate just the once when the merchant first installs the app, save the password to a db, and load it up whenever you need it. Your self.shop.connect_to_store call should then just set the ShopifyAPI::Session instance.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!