【问题标题】:Stripe Checkout with Rails Charging Different Amounts使用 Rails 收取不同金额的 Stripe Checkout
【发布时间】:2015-06-28 06:44:14
【问题描述】:

我正在按照 Stripe 的 rails 指南设置基本结帐。我让它工作了,但只花了 5 美元。

找不到有关添加其他金额的文档。我希望一页有 5 美元、10 美元和 15 美元的结帐选项(我正在创建一个捐赠页面)。

我知道我可以为每个付款金额创建多个控制器,但这似乎有点过火了。任何建议将不胜感激。到目前为止,这是我的代码...

charges_controller.rb:

class ChargesController < ApplicationController
  def new
  end

  def create
    # Amount in cents
    @amount = 500

    customer = Stripe::Customer.create(
      :email => 'example@stripe.com',
      :card  => params[:stripeToken]
    )

    charge = Stripe::Charge.create(
      :customer    => customer.id,
      :amount      => @amount,
      :description => 'Rails Stripe customer',
      :currency    => 'usd'
    )

  rescue Stripe::CardError => e
    flash[:error] = e.message
    redirect_to charges_path
  end
end

new.html.erb(收费查看页面):

<%= form_tag charges_path do %>
  <article>
    <label class="amount">
      <span>Amount: $5.00</span>
    </label>
  </article>

  <script src="https://checkout.stripe.com/checkout.js" class="stripe-button"
      data-key="<%= Rails.configuration.stripe[:publishable_key] %>"
      data-description="A month's subscription"
      data-amount="500"></script>
<% end %>

charges.html.erb(布局):

<!DOCTYPE html>
<html>
<head>
</head>
<body>
  <%= yield %>
</body>
</html>

stripe.rb(初始化器):

Rails.configuration.stripe = {
  :publishable_key => ENV['PUBLISHABLE_KEY'],
  :secret_key      => ENV['SECRET_KEY']
}

Stripe.api_key = Rails.configuration.stripe[:secret_key]

routes.rb:

resources :charges

谢谢! Rails 还是新手,所以我猜这很简单。

【问题讨论】:

  • 您需要从视图中发送金额,并在控制器中将其乘以 100 以转换为美分,然后将其传递给条带并完成。

标签: ruby-on-rails ruby-on-rails-3 token payment stripe-payments


【解决方案1】:

如果您在表单中添加一些具有不同数量的单选按钮并从脚本中删除 data-amount,那么它将使用表单中的 amount 值。比如:

<% ["500", "1000", "1500"].each do |amount| %>
  <input type="radio" name="amount" value="<%= amount %>" />
<% end %>

显然,您可能希望使用标签和默认选择对其进行一些修饰,但这种方法可以让您从用户那里获得数量选择。

然后,在您的控制器中,您需要使用传入的金额而不是 @amount 创建您的费用:

charge = Stripe::Charge.create(
  :customer    => customer.id,
  :amount      => params[:amount],
  :description => 'Rails Stripe customer',
  :currency    => 'usd'
)

【讨论】:

  • 但他使用的是form_tag,所以我认为他需要进行很多更改。他需要创建一个form_for 或使用其他东西将金额发送给控制器。
  • 意识到我错过了控制器代码更改。您需要做的就是在调用中使用params[:amount] 来创建费用。
猜你喜欢
  • 2015-07-23
  • 2017-07-18
  • 2018-06-29
  • 2021-05-29
  • 2018-08-15
  • 1970-01-01
  • 2012-08-09
  • 1970-01-01
  • 2019-07-11
相关资源
最近更新 更多