From acdb96b4dcff785361334ebed82b4fac3772dae3 Mon Sep 17 00:00:00 2001 From: Zoey Lan Date: Tue, 29 Oct 2024 16:44:45 -0600 Subject: [PATCH] Update access scopes in DB from new webhook subscription --- shopify.app.toml | 6 +++++- .../webhooks/app_scopes_update_controller.rb | 13 +++++++++++++ web/app/jobs/app_scopes_update_job.rb | 16 ++++++++++++++++ web/config/routes.rb | 1 + 4 files changed, 35 insertions(+), 1 deletion(-) create mode 100644 web/app/controllers/webhooks/app_scopes_update_controller.rb create mode 100644 web/app/jobs/app_scopes_update_job.rb diff --git a/shopify.app.toml b/shopify.app.toml index dd8d68f..fd791fb 100644 --- a/shopify.app.toml +++ b/shopify.app.toml @@ -3,7 +3,11 @@ scopes = "write_products" [webhooks] -api_version = "2024-07" +api_version = "2024-10" + + [[webhooks.subscriptions]] + topics = [ "app/scopes_update" ] + uri = "/api/webhooks/app_scopes_update" [[webhooks.subscriptions]] uri = "/api/webhooks/app_uninstalled" diff --git a/web/app/controllers/webhooks/app_scopes_update_controller.rb b/web/app/controllers/webhooks/app_scopes_update_controller.rb new file mode 100644 index 0000000..ad7b8bc --- /dev/null +++ b/web/app/controllers/webhooks/app_scopes_update_controller.rb @@ -0,0 +1,13 @@ +# frozen_string_literal: true + +module Webhooks + class AppScopesUpdateController < ApplicationController + include ShopifyApp::WebhookVerification + + def receive + webhook_request = ShopifyAPI::Webhooks::Request.new(raw_body: request.raw_post, headers: request.headers.to_h) + AppScopesUpdateJob.perform_later(shop_domain: webhook_request.shop, webhook: webhook_request.parsed_body) + head(:no_content) + end + end +end diff --git a/web/app/jobs/app_scopes_update_job.rb b/web/app/jobs/app_scopes_update_job.rb new file mode 100644 index 0000000..e9cb803 --- /dev/null +++ b/web/app/jobs/app_scopes_update_job.rb @@ -0,0 +1,16 @@ +# frozen_string_literal: true + +class AppScopesUpdateJob < ActiveJob::Base + def perform(shop_domain:, webhook:) + shop = Shop.find_by(shopify_domain: shop_domain) + + if shop.nil? + logger.error("#{self.class} failed: cannot find shop with domain '#{shop_domain}'") + return + end + + logger.info("#{self.class} started for shop '#{shop_domain}'") + shop.access_scopes = webhook["current"].join(",") + shop.save! + end +end diff --git a/web/config/routes.rb b/web/config/routes.rb index d8389dd..5586048 100644 --- a/web/config/routes.rb +++ b/web/config/routes.rb @@ -14,6 +14,7 @@ end namespace :webhooks do post "/app_uninstalled", to: "app_uninstalled#receive" + post "/app_scopes_update", to: "app_scopes_update#receive" post "/customers_data_request", to: "customers_data_request#receive" post "/customers_redact", to: "customers_redact#receive" post "/shop_redact", to: "shop_redact#receive"