私はレールを初めて使用し、アクティブなマーチャントを初めて使用します。次のコードがアクティブなマーチャントを使用した支払い処理に十分かどうかを知りたいだけです。
ご覧のとおり、購入方法の代わりにオーソライズ アンド キャプチャを使用しています。私の主な懸念は、コード内の「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
編集 OK、いくつかのリファクタリングを行いました。これが更新されたコードです。コメントや提案は大歓迎です。を削除しました ! これは、例外を発生させるほど重要な操作ではないためです。
フィードバックに基づいて更新されたコードを次に示します。
#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
終わり