How to create Webhooks (orders/create)

Highlighted
Tourist
16 0 2

Hello, I am developing a Shopify App in rails, and I need to send some JSON requests/responses to one carrier service when a new order is created.

I want to integrate webhooks in my App, but I have no idea what I have to do. At the moment I am working with this, using requestb:

shopify_app.rb

ShopifyApp.configure do |config|
  config.application_name = "My Shopify App"
  config.api_key = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
  config.secret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
  config.scope = "read_orders, read_products,read_script_tags, write_script_tags, write_shipping"
  config.embedded_app = true
  config.after_authenticate_job = false
  config.session_repository = Shop
  config.webhooks = [
    {topic: 'orders/create', address: 'https://requestb.in/xxxxxxx/orders_create', format: 'json'},
  ]
end

orders_create_job.rb 

class OrdersCreateJob < ActiveJob::Base
  def perform(shop_domain:, webhook:)
    shop = Shop.find_by(shopify_domain: shop_domain)

    shop.with_shopify_session do
    end
  end
end

I don't know if I should create a webhook_controller or what I have to do to send POST responses.

What I should write on routes.rb?

Could you help me with this? Basicly I would want to be able to send something like this through the API when a new order is created:

{"id":29908140045,"email":"example@example.com","closed_at":null,"created_at":"2017-11-08T13:10:30-05:00","updated_at":"2017-11-08T13:20:20-05:00",...}

Thank you.

0 Likes
Shopify Staff
Shopify Staff
1555 79 240

Hey Alberto,

I think the webhook creation request is made by default, but if you wanted to redefine that request:

You can copy some core controllers like the sessions_controller and authenticated_controller into your project by running `rails g controller shopify_app:controllers` which are typically hidden in the gem source code.

The sessions_controller has a `callback` method defined in it which should be invoking a predefined install_webhooks method which uses the configuratiuon data you set to make the resource. Eg:

module ShopifyApp
  class SessionsController < ActionController::Base
    include ShopifyApp::LoginProtection
    layout false, only: :new

    # ....

    def callback
      if auth_hash
        login_shop
        install_webhooks
        install_carrier_service
        perform_after_authenticate_job

        redirect_to return_address
      else
        flash[:error] = I18n.t('could_not_log_in')
        redirect_to login_url
      end
    end

    # ....

    private

    # ....

    def install_webhooks
      return unless ShopifyApp.configuration.has_webhooks?

      WebhooksManager.queue(
        shop_name,
        token,
        ShopifyApp.configuration.webhooks
      )
    end
end

I hope that's a step in the right direction!

Cheers.

0 Likes