1

我正在尝试将我的 Ruby on Rails 应用程序与 CheddarGetter 使用他们的托管支付页面(http://support.cheddargetter.com/kb/hosted-payment-pages/hosted-payment-pages-setup-guide)集成。

除了最后一部分——检查客户数据与他们的 API 以确保客户在让他登录您的系统之前仍然处于活动状态,我几乎已经弄清楚了所有事情。

显然它涉及某种 HTTP 请求,老实说我一点也不熟悉,抱歉。这是代码:

uri = URI.parse("https://yoursite.chargevault.com/status?key=a1b2c3d4e6&code=yourcustomercode")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
request = Net::HTTP::Get.new(uri.request_uri)
status = http.request(request).body

我想知道我到底把这段代码放在哪里?

我正在考虑将以下内容放入我的user_session.rb模型中:

class UserSession < Authlogic::Session::Base
  before_create :check_status

  private
  def check status
      # insert above code here
  end
end

但我不太确定..?我怀疑那里还必须有一些if active? elsif cancelled? && pending?代码,指的是 CheddarGetter API 会给你的响应..

希望给点指导,谢谢..

4

1 回答 1

1

我建议将它放在/lib目录中它自己的模块中,并将调用包装在 aTimeout中,以防您尝试访问的网站不可用。我只是在下面做了一个通用示例,因此您可以根据需要调整时间。

/lib/customer_status.rb 内部

require 'timeout'
module CustomerStatus
  class << self
    def get_status
      begin
        Timeout::timeout(30) {
          uri = URI.parse("https://yoursite.chargevault.com/status?key=a1b2c3d4e6&code=yourcustomercode")
          http = Net::HTTP.new(uri.host, uri.port)
          http.use_ssl = true
          http.verify_mode = OpenSSL::SSL::VERIFY_NONE
          request = Net::HTTP::Get.new(uri.request_uri)
          status = http.request(request).body
        } # end timeout

        return status

      rescue Exception => e
        # This will catch a timeout error or any other network connectivity error
        Rails.logger.error "We had an error getting the customer's status: #{e}"
      end
    end
  end
end

然后你可以这样称呼它:

class UserSession < Authlogic::Session::Base
  # include the new module we added
  include CustomerStatus

  before_create :check_status

  private
  def check status
    raise someError unless (CustomerStatus.get_status.include?("active"))
  end
end

我会让你为cancelled, pendingetc 状态添加其他逻辑,以及将客户信息传递给新的模块方法。您可能只想使用 switch 语句来处理不同的状态。


更新

此外,如果您的文件中还没有此config/application.rb文件,请确保包含它,以便将lib文件夹添加到自动加载路径:

module YourAppNameGoesHere
  class Application < Rails::Application

    # Custom directories with classes and modules you want to be autoloadable.
    config.autoload_paths += %W(#{config.root}/lib)

  end
end
于 2011-12-22T16:50:43.320 回答