Sylar Sylar - 2 months ago 16
Ruby Question

Use Rake to create webhooks in Shopify

Currently, if I add/remove a webhook from my application, for it to reflect in shopify app, the user has to reinstall the app. I need a way to avoid that so I thought I'd use rake.

For this I'm using the Rails ShopifyAPP. My app uses Rails 5.

config/application.rb:

...

config.after_initialize do
Rails.application.load_tasks
Rake::Task['shopifyapp:shopify_webhooks'].invoke
end

...


lib/tasks/shopify_webhooks.rake:

namespace :shopifyapp do
desc "create webhooks in shopify"
task :shopify_webhooks do
ShopifyApp.configure do |config|
config.webhooks = [
{topic: 'carts/update', address: 'https://some-external-address', format: 'json'},
]
end
puts "works" # outputs when server restarts
end
end


My 6th sense tells me something is not right with the rake file. Am I missing something? What's the issue? Webhooks are not creating.

If I add a new webhook in
config/initializers/shopify_app.rb
, it will work only if the app is reinstalled.

Answer

Since you have a valid authentication token to the Shop, in your rake task just connect to the Shop, and use the API to create the webhook. It is very easy to do.

ShopifyAPI::Base.activate_session(ShopifyAPI::Session.new(shop,token))
ShopifyAPI::Webhook.create(topic: 'orders/paid', address: 'https:foo', format: 'json')

I think that is more inline with how to use rake than to try and mimic Rails inside a rake task.