YummyTree
YummyTree

Reputation: 59

Stripe charge create amount to be dynamic

I'm trying to implement a stripe payment, and I know that stripe requires you to set the amount twice. Once at checkout and another on the server side.

I'm using web2py as my framework.

So my question is how do I make them match?

I made the server side dynamic via JS, but I'm struggling to the server side to have the same amount.

# Set your secret key: remember to change this to your live secret key in production
# See your keys here https://dashboard.stripe.com/account/apikeys
stripe.api_key = "sk_test_BQokikJOvBiI2HlWgH4olfQ2"

# Get the credit card details submitted by the form
token = request.POST['stripeToken']

# Create the charge on Stripe's servers - this will charge the user's card
try:
  charge = stripe.Charge.create(
      amount=1000, # how to make this portion match the check out amount
      currency="usd",
      source=token,
      description="Example charge"
  )
except stripe.error.CardError, e:
  # The card has been declined
  pass

is there away to the get more information?

Upvotes: 1

Views: 1526

Answers (1)

Ywain
Ywain

Reputation: 17503

The data-amount and data-currency Checkout configuration options are only used for display purposes. They're irrelevant to the actual charge's amount and currency.

To let your user specify the amount themselves, you could add an amount field to your form, that will be sent along with the "normal" Checkout parameters (stripeToken, stripeEmail, etc.).

Here's a simple JSFiddle to illustrate: https://jsfiddle.net/ywain/g2ufa8xr/

Server-side, all you'd need to do is get the amount from the POST parameters:

try:
  charge = stripe.Charge.create(
    amount=request.POST['amount']
    # ...

Of course, in a real-world scenario, you should validate the amount field, both client-side and server-side. At the very least, you want to make sure that it's:

  • a strictly positive numerical value
  • above the minimum charge amount
  • below a reasonable maximum for your application

Upvotes: 2

Related Questions