sharataka sharataka - 6 months ago 39
Ruby Question

How to dynamically change price charged with Stripe in Rails?

I am trying to integrate Stripe into my Rails app. I followed the tutorial on their website and have most of it working. My 1 question is how to dynamically change the price charged to customers.

Right now @amount is hardcoded at 500. How do I pass @price (from new.html.erb or the controller) to the 'create' action?

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>

Answer

You can either pass @price via the params hash by adding a hidden form field or you can calculate it in your new action in the controller and then store it in a session. Then access that value from the session. For example:

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 

If you go the hidden form field route instead of using sessions you just have to whitelist the hidden field attribute in your controller and it will be passed as part of the params hash with the other form fields values.

Comments