mardi 21 avril 2015

Stripe Checkout with Rails Charging Different Amounts

I am following Stripe's rails guide to set up a basic checkout. I got it to work, but only for one amount of $5.

Having trouble finding documentation on adding another amount. I want one page to have a $5, $10 and $15 checkout option (i am creating a donate page).

I know I can create multiple controllers for each payment amount but that seems a bit overboard. Any suggestions would be more than appreciated. Here is my code so far...

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 (charge view page):

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

  <script src="http://ift.tt/1doUtf9" class="stripe-button"
      data-key="<%= Rails.configuration.stripe[:publishable_key] %>"
      data-description="A month's subscription"
      data-amount="500"></script>
<% end %>

charges.html.erb (layouts):

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

stripe.rb (initializer):

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

Thank you! Still new to rails so I'm guessing this is something simple.

Aucun commentaire:

Enregistrer un commentaire