我是 Rails 新手,也是活跃商家的新手,只想知道以下代码是否足以使用活跃商家进行支付处理。
如您所见,我使用的是授权和捕获而不是购买方法。我主要关心的是代码中的“brought_quantity”减法(当支付处理失败时,它是对应的部分),我不太确定在竞争条件或支付网关错误的情况下如何处理它。
请注意,变量 transactions 是模型/表的实例变量,我在其中存储支付网关响应的信息。
def purchase(item)
price = price_in_cents(item.value)
if !item.can_purchase
errors[:base] << "We are sorry, all items are sold out at the moment."
return false
else
response = GATEWAY.authorize(price, credit_card, purchase_options)
transactions.create!(:action => "authorize", :value => price, :params => response)
#p response
if response.success?
item.brought_quantity = item.brought_quantity + 1
if item.save!
response = GATEWAY.capture(price, response.authorization)
transactions.create!(:action => "capture", :value => price, :params => response)
if !response.success?
errors[:base] << "There were some problem processing your payment, please either try again or contact us at support@foo.com with this error id: 111"
@rd = RunningDeal.find_by_id(@item.id)
@rd.brought_quantity = @rd.brought_quantity - 1
@rd.save!
return false
end
else
errors[:base] << "We are sorry, all items are sold out at the moment."
return false
end
else
# problem process their payment, put out error
errors[:base] << "There were some problem processing your payment, please either try again or contact us at support@foo.com with this error id: 111"
return false
end
end
return true
end
编辑 好的,做了一些重构,这里是更新的代码,欢迎任何意见和建议。我删除了!在 transaction.create 上,因为这不是一个足够重要的操作来引发异常。
这是基于反馈的更新代码。
#from running_deal.rb
def decrement_deal_quantity
self.brought_quantity = self.brought_quantity + 1
return self.save!
end
def purchase(running_deal)
price = price_in_cents(running_deal.value)
if !running_deal.can_purchase
errors[:base] << "We are sorry, all items are sold out at the moment."
return false
else
auth_resp = GATEWAY.authorize(price, credit_card, purchase_options)
transactions.create(:action => "authorize", :value => price, :success => auth_resp.success?, :message => auth_resp.message, :authorization => auth_resp.authorization, :params => auth_resp)
if auth_resp.success?
begin
running_deal.decrement_deal_quantity
cap_resp = GATEWAY.capture(price, auth_resp.authorization)
transactions.create(:action => "capture", :value => price, :success => cap_resp.success?, :message => cap_resp.message, :authorization => cap_resp.authorization, :params => cap_resp)
rescue
GATEWAY.void(auth_resp.authorization, purchase_options) if auth_resp.success?
errors[:base] << "There were some problem processing your payment, please either try again or contact us at support@foo.com"
return false
end
else
# problem process their payment, put out error
errors[:base] << "There were some problem processing your payment, please either try again or contact us at support@foo.com"
return false
end
end
return true
结尾