【问题标题】:Shopify App causing return code 302Shopify 应用程序导致返回码 302
【发布时间】:2016-10-23 17:48:08
【问题描述】:

我有这段代码在我的 Shopify 商店中创建新订单时触发:

class CustomwebhooksController < ShopifyApp::WebhooksController 
  #the line below is to avoid the CSR error
  protect_from_forgery with: :null_session, if: Proc.new { |c| c.request.format == 'application/json' }

  include ShopifyApp::WebhookVerification

  # This method is triggered when the user completes the checkout process
  # Gets the order number and see the message "Your order is confirmed" 
  # I should use this as the trigger to update the other SKU for the DT solution:
  def orders_create
    request.body.rewind
    data = JSON.parse(request.body.read)

    #redirect_to controller: "home", action: "update_stock", status: :found

    @MyHomeController = HomeController.new
    @MyHomeController.update_stock

    #do not remove line below
    head :ok

  end

end

这是我家控制器中的代码:

class HomeController < ShopifyApp::AuthenticatedController
  def update_stock
    @products = ShopifyAPI::Product.find(:all, :params => {:title => 'DT382'})
    @products.each do |product|
      puts(product.id)
    end  
  end      
end

不知何故,对@MyHomeController.update_stock 的调用会生成如下所示的 302:

渲染的内联模板(0.4ms) 完成 302 发现时间为 689 毫秒(查看次数:0.9 毫秒 | ActiveRecord:0.0 毫秒)

我错过了什么吗?

【问题讨论】:

  • 您应该格式化/缩进代码部分以获得更好的可读性。
  • "HTTP 响应状态码 302 Found 是执行 URL 重定向的常用方法。具有此状态码的 HTTP 响应将在位置标头字段中额外提供 URL。用户代理(例如 Web浏览器)被带有此代码的响应邀请向位置字段中指定的新 URL 发出第二个(否则相同)请求。HTTP/1.0 规范 (RFC 1945) 最初定义了此代码,并为其提供了描述短语“临时搬家”。
  • here

标签: ruby-on-rails shopify


【解决方案1】:

我想挑战一下你的设计。

首先,如果您要重定向到不同的控制器/动作,为什么不使用redirect_to update_stock_path,路径在您的路由文件中指定?

其次,为什么要重定向?您正在接收带有一些有效负载的 webhook,然后您需要点击 Shopify API 以获取产品数据。对我来说,这更适合作为后台工作。此外,将其设计为 receive webhook -&gt; schedule background job -&gt; do work in the job 将比您现在所做的更具可扩展性。

【讨论】:

  • 感谢您的回复。
  • 感谢您的回复。我确实尝试使用redirect_to。它似乎有效,但 update_stock 方法中的代码永远不会被执行。尽管我有使用 Objective-C 的经验,但我是 Rails 的新手。您能否指出一些有关如何使用 Rails 对 Shopify webhook 进行编程的资源?
【解决方案2】:

在仔细阅读 Shopify API 文档后,我设法找出了解决方案。

类 HomeController https://#{ENV['API_KEY']}:#{ENV['API_SECRET']}@myshopifyshop.myshopify.com/admin" ShopifyAPI::Base.site = shop_url @products = ShopifyAPI::Product.find(:all, :params => {:title => 'DT382'}) @products.each 做 |产品| 放置(产品.id) 结束
ShopifyAPI::Base.clear_session 结束
结束

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-25
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 2021-04-13
    • 2017-11-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多