Question

I am sure this is very simple, but I cannot figure it out. I am new to stripe and I am configuring it on my website for the first time. I am using the following javascript code from Stripe's library to make charges.

<script src="https://checkout.stripe.com/v2/checkout.js" class="stripe-button"
                data-key="<%= Rails.configuration.stripe[:publishable_key] %>"
                data-description="Qsnag One Time Fee"
                data-amount="<%=@amount*100%>"
                data-email="<%=current_user.email%>">
</script>

As you can see here, my amount is a variable based on what plan the user chooses. My question is how can I access the amount in my charge controller to create a charge. My charges controller code is below

  def create
    customer = Stripe::Customer.create(
      :email => params[:stripeEmail],
      :card  => params[:stripeToken],
      :plan  => @plan_id,
    )

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

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

As you would expect, my @amount in the charges#create is 0. I want to avoid creating a custom form and use the javascript API. Is there a way to access the amount from the javascript API in my charges controller.

Was it helpful?

Solution

I added the amount as a hidden field and put the script in a form tag.

Here is the updated answer:

        <form action="/charge" method="post">
          <script src="https://checkout.stripe.com/v2/checkout.js" class="stripe-button"
                  data-key="<%= Rails.configuration.stripe[:publishable_key] %>"
                  data-description="Qsnag One Time Fee"
                  data-amount="<%=@amount*100%>"
                  data-email="<%=current_user.email%>">
          </script>
          <input type="hidden" name="amount" value="<%=@amount*100%>"/>
          <input type="hidden" name="plan" value="<%=@plan%>"/>
        </form>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top