我在我的应用程序中使用Stripe Checkout。我想这样做,以便当访客用户想要购买商品时,他们会被要求创建一个帐户。创建帐户后,他们将收取费用并为他们创建收据。
对于非访客用户,我的Stripe付款会按照我想要的方式运行。我想要做的是,一旦我在用户控制器的创建操作中创建了用户,将其基本上POST到我的充电控制器的创建操作,以便在他们创建他们的时候自动收费帐户。
但是阅读它似乎在控制器之间发布是一件非常非常有用的事情。所以我不确定我应该如何做到这一点,以便它与MVC模式合作。在我看来,访客用户已经点击购买机票,所以只有在他们不应该再次点击进行操作时才有意义。
如果不将我的充电控制器中的大量代码复制到我的用户控制器的创建操作中,我无法看到一个简洁的方法来执行此操作 - 但这似乎很荒谬。我有更好的方法吗?
答案 0 :(得分:1)
我建议将费用操作放入自己的模型中,例如Payment
或Charge
,这样您就可以通过传递必要的参数来调用操作。例如
class Payment < ActiveRecord::Base
def self.charge(amount, token)
charge = Stripe::Charge.create({
:amount => amount * 100, # Amount is based in cents
:source => token, # Could be existing credit card token or JS Stripe token
:currency => "usd",
:description => "Test Charge"
})
end
end
然后从任何控制器中你可以这样称呼它:
class UsersController < ApplicationController
def create
user = User.new(user_params)
if user.save
add_to_flash = ""
# You could do another conditional here to check if the card should be processed
if params[:card_should_charged]
Payment.charge("1200", "tok_8asdfa9823r23") #=> $12.00 and the charge token
add_to_flash = " and your payment was accepted"
end
flash[:notice] = "Your account was created" + add_to_flash + "."
redirect_to whatever_path
else
flash[:error] = "Failed to create user."
render :new
end
end
end
您显然必须自己创建条件,最有可能在视图中创建条件,并在提交用户创建表单时将其传递。
如果您需要在没有表格的情况下生成Payment
模型(如果您只是想使用模型来处理付款,而不是存储它们),那么您可以使用:
rails g model Payment --no-migration
生成它。