Stripe is a payment infrastructure platform that simplifies the process of accepting payments online. It provides APIs for various payment methods, including credit cards, digital wallets (such as Apple Pay and Google Pay), and bank transfers. Stripe handles the complex tasks of payment processing, fraud prevention, and compliance, allowing developers to focus on building their applications.
Django is a Python web framework that follows the Model - View - Template (MVT) architectural pattern. It provides built - in features such as user authentication, database management, and URL routing, which can be leveraged when integrating Stripe payments.
Payment Intents are a key concept in Stripe. A Payment Intent represents an attempt to collect payment from a customer. It tracks the lifecycle of a payment, from creation to capture, and handles scenarios such as 3D Secure authentication.
First, you need to install the stripe
Python library in your Django project. You can use pip
to install it:
pip install stripe
In your Django project’s settings.py
file, add your Stripe keys:
# settings.py
import os
# Stripe keys
STRIPE_PUBLIC_KEY = os.environ.get('STRIPE_PUBLIC_KEY')
STRIPE_SECRET_KEY = os.environ.get('STRIPE_SECRET_KEY')
# It's a good practice to use environment variables to store sensitive information.
# You can set these variables in your local environment or in your server's environment.
Create a view in your Django app to handle the creation of a Payment Intent:
# views.py
import stripe
from django.conf import settings
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
stripe.api_key = settings.STRIPE_SECRET_KEY
@csrf_exempt
def create_payment_intent(request):
try:
# Get the amount from the request (you may need to adjust this based on your application)
amount = 1000 # Amount in cents
currency = 'usd'
# Create a PaymentIntent
intent = stripe.PaymentIntent.create(
amount=amount,
currency=currency,
automatic_payment_methods={
'enabled': True,
},
)
return JsonResponse({
'clientSecret': intent.client_secret
})
except Exception as e:
return JsonResponse({'error': str(e)}, status=400)
On the client - side, you can use the Stripe.js library to collect payment information and confirm the Payment Intent. Here is a simple example using JavaScript:
<!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">
<!-- Stripe.js will inject the payment fields here -->
</div>
<button id="submit">Pay</button>
</form>
<script>
const stripe = Stripe('{{ settings.STRIPE_PUBLIC_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'
}
}).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 {
// Payment succeeded
window.location.href = 'https://your - website.com/success';
}
});
</script>
</body>
</html>
On the server - side, you can create views to handle the success and failure of payments:
# views.py
from django.shortcuts import render
def payment_success(request):
return render(request, 'success.html')
def payment_failure(request):
return render(request, 'failure.html')
stripe
Python library to ensure that you have the latest security patches and features.Integrating Stripe payments in a Django app can provide a secure and seamless payment experience for your users. By following the steps outlined in this blog post and avoiding common pitfalls, you can successfully implement payment processing in your Django application. Remember to test your integration thoroughly and follow best practices to ensure a smooth and reliable payment process.