Skip to main content

Integrate Django with Stripe

Learn how to integrate Django with Stripe for payments

Integrating Stripe with Django allows you to accept online payments in your web application.

Integrate Django with Stripe - Tutorial provided by AppSeed.

Stripe is a popular payment processing platform that provides a Python library for easy integration with Django. This page walk you through the process of integrating Stripe with Django and provide code samples.

Set Up Your Stripe Account

Before you begin, make sure you have a Stripe account. You will need your Stripe API keys:

  • Publishable Key: Used in the client-side code to make secure requests to Stripe.
  • Secret Key: Used in the server-side code to interact with Stripe's API.

Install Stripe Library

Install the stripe library, which is the official Python library for Stripe:

pip install stripe

Configure Your Django Settings

In your Django project's settings, add your Stripe API keys:

# settings.py

STRIPE_PUBLISHABLE_KEY = 'your_publishable_key'
STRIPE_SECRET_KEY = 'your_secret_key'

Create a Payment Form

Create a Django form to collect payment information from the user. Here's a simple example:

# forms.py

from django import forms

class PaymentForm(forms.Form):
card_number = forms.CharField(label='Card Number', required=True)
exp_month = forms.IntegerField(label='Expiration Month', required=True)
exp_year = forms.IntegerField(label='Expiration Year', required=True)
cvc = forms.CharField(label='CVC', required=True)

Create a Payment View

Create a Django view that handles the payment process. This view will use the Stripe library to process the payment.

# views.py

import stripe
from django.conf import settings
from django.shortcuts import render, redirect
from .forms import PaymentForm

stripe.api_key = settings.STRIPE_SECRET_KEY

def process_payment(request):
if request.method == 'POST':
form = PaymentForm(request.POST)
if form.is_valid():
# Get token from the form data (generated by Stripe.js)
token = request.POST['stripeToken']

try:
# Charge the customer
charge = stripe.Charge.create(
amount=1000, # Amount in cents
currency='usd',
description='Example Charge',
source=token,
)

# If the charge is successful, you can handle success here
return redirect('payment_success')

except stripe.error.CardError as e:
# If there's an issue with the user's card, handle it here
error_message = e.error.message
return render(request, 'payment_form.html', {'form': form, 'error_message': error_message})

else:
form = PaymentForm()

return render(request, 'payment_form.html', {'form': form})

Create a Payment Template

Create an HTML template (e.g., payment_form.html) to display the payment form and handle user input. You can use Stripe.js to securely collect card information and generate a token, which is sent to your server.

<!-- payment_form.html -->

<form action="{% url 'process_payment' %}" method="POST">
{% csrf_token %}
{{ form.as_p }}
<script src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="{{ STRIPE_PUBLISHABLE_KEY }}"
data-description="Payment"
data-amount="1000" <!-- Amount in cents -->
data-locale="auto">
</script>
{% if error_message %}
<p>{{ error_message }}</p>
{% endif %}
</form>

Create a Success Page

Create a success page to display after a successful payment:

<!-- success.html -->

<h1>Payment Successful</h1>

Set Up URLs

Configure your Django project's URLs to route requests to the appropriate views:

# urls.py

from django.urls import path
from . import views

urlpatterns = [
path('process_payment/', views.process_payment, name='process_payment'),
path('payment_success/', views.payment_success, name='payment_success'),
]

Run Django Application

Start your Django development server and navigate to the payment form page. You should be able to make test payments using the Stripe test card numbers provided in the Stripe documentation.

✅ Conclusion

Remember that this is a basic example, and in a production environment, you should handle errors and security more robustly. Additionally, you may want to implement order processing and store payment information securely.

Make sure to refer to the Stripe documentation for more detailed information on integrating Stripe with Django and handling various aspects of online payments.

✅ Resources