Rails,Stripe,什么时候POST向控制器收费
Rails, Stripe, when to POST to Charges controller
我在我的应用程序中使用 Stripe Checkout。我想这样做,以便当来宾用户想要购买商品时,他们会被要求创建一个帐户。创建帐户后,系统会向他们收费并为其创建收据。
对于非访客用户,我的 Stripe 付款完全按照我想要的方式运行。我想做的是,一旦我在我的用户控制器的创建操作中创建了用户,就基本上 POST 我的收费控制器的创建操作,以便在他们创建他们的帐户时自动进行收费。
但阅读周围似乎在控制器之间发帖是一件非常不 rails 的事情。所以我不确定我应该怎么做才能与 MVC 模式合作。在我看来,来宾用户已经点击购买了机票,所以他们不必再次点击才有意义。
如果不从我的收费控制器的创建操作中将大量代码复制到我的用户控制器的创建操作中,我无法找到一种巧妙的方法来执行此操作 - 但这似乎很荒谬。我有更好的方法吗?
我建议将充电操作放入其自己的模型中,例如 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") #=> .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
您显然必须自己创建条件,很可能是在视图中,并在提交用户创建表单时将其传入。
如果您需要生成没有 table 的 Payment
模型(如果您只想使用该模型来处理付款,而不是存储它们),那么您可以使用:
rails g model Payment --no-migration
生成它。
我在我的应用程序中使用 Stripe Checkout。我想这样做,以便当来宾用户想要购买商品时,他们会被要求创建一个帐户。创建帐户后,系统会向他们收费并为其创建收据。
对于非访客用户,我的 Stripe 付款完全按照我想要的方式运行。我想做的是,一旦我在我的用户控制器的创建操作中创建了用户,就基本上 POST 我的收费控制器的创建操作,以便在他们创建他们的帐户时自动进行收费。
但阅读周围似乎在控制器之间发帖是一件非常不 rails 的事情。所以我不确定我应该怎么做才能与 MVC 模式合作。在我看来,来宾用户已经点击购买了机票,所以他们不必再次点击才有意义。
如果不从我的收费控制器的创建操作中将大量代码复制到我的用户控制器的创建操作中,我无法找到一种巧妙的方法来执行此操作 - 但这似乎很荒谬。我有更好的方法吗?
我建议将充电操作放入其自己的模型中,例如 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") #=> .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
您显然必须自己创建条件,很可能是在视图中,并在提交用户创建表单时将其传入。
如果您需要生成没有 table 的 Payment
模型(如果您只想使用该模型来处理付款,而不是存储它们),那么您可以使用:
rails g model Payment --no-migration
生成它。