request
object in Flask is used to access incoming data such as form data or JSON payloads. The response
is what the server sends back to the client, which can be HTML, JSON, or other types of data.First, make sure you have Flask installed. If not, you can install it using pip
:
pip install flask
Here is a basic Flask application structure:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return "Welcome to the Flask - Stripe integration app!"
if __name__ == '__main__':
app.run(debug=True)
In this code:
Flask
class from the flask
module.Flask
class named app
./
). When a user visits this URL, the index
function is called, which returns a simple welcome message.Install the Stripe Python library using pip
:
pip install stripe
import stripe
from flask import Flask, request, jsonify
# Set your Stripe API keys
stripe.api_key = "YOUR_SECRET_KEY"
app = Flask(__name__)
@app.route('/create-payment-intent', methods=['POST'])
def create_payment_intent():
try:
data = request.get_json()
amount = data.get('amount')
currency = data.get('currency', 'usd')
# Create a PaymentIntent
intent = stripe.PaymentIntent.create(
amount=amount,
currency=currency
)
return jsonify({
'clientSecret': intent.client_secret
})
except Exception as e:
return jsonify(error=str(e)), 403
if __name__ == '__main__':
app.run(debug=True)
In this code:
stripe
library and necessary Flask modules./create - payment - intent
that accepts POST requests.amount
and currency
from the JSON data sent by the client.PaymentIntent
using the Stripe API.client_secret
of the PaymentIntent
to the client in JSON format.We’ll use Stripe.js to handle the payment form on the client - side. Here is an example HTML file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF - 8">
<title>Stripe Payment</title>
<script src="https://js.stripe.com/v3/"></script>
</head>
<body>
<form id="payment - form">
<div id="payment - element"></div>
<button id="submit">Pay</button>
</form>
<script>
const stripe = Stripe('YOUR_PUBLISHABLE_KEY');
const elements = stripe.elements();
const paymentElement = elements.create('payment');
paymentElement.mount('#payment - element');
const form = document.getElementById('payment - form');
form.addEventListener('submit', async (event) => {
event.preventDefault();
const { clientSecret } = await fetch('/create - payment - intent', {
method: 'POST',
headers: {
'Content - Type': 'application/json'
},
body: JSON.stringify({ amount: 1000, currency: 'usd' })
}).then((r) => r.json());
const { error } = await stripe.confirmPayment({
elements,
clientSecret,
confirmParams: {
return_url: 'https://your - website.com/success'
}
});
if (error) {
console.log(error.message);
} else {
console.log('Payment successful!');
}
});
</script>
</body>
</html>
In this HTML code:
PaymentElement
and mount it to the payment - element
div./create - payment - intent
route on the server to get the client_secret
.client_secret
to confirm the payment using stripe.confirmPayment
.amount
and currency
values are correctly set on both the client - side and server - side. Incorrect values can lead to payment failures or incorrect charges.PaymentIntent
creation fails on the server, the client should be informed with a meaningful error message.os
module to access environment variables:import os
stripe.api_key = os.getenv('STRIPE_SECRET_KEY')
Integrating Stripe payments in a Flask application is a powerful way to add payment functionality to your web projects. By understanding the core concepts, following the steps for integration, and being aware of common pitfalls and best practices, you can create a secure and reliable payment system. Whether you’re building an e - commerce site, a subscription service, or a donation platform, this integration can help you accept payments smoothly and efficiently.