我建議將充電動作放入其自己的模型中,例如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
生成它。
這太神奇了!非常感謝。這是一個很好的通用方法。 – Dennis
我可以問一個快速相關的問題讓我放心嗎?目前,我傳遞的參數的負載,以註冊表單視圖 - 的URL看起來像「HTTP://本地主機:3000 /註冊額= 75306&電子郵件=電子郵件%40email.com&stripeToken = tok_17CD5iF5yf5JD010v47usr7G&ticket_purchase =真正的」 - 這是一個好辦法保持這些參數?安全權不應該存在任何問題,因爲只要我的條帶私鑰仍然是私有的,如果有人獲得了條帶標記,這並不重要。 – Dennis