如何动态更改 Rails 中 Stripe 收取的价格?

How to dynamically change price charged with Stripe in Rails?

我正在尝试将 Stripe 集成到我的 Rails 应用程序中。我按照他们网站上的教程进行操作,并且大部分都在工作。我的第一个问题是如何动态更改向客户收取的价格。

现在@amount 硬编码为 500。如何将 @price(从 new.html.erb 或控制器)传递给 'create' 操作?

def new
    @project = Project.find(params[:project_id])
    number_of_testers = @project.testers
    @price = 30 * number_of_testers
end

def create
  # Amount in cents
  # @amount = 500



  customer = Stripe::Customer.create(
    :email => params[:stripeEmail],
    :source  => 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 new_charge_path
end

new.html.erb

<center>
    <%= form_tag charges_path do %>

      <article>
        <% if flash[:error].present? %>
          <div id="error_explanation">
            <p><%= flash[:error] %></p>
          </div>
        <% end %>
        <label class="amount">
          <span>Amount: $<%= @price %></span>
        </label>
      </article>

        <script src="https://checkout.stripe.com/checkout.js" class="stripe-button"
          data-key="<%= Rails.configuration.stripe[:publishable_key] %>"
          data-description="Buy usability testing credits"
          data-amount="<%= @price*100 %>"
          data-locale="auto"></script>
    <% end %>

</center>

您可以通过添加隐藏表单字段通过参数散列传递@price,也可以在控制器的新操作中计算它,然后将其存储在会话中。然后从会话中访问该值。例如:

def new
  @price = 30 * number_of_testers
  session[:price] = @price
end

def create
  @amount = session[:price] 
  ...rest of your code here...
  session.delete(:price)
end 

如果您使用隐藏的表单字段路由而不是使用会话,您只需将控制器中的隐藏字段属性列入白名单,它将作为参数散列的一部分与其他表单字段值一起传递。

为什么不使用 number_field_tag :amount 将您的金额发送回参数中的控制器 create 方法?

但是从下面的js脚本看来,你实际上需要将总数发送到stripe,这意味着如果你的价格在表格中发生变化,你将需要重新加载在js中发送的值,所以你可能您的号码字段还需要一个 onChange属性。它将调用一个 js 函数,该函数将获取新值并将其发送到 stripe。