Integrating Stripe Payments in a Django App

In today’s digital age, online payment processing is a crucial feature for many web applications. Stripe is a popular and developer - friendly payment gateway that allows businesses to accept payments from customers around the world. Django, on the other hand, is a high - level Python web framework that enables rapid development of secure and maintainable websites. Integrating Stripe payments into a Django app can provide a seamless payment experience for your users. In this blog post, we will explore the core concepts, typical usage scenarios, common pitfalls, and best practices for integrating Stripe payments in a Django application.

Table of Contents

  1. Core Concepts
  2. Typical Usage Scenarios
  3. Prerequisites
  4. Step - by - Step Integration
    • Installing Required Libraries
    • Stripe Account Setup
    • Django Settings Configuration
    • Creating a Payment View
    • Handling Payment Success and Failure
  5. Common Pitfalls
  6. Best Practices
  7. Conclusion
  8. References

Core Concepts

Stripe

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

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

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.

Typical Usage Scenarios

  • E - commerce Websites: Accept payments for products or services sold on an online store.
  • Subscription - Based Services: Charge customers on a recurring basis for access to premium content or features.
  • Donation Platforms: Allow users to make one - time or recurring donations to a cause or organization.

Prerequisites

  • A Django project set up on your local machine or a server.
  • A Stripe account. You can sign up for a free account at Stripe .
  • Basic knowledge of Python and Django.

Step - by - Step Integration

Installing Required Libraries

First, you need to install the stripe Python library in your Django project. You can use pip to install it:

pip install stripe

Stripe Account Setup

  1. Log in to your Stripe account.
  2. Navigate to the “Developers” section and click on “API keys”.
  3. Here, you will find your publishable key and secret key. The publishable key is used on the client - side, and the secret key is used on the server - side. Keep your secret key secure.

Django Settings Configuration

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.

Creating a Payment View

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)

Handling Payment Success and Failure

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>

Handling Payment Success and Failure

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')

Common Pitfalls

  • Exposing Secret Keys: Never expose your Stripe secret key on the client - side. It should only be used on the server - side to interact with the Stripe API.
  • Not Handling Errors Properly: Stripe API calls can fail for various reasons, such as network issues or invalid input. Make sure to handle errors gracefully in your code.
  • Ignoring 3D Secure Authentication: Some payments may require 3D Secure authentication. Ensure that your application handles these scenarios correctly to avoid payment failures.

Best Practices

  • Use Webhooks: Stripe webhooks allow you to receive real - time notifications about payment events, such as payment success or failure. Use webhooks to update your database and perform other actions based on the payment status.
  • Test Payments: Use Stripe’s test mode to test your payment integration thoroughly before going live. This will help you catch any issues or bugs early.
  • Keep Your Stripe Library Up - to - Date: Regularly update the stripe Python library to ensure that you have the latest security patches and features.

Conclusion

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.

References