How to add (backend) Stripe payment method in Django?

0 / 0 2 Mins Admin

December 18, 2022


In this tutorial, I’ll show you how to set up the Stripe payment method in Django. You can use the Stripe Python library to add a Stripe payment option to Django.

  1. First, you will need to install the Stripe Python library in your Django project. You can do this by running the following command:
pip install stripe
  1. Next, you will need to sign up for a Stripe account and obtain your Stripe API keys. You can find your API keys in the Stripe dashboard under the “Developers” tab.
  2. In your Django application, you will need to configure the Stripe Python library with your API keys. You can do this by adding the following code to your file:
STRIPE_SECRET_KEY = 'sk_test_your_stripe_secret_key'
STRIPE_PUBLISHABLE_KEY = 'pk_test_your_stripe_publishable_key'
  1. To accept payment using Stripe, you will need to create a form that includes a credit card input field and a submit button. You can use Stripe Elements to create a customizable credit card form that is compatible with Stripe’s payment processing.
  2. When the form is submitted, you can use the Stripe Python library to create a charge using the stripe.Charge.create() method. This method takes an array of parameters as an argument, including the amount you want to charge, the credit card details, and the currency.

Here is some sample code that demonstrates how to accept a payment using Stripe in Django:

import stripe

stripe.api_key = settings.STRIPE_SECRET_KEY

def charge(request):
    if request.method == 'POST':
        # Token is created using Checkout or Elements!
        # Get the payment token ID submitted by the form:
        token = request.POST['stripeToken']

        # Charge the user's card:
        charge = stripe.Charge.create(
            description='Example charge',

        return redirect('home')
    return render(request, 'charge.html', {'publishable_key': settings.STRIPE_PUBLISHABLE_KEY})

You can check your ‘Stripe Dashboard’ to see if the payment was successful. Check out the payments section to see all of the transactions on your portal.
We can now integrate the Stripe payment gateway into your Django website. You can change the HTML page to match your website!