Public Shopify Rails App

0

class PagesController < ApplicationController

  def install 
    app_url    = "xxx.ngrok.io"
    scope      = "read_orders, write_products"

    api_secret = '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'
    state      = OpenSSL::HMAC.hexdigest("SHA256", api_secret, 'yyy')

    # url = "https://#{shop}/admin/oauth/authorize?client_id=#{api_key}&scope=#{scope}&redirect_uri=https://#{app_url}/shopify/auth&state=#{state}"
    url = shopify_session.create_permission_url(scope, "https://#{app_url}/shopify/auth", { state: state })

    redirect_to url, allow_other_host: true
  end

  def auth
    @valid_hmac  = validate_hmac( request)
    @valid_state = validate_state(request)
    token = shopify_session.request_token(request.params)
  end

  def rest
    shop  = 'yyyy.myshopify.com'
    token = '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'
    session = ShopifyAPI::Session.new(domain: shop, api_version: "2022-01", token: token)
    ShopifyAPI::Base.activate_session(session)

    shop = ShopifyAPI::Shop.current
    p1   = ShopifyAPI::Product.first
    p2   = ShopifyAPI::Product.last

    p1.title = "Test Title"
    p1.save

    @content = "#{shop.name} #{p1.title} #{p2.title} #{p2.variants.first.sku} #{p2.variants.first.inventory_quantity}"
  end

  private
  def shopify_session
    api_key    = '54f08615e958a48f199b98f611893189'
    api_secret = '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'
    shop       = 'yyyy.myshopify.com'

    ShopifyAPI::Session.setup(api_key: api_key, secret: api_secret)
    @shopify_session ||= ShopifyAPI::Session.new(domain: shop, api_version: '2022-01', token: nil)
  end
  def validate_hmac(request)
    key  = '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'
    data = request.query_parameters.except(:hmac).to_query
    mac  = OpenSSL::HMAC.hexdigest("SHA256", key, data)
    ActiveSupport::SecurityUtils.secure_compare(mac, request[:hmac])
  end
  def validate_state(request)
    api_secret = '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'
    ActiveSupport::SecurityUtils.secure_compare(OpenSSL::HMAC.hexdigest("SHA256", api_secret, 'yyy'), request[:state])
  end
end

  • 0 posts
  • 0 subtopics
  • 3 months ago by vince