How to Add Payment Subscriptions With Stripe in Django


Integrating Stripe subscriptions into your Django site involves several steps. Here’s a high-level overview of the process. Please note that the exact implementation can vary based on your specific requirements.

Steps involved

Sign Up and Set Up Stripe Account

If you haven’t already, sign up for a Stripe account at https://stripe.com . Once you’ve signed up, you’ll need your API keys: a Publishable Key (for the client-side) and a Secret Key (for server-side interactions).

Install the Stripe Python Library

Install the stripe Python library using pip:

pip install stripe

Create Subscription Plans on Stripe Dashboard

Log in to your Stripe dashboard and create subscription plans (monthly, yearly, etc.) that users can subscribe to. Note down the Plan IDs.

Configure Stripe Keys

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

STRIPE_PUBLISHABLE_KEY = 'your-publishable-key'
STRIPE_SECRET_KEY = 'your-secret-key'

Create Views and Templates

Create views and templates for the subscription flow, including pages for selecting a subscription plan, handling payment details, and displaying subscription status.

Create a Subscription Management Model

Create a Django model to manage user subscriptions. This might include fields like user, subscription_id, plan_id, status, start_date, end_date, etc.

Create Subscription Views

Implement views for the subscription flow:

  • Display available subscription plans and let users choose.
  • Collect payment details (using Stripe Elements or Checkout).
  • Handle the subscription creation process using the Stripe API.

Handle Webhooks

Stripe sends events to your server (webhooks) for important subscription-related events. Implement webhook handlers to handle events like subscription cancellation, renewal, payment failures, etc.

Protect Views with User Authentication

Make sure to protect subscription-related views using Django’s authentication system to ensure only logged-in users can access them.

Testing

Test your subscription flow thoroughly in both development and testing environments. You can use Stripe’s test mode to avoid real charges during testing.

Security

Ensure you’re following security best practices, especially when handling sensitive data like payment information.

Documentation

Provide clear documentation for users on how to subscribe, manage their subscriptions, and what to do in case of issues.

The above steps provide a general guideline for integrating Stripe subscriptions into your Django site. It’s important to consult the official Stripe documentation as well, as it provides detailed information on the API endpoints, authentication, webhooks, and best practices.

Stripe API Reference: https://stripe.com/docs/api Stripe Python Library Documentation: https://stripe.com/docs/api/python

Show me some Python code

Below is an example of how you might implement a basic subscription flow using Stripe in a Django project. This example focuses on the backend code and assumes you’ve set up the necessary templates, views, and models on your own.

Make sure to install the stripe library using pip install stripe and configure your Stripe API keys in your Django settings before proceeding.

# views.py
import stripe
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.shortcuts import render, redirect
from django.urls import reverse
from .models import Subscription

stripe.api_key = settings.STRIPE_SECRET_KEY

@login_required
def subscription_plans(request):
    # Fetch available subscription plans from Stripe
    plans = stripe.Plan.list()
    return render(request, 'subscriptions/subscription_plans.html', {'plans': plans})

@login_required
def create_subscription(request, plan_id):
    user = request.user
    plan = stripe.Plan.retrieve(plan_id)

    # Create a subscription on Stripe
    subscription = stripe.Subscription.create(
        customer=user.stripe_customer_id,  # Assuming you store customer IDs
        items=[{'plan': plan.id}],
        payment_behavior='default_incomplete',  # Change based on your requirements
        expand=['latest_invoice.payment_intent']
    )

    # Save subscription details to your database
    Subscription.objects.create(
        user=user,
        subscription_id=subscription.id,
        plan_id=plan.id,
        status=subscription.status,
        current_period_start=subscription.current_period_start,
        current_period_end=subscription.current_period_end
    )

    return redirect(reverse('subscription_success'))

# webhook_handlers.py
from django.http import HttpResponse
import json
import stripe
from django.conf import settings

stripe.api_key = settings.STRIPE_SECRET_KEY

def handle_subscription_webhook(request):
    payload = request.body
    event = None

    try:
        event = stripe.Event.construct_from(
            json.loads(payload), stripe.api_key
        )
    except ValueError as e:
        # Invalid payload
        return HttpResponse(status=400)

    # Handle specific events
    if event.type == 'invoice.payment_failed':
        # Handle payment failure
        # Update user's subscription status or take necessary actions

    return HttpResponse(status=200)

Please note that this is a simplified example. In a real-world scenario, you’d need to handle error cases, add proper user authentication, implement webhook security, handle payment confirmation, and integrate this with your templates and frontend components.

Make sure to consult Stripe’s official documentation for comprehensive information on their API, security practices, and webhook handling: https://stripe.com/docs/api

Some other considerations

Here are some advanced considerations and tips when implementing Stripe subscriptions in your Django project:

Authentication and User Experience

  • Utilize Django’s authentication system to manage user accounts and sessions.
  • Provide clear instructions and a user-friendly interface for managing subscriptions.
  • Implement password-protected account access and two-factor authentication (2FA) for added security.

Webhooks and Event Handling

  • Set up webhook endpoints to receive and handle Stripe events. Secure your webhook endpoint by verifying the Stripe signature.
  • Implement retry and error handling for webhook events to ensure data consistency.

Subscription Management

  • Allow users to upgrade, downgrade, or cancel their subscriptions from your website.
  • Implement logic to handle prorated charges when changing subscription plans.

Payment Methods and Payment Intent

  • Implement a payment method management system that allows users to add, remove, or update payment methods.
  • Use Payment Intents when dealing with subscription payments to handle potential authentication requirements.

Invoice Management

  • Keep track of invoices and invoice items in your database for better record-keeping.
  • Allow users to view and download their invoices from your website.

Grace Periods and Dunning Management

  • Implement grace periods for subscription renewals to allow users some time to update their payment information.
  • Set up strategies for handling dunning management (failed payment recovery).

Localized Pricing and Currencies

  • If your service caters to international customers, consider providing localized pricing and accepting multiple currencies.

Testing and Staging Environments

  • Use Stripe’s testing mode and test cards for thorough testing of your subscription flow in a staging environment.
  • Test various scenarios, such as trial periods, upgrades, downgrades, and cancellations.

Documentation and Support

  • Provide detailed documentation for users regarding subscription management, billing, and common issues.
  • Offer customer support channels to assist users with subscription-related queries.

Logging and Monitoring

  • Implement logging to track important actions, errors, and events related to subscriptions.
  • Use monitoring tools to track the health of your subscription system and detect anomalies.
  • Ensure your subscription setup adheres to relevant legal and compliance requirements, such as GDPR.

Scalability

  • Design your subscription system to handle increased traffic and growing user bases.
  • Monitor performance and scalability as your user base grows.

Security

  • Implement security best practices, such as input validation, data sanitization, and avoiding direct access to sensitive endpoints.
  • Protect sensitive user data using encryption and follow best practices for data security.