Ad

Shopify Rails App Retrieve Session From SessionRepository With Shop Domain

- 1 answer

I'm attempting to create a Proxy App by creating a new session in my controller. The proxy controller is given one parameter: the shop's myshopify.com domain. Using this, I would like to retrieve that shop's session from my Session Repository and instantiate the session.

This is what my code looks like now

class ProxyController < ActionController::Base
  def index
    shop_domain = params[:shop]
    #puts ShopifyApp::SessionRepository.methods.sort
    shop = ShopifyApp::SessionRepository.retrieve(shop_domain)
    ShopifyAPI::Base.activate_session(shop)

This is the ShopifyApp::SessionRepository class

module ShopifyApp
  class SessionRepository
    class ConfigurationError < StandardError; end

    class << self
      def storage=(storage)
        @storage = storage

        unless storage.nil? || self.storage.respond_to?(:store) && self.storage.respond_to?(:retrieve)
          raise ArgumentError, "storage must respond to :store and :retrieve"
        end
      end

      def retrieve(id)
        storage.retrieve(id)
      end

      def store(session)
        storage.store(session)
      end

      def storage
        load_storage || raise(ConfigurationError.new("ShopifySessionRepository.storage is not configured!"))
      end

      private

      def load_storage
        return unless @storage
        @storage.respond_to?(:safe_constantize) ? @storage.safe_constantize : @storage
      end
    end
  end
end

And this is the storage module.

module ShopifyApp
  module SessionStorage
    extend ActiveSupport::Concern

    class_methods do
      def store(session)
        shop = self.find_or_initialize_by(shopify_domain: session.url)
        shop.shopify_token = session.token
        shop.save!
        shop.id
      end

      def retrieve(id)
        return unless id

        if shop = self.find_by(id: id)
          ShopifyAPI::Session.new(shop.shopify_domain, shop.shopify_token)
        end
      end
    end

  end
end

So retrieve requires the ID of the shop in my database (like 3) rather than the shop's domain (like dev-store.myshopify.com).

I'm looking for a way to retrieve/create a session on my proxy controller, by modifying the Shop model so I can retrieve it with the shop domain, or any other way to create a session that will allow me to use API calls on my proxy controller.

Ad

Answer

I know this old, but I was having issues with this earlier. There aren't too many helpful solutions.

This worked for me:

shop = Shop.find_by(shopify_domain: params[:shop])
shop = ShopifyApp::SessionRepository.retrieve(shop.id)
ShopifyAPI::Base.activate_session(shop)

You should be able to find your shop by domain in the db. Thus being able to grab the specific id.

Ad
source: stackoverflow.com
Ad