簡體   English   中英

如何動態更改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>

為什么不使用number_field_tag :amount將您的number_field_tag :amount以參數形式發送回控制器create方法?

但是從下面的js腳本看來,您實際上確實需要將總數發送到stripe,這意味着,如果您的價格在表單中發生變化,那么您還需要重新加載以js發送的值,因此您可能還需要onChange屬性為您的數字字段。 它將調用一個js函數,該函數將獲取新值並將其發送到stripe。

您可以通過添加隱藏的表單字段通過params哈希傳遞@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 

如果您使用隱藏表單域路由而不是使用會話,則只需在控制器中將隱藏域屬性列入白名單,該屬性將作為參數散列的一部分與其他表單域值一起傳遞。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM