我是新來的rails和新的活動商家,只是想知道下面的代碼是否足夠支付使用活動商家的處理。rails 3有效的商戶採購代碼
正如您所看到的,我正在使用授權和捕獲來代替購買方法。我主要關心的是代碼中的「帶來數量」減法(當付款處理失敗時它是相反的部分),但我不太清楚如果在支付網關存在競爭條件或錯誤的情況下如何處理它。
請注意,變量事務是模型/表的實例變量,用於存儲支付網關響應的信息。
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 [email protected] 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 [email protected] 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 [email protected]"
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 [email protected]"
return false
end
end
return true
端
你的問題是什麼? – Eric 2011-05-19 18:37:35