ruby-on-rails - 在哪里以及如何处理Stripe异常?

标签 ruby-on-rails ruby-on-rails-3 exception-handling stripe-payments

我正在使用Stripe和Ruby on Rails 3.2构建一个小的概念证明。到目前为止,我已经看过Railscast关于如何在RoR应用程序中实现Stripe的功能,并且运行得非常好。

我通过遵循RailsCast #288 Billing with Stripe构建了我的应用程序。现在,我的用户可以添加和编辑其信用卡,甚至可以注册类(class),并在完成类(class)后为其信用卡付款。

现在,我已经在使用Stripe的众多test credit cards进行测试,并且想在引发时捕获尽可能多的异常。我在我的注册模型中使用Stripe的example错误,如下所示:

class Registration < ActiveRecord::Base

  belongs_to :user
  belongs_to :session

  attr_accessible :session_id, :user_id, :session, :user, :stripe_payment_id
  validates :user_id, :uniqueness => {:scope => :session_id}

  def save_with_payment(user, stripe_card_token)
    if valid?
      if user.stripe_customer_id.present?
        charge = Stripe::Charge.create(
            :customer => user.stripe_customer_id,
            :amount => self.session.price.to_i * 100,
            :description => "Registration for #{self.session.name} (Id:#{self.session.id})",
            :currency => 'cad'
        )
      else
        customer = Stripe::Customer.create(
            :email => user.email,
            :card => stripe_card_token,
            :description => user.name
        )
        charge = Stripe::Charge.create(
            :customer => customer.id,
            :amount => self.session.price.to_i * 100,
            :description => "Registration for #{self.session.name} (Id:#{self.session.id})",
            :currency => 'cad'
        )
        user.update_attribute(:stripe_customer_id, customer.id)
      end
      self.stripe_payment_id = charge.id
      save!
    end
  rescue Stripe::CardError => e
    body = e.json_body
    err  = body[:error]
    logger.debug "Status is: #{e.http_status}"
    logger.debug "Type is: #{err[:type]}"
    logger.debug "Code is: #{err[:code]}"
    logger.debug "Param is: #{err[:param]}"
    logger.debug "Message is: #{err[:message]}"
  rescue Stripe::InvalidRequestError => e
    # Invalid parameters were supplied to Stripe's API
  rescue Stripe::AuthenticationError => e
    # Authentication with Stripe's API failed
    # (maybe you changed API keys recently)
  rescue Stripe::APIConnectionError => e
    # Network communication with Stripe failed
  rescue Stripe::StripeError => e
    # Display a very generic error to the user, and maybe send
    # yourself an email
  rescue => e
    # Something else happened, completely unrelated to Stripe
  end
end

我现在只是从错误中解救出来,在被提出后并没有真正采取措施,最终我想停止当前的类注册,并使用Flash错误重定向用户。

我已经读过有关rescure_from的信息,但是我不确定什么是处理所有可能的Stripe错误的最佳方法。我知道无法从模型中重定向,您的专家将如何处理?

这是我的注册 Controller :
class Classroom::RegistrationsController < ApplicationController
  before_filter :authenticate_user!

  def new
    if params[:session_id]
      @session = Session.find(params[:session_id])
      @registration = Registration.new(user: current_user, session: @session)
    else
      flash[:error] = "Course session is required"
    end

    rescue ActiveRecord::RecordNotFound
      render file: 'public/404', status: :not_found

  end

  def create
    if params[:session_id]
      @session = Session.find(params[:session_id])
      @registration = Registration.new(user: current_user, session: @session)
      if @registration.save_with_payment(current_user, params[:stripe_card_token])
        flash[:notice] = "Course registration saved with success."
        logger.debug "Course registration saved with success."
        mixpanel.track 'Registered to a session', { :distinct_id => current_user.id,
                                           :id => @session.id,
                                           'Name' => @session.name,
                                           'Description' => @session.description,
                                           'Course' => @session.course.name
        }
        mixpanel.increment current_user.id, { :'Sessions Registered' => 1}
        mixpanel.track_charge(current_user.id, @session.price.to_i)
      else
        flash[:error] = "There was a problem saving the registration."
        logger.debug "There was a problem saving the registration."
      end
      redirect_to root_path
    else
      flash[:error] = "Session required."
      redirect_to root_path
    end
  end

end

感谢您抽出宝贵的时间回复,非常感谢!

弗朗西斯(Francis)

最佳答案

您是否考虑过将实际的Stripe调用放入自定义验证器中?

http://apidock.com/rails/ActiveModel/Validations/ClassMethods/validate

这样,您可以使用以下内容向对象添加错误

这背后的逻辑是,无论如何,您只想将成功的事务保存为“事务”,为什么不将Stripe费用放入验证器中。

validate :card_validation

def card_validation

    begin
        charge = Stripe::Charge.create(
           :customer => user.stripe_customer_id,
           :amount => self.session.price.to_i * 100,
           :description => "Registration for #{self.session.name} (Id:#{self.session.id})",
           :currency => 'cad'
        )
        etc etc
    rescue => e
      errors.add(:credit_card, e.message)
      #Then you might have a model to log the transaction error.
      Error.create(charge, customer)
    end

end

这样,您就可以像处理从条目中不保存的任何其他错误一样处理这些错误,而不必给出空白错误消息,也不必处理Stripe中的每个最后错误。
class Classroom::RegistrationsController < ApplicationController
  before_filter :authenticate_user!

  def create
    if params[:session_id]
      @session = Session.find(params[:session_id])

      params[:registration][:user] = current_user
      params[:registration][:session] = @session
      params[:registration][:stripe_card_token] = params[:stripe_card_token]

      @registration = Registration.new(params[:registration])
      respond_with(@registration) do |format|
        if @registration.save
          format.html {redirect_to root_path, :notice => "SOMETHING HERE TO TELL THEM SUC"}
        else
          format.html {render}
        end
      end
    else
      respond_with do |format|
        format.html {redirect_to root_path, :error => "SOMETHING HERE TO TELL THEM GET SESSION"}
      end
    end
  end

end

关于ruby-on-rails - 在哪里以及如何处理Stripe异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15824860/

相关文章:

ruby-on-rails - Unicorn 完全忽略 USR2 信号

html - 覆盖其他HTML文件的application.html.erb

ruby-on-rails - Rails 如何使用 where 对多列进行排序?

ruby-on-rails - ActiveRecord 查询中的 "includes"和 "joins"有什么区别?

PHP:异常与错误?

ruby-on-rails - 使用 rails 设置 backbone.js 时为 "SyntaxError: unexpected }"

ruby-on-rails - will_paginate 报告太多条目和页面

java - 在 Java 中,继续调用函数直到没有异常抛出的最佳方式是什么?

ruby-on-rails - rails Assets 管道 "Cannot allocate memory - nodejs"

C#异常处理,使用哪个catch子句?