I’m developing a Rails application that connects with Shopify via their API. I have set up webhooks successfully, but I am now attempting to handle them with background jobs, and I’m facing some challenges.
My webhook controller includes a filter to link to the Shopify store:
def handle_product_creation
payload = JSON.parse(request.body.read)
product_id = payload["id"]
Product.create_from_shopify(@shop, product_id)
head :ok
end
private
def link_to_store
shop_domain = request.headers['HTTP_X_SHOPIFY_SHOP_DOMAIN']
shop_domain = "http://" + shop_domain
@shop = Shop.find_by_domain(shop_domain)
session = ShopifyAPI::Session.new(@shop.domain, @shop.token)
session.valid?
ShopifyAPI::Base.activate_session(session)
end
In my model, I access the API with:
def self.create_from_shopify(shop, product_id)
shopify_product = ShopifyAPI::Product.find(product_id)
new_product = Product.new
new_product.shopify_id = shopify_product.id
new_product.name = shopify_product.title
new_product.shop = shop
new_product.save
end
However, when I switch to using Product.delay.create_from_shopify(@shop, product_id), the background job loses access to the API session, which causes an error.
What is the proper way to resolve this issue?