22
loading...
This website collects cookies to deliver better user experience
Always. use. tokens! Never EVER send a customers raw credit card information to your server. It's unsafe and requires a thing called PCI compliance, which is a headache to obtain and maintain.
<script src="https://js.stripe.com/v2/"></script>
<script>
Stripe.setPublishableKey('your_test_publishable_key');
const card = {
name: nameOnCard, // Use JavaScript to get the <input> text value
number: cardNumber,
cvc: cardCvc,
exp_month: cardExpMonth,
exp_year: cardExpYear,
address_line1: address1,
address_line2: address2, // Optional
address_city: city,
address_state: state,
address_country: country,
currency: 'usd',
address_zip: postalCode
}
Stripe.card.createToken(card, stripeResponseHandler);
function stripeResponseHandler(status, response) {
if (response.error) {
// Problem!
// Show the error
alert(response.error.message);
} else {
// Token was created!
// Get the token ID:
const token = response.id;
// TODO: Ajax the token to your backend/server
// Make sure you create a POST request and not a GET request
}
}
<form>
because that could be submitted by accident and could share credit card info in a POST or GET request.eventListener
to a button click
event, perform some light frontend validation to make sure fields aren't missing and are formatted correctly. import stripe
stripe.api_key = "sk_test_blah_blah_blah"
# `source` is obtained with Stripe.js this is your "token"
charge = stripe.Charge.create(
amount=2000, # Value in pennies, so this is 20.00
currency="usd",
source=request.POST.get("token"),
description="A test token payment of $20.00 USD",
)
Pro tip: Wrap the stripe.Charge.create() method in a try/catch block.
try:
charge = stripe.Charge.create(
amount=2000, # Value in pennies, so this is 20.00
currency="usd",
source=request.POST.get("token"),
description="A test token payment of $20.00 USD",
)
except stripe.error.CardError as e:
# Since it's a decline, stripe.error.CardError will be caught
...
except stripe.error.InvalidRequestError as e:
# Invalid parameters were supplied to Stripe's API
...
except stripe.error.AuthenticationError as e:
# Authentication with Stripe's API failed
# (maybe you changed API keys recently)
# Log the failed transaction in the users account
...
except stripe.error.StripeError as e:
# Display a very generic error to the user
...
except Exception as e:
# Something else happened, completely unrelated to Stripe
print(type(e))
print(e)
charge
(from the code above) and it'll hold A LOT of useful information you can store for later, including an id
that always starts with ch_
- this can be used later for issuing refunds. id
that Stripe gives you - save it in your database. This isn't considered sensitive information so you can plop it in your database without worries. Remember: These keys work together. Use both testing keys together, or use both live keys together, but don't mix and match them.