Integrating a Payment System in Django (2024)

In this tutorial, we will learn how to integrate a payment system in Django. We will be using Stripe as our payment gateway, but the process is similar for other payment gateways such as PayPal and Braintree. Integrating a payment system is essential for any e-commerce platform, and Django makes it relatively easy to do so with the help of third-party packages and a bit of customization. Let's get started!

Prerequisites

  • Basic knowledge of Django and Python
  • Django project set up and running
  • Stripe account and API keys

Step 1: Install Required Packages

To integrate Stripe with our Django project, we need to install the following packages:

pip install stripepip install django-stripe-payments

The first package is the official Stripe Python library, and the second package, django-stripe-payments, is a Django package that simplifies the integration process.

Step 2: Configure Django Settings

Next, we need to add the Stripe API keys and configure the django-stripe-payments package in our Django settings.py file:

# settings.py# Stripe API keysSTRIPE_PUBLIC_KEY = 'your_stripe_public_key'STRIPE_PRIVATE_KEY = 'your_stripe_private_key'# django-stripe-payments configurationINSTALLED_APPS = [ # ... 'djstripe', # ...]DJSTRIPE_WEBHOOK_SECRET = 'your_stripe_webhook_secret'DJSTRIPE_USE_NATIVE_JSONFIELD = True

Replace 'your_stripe_public_key', 'your_stripe_private_key', and 'your_stripe_webhook_secret' with the corresponding values from your Stripe dashboard.

Step 3: Create a Payment Model

We need a model to store the payment information. Let's create a Payment model in our app's models.py file:

# models.pyfrom django.db import modelsfrom djstripe.models import StripeModelclass Payment(StripeModel): amount = models.DecimalField(max_digits=10, decimal_places=2) description = models.CharField(max_length=100) paid = models.BooleanField(default=False) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return f'{self.user.username} - {self.description}'

Here, we inherit from StripeModel, which is provided by django-stripe-payments and contains useful fields and methods for working with Stripe objects.

Step 4: Create a Payment Form

Now, let's create a form to collect the necessary payment information from the user. Create a new file called forms.py in your app directory and add the following code:

# forms.pyfrom django import formsfrom .models import Paymentclass PaymentForm(forms.ModelForm): class Meta: model = Payment fields = ('amount', 'description',) widgets = { 'amount': forms.NumberInput(attrs={'class': 'form-control'}), 'description': forms.TextInput(attrs={'class': 'form-control'}), }

Step 5: Create Payment Views

Next, let's create the views to handle the payment process. We will need two views: one to display the payment form and another to process the payment. Add the following code to your views.py file:

# views.pyfrom django.shortcuts import render, redirectfrom django.contrib import messagesfrom .forms import PaymentFormfrom .models import Paymentimport stripedef payment(request): form = PaymentForm(request.POST or None) if request.method == "POST": if form.is_valid(): payment = form.save(commit=False) payment.user = request.user payment.save() # Create a Stripe PaymentIntent stripe.api_key = settings.STRIPE_PRIVATE_KEY intent = stripe.PaymentIntent.create( amount=int(payment.amount * 100), currency='usd', metadata={'payment_id': payment.id} ) # Redirect to the payment processing view return redirect('process_payment', intent.client_secret) context = {'form': form} return render(request, 'payment.html', context)def process_payment(request, client_secret): if request.method == "POST": stripe.api_key = settings.STRIPE_PRIVATE_KEY intent = stripe.PaymentIntent.confirm(client_secret) if intent.status == 'succeeded': # Update the Payment model payment_id = intent.metadata['payment_id'] payment = Payment.objects.get(id=payment_id) payment.paid = True payment.save() messages.success(request, 'Payment successful!') return redirect('success') context = {'client_secret': client_secret} return render(request, 'process_payment.html', context)

In the payment view, we create a new Payment object and a Stripe PaymentIntent. We then redirect the user to the process_payment view, where the actual payment processing takes place using the Stripe JavaScript library.

Step 6: Create Payment Templates

Create two new templates, payment.html and process_payment.html, and add the following code:

<!-- payment.html -->{% extends 'base.html' %}{% block content %} <h2>Make a Payment</h2> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="btn btn-primary">Pay</button> </form>{% endblock %}<!-- process_payment.html -->{% extends 'base.html' %}{% block content %}<h2>Processing Payment...</h2><p>Please wait while we process your payment.</p> {% load static %} <script src="https://js.stripe.com/v3/"></script> <script src="{% static 'js/payment.js' %}"></script> <script> processPayment('{{ client_secret }}'); </script>{% endblock %}

The process_payment template includes the Stripe JavaScript library and a custom JavaScript file called payment.js, which we will create in the next step.

Step 7: Add Payment JavaScript

Create a new file called payment.js in your app's static/js directory and add the following code:

// payment.jsasync function processPayment(clientSecret) { const stripe = Stripe('your_stripe_public_key'); const result = await stripe.confirmCardPayment(clientSecret, { payment_method: { card: await stripe.createToken('card', { number: '4242424242424242', exp_month: '12', exp_year: '2030', cvc: '123', }), }, }); if (result.error) { // Error handling console.error(result.error.message); } else { // Payment succeeded window.location.href = '/success/'; }}

Replace 'your_stripe_public_key' with your actual Stripe public key. This script processes the payment using the Stripe API and redirects the user to a success page if the payment is successful.

Step 8: Update URLs

Finally, add the new views to your app's urls.py file:

# urls.pyfrom django.urls import pathfrom . import viewsurlpatterns = [ # ... path('payment/', views.payment, name='payment'), path('process_payment/<str:client_secret>/', views.process_payment, name='process_payment'), # ...]

Conclusion

In this tutorial, we learned how to integrate a payment system in Django using Stripe. Integrating a payment system is crucial for e-commerce platforms, and Django makes it relatively easy with the help of third-party packages and customization. You can also hire remote Python developers to help with the integration process and customize it according to your needs.

Integrating a Payment System in Django (2024)

FAQs

Integrating a Payment System in Django? ›

Step 1: Initiate the Django project

Make sure you are done with the django installation. Create a new project called dj_razorpay and then start a new app called payment. Add “payment” to the list of installed_apps in the settings.py file. Also, apply the migrations.

How to integrate payment methods in Django? ›

Step 1: Initiate the Django project

Make sure you are done with the django installation. Create a new project called dj_razorpay and then start a new app called payment. Add “payment” to the list of installed_apps in the settings.py file. Also, apply the migrations.

How do I integrate payment system into my website? ›

How to integrate a payment gateway into a website
  1. Step one: choose a payment gateway provider. The first step is to choose a payment gateway provider. ...
  2. Step two: set up your account. ...
  3. Step three: integrate payment gateway in website. ...
  4. Step four: test your checkout process.
Feb 12, 2024

How to integrate a payment gateway in Python? ›

To integrate Razorpay Payment Gateway on your Python website:
  1. 1.1. Install Razorpay Python SDK. .
  2. 1.2. Create an Order in Server. .
  3. 1.3. Add Checkout Options. .
  4. 1.4. Store Fields in Server. .
  5. 1.5. Verify Payment Signature. .
  6. 1.6. Verify Payment Status. .

How do I create a payment integration? ›

How to create a payment gateway
  1. Create your payment gateway infrastructure. You'll need a server to host your gateway, whether it's your own or via a third party. ...
  2. Choose a payment processor. ...
  3. Create a customer relationship management (CRM) system. ...
  4. Implement security features. ...
  5. Obtain required certifications.

How to build a payment system in Python? ›

How can you build a Python API to integrate with payment systems?
  1. Choose a payment system. ...
  2. Install and import dependencies. ...
  3. Set up authentication and configuration. ...
  4. Define the endpoints and methods. ...
  5. Implement the logic and calls. ...
  6. Test and deploy your payment API. ...
  7. Here's what else to consider.
Sep 29, 2023

How do I integrate PayPal API into my website? ›

Here are the steps involved with API Integration: Verify your API settings. My Account > Profile > My Selling Tools > My business > API access > Update. Choose to host buttons on PayPal or encrypt and host with your API.

What is an API payment gateway? ›

Application programming interface (API) is the technology that merges your online processes. A payment gateway API helps connect the checkout system to a payment acquiring network. The distance between placing an order and making the payment must be simple, fast, and transparent for a user.

Which is the best payment gateway? ›

Best Online Payment Gateways in India 2024
  • PayU.
  • Instamojo.
  • CCAvenue.
  • Bill Desk.
  • JusPay.
  • Airpay.
  • Cashfree Payments.
  • Zaakpay.

How to build an API gateway in Django? ›

Prerequisites
  1. Step 1: Set Up Django CORS Headers: To allow cross-origin requests from the API Gateway, install the django-cors-headers package and configure it in your Django project. ...
  2. Step 2: Create an API Gateway: ...
  3. Step 3: Create Resources and Methods: ...
  4. Step 4: Deploy the API: ...
  5. Step 5: Test the Integration:
Mar 23, 2024

What is needed to integrate payment gateway? ›

For integrated payment gateways, you'll need to use a development team to connect your website. Most gateways will be able to link you with their own partner developers or link to an API. When choosing integrated gateways, be sure that it accepts a variety of different payment types including mobile users.

How do I create a payment gateway API? ›

Several steps are involved in developing a custom payment gateway:
  1. Registration of payment gateway providers.
  2. Setting up infrastructure.
  3. Register with a credit card company (or several) through your acquiring bank as a payment gateway provider.
Apr 6, 2024

How to integrate PayPal payment gateway in Python Django? ›

Please follow the below steps via your PayPal Business account to explore other integrations. Login to PayPal.com >> click on "settings icon" >> go to "Account settings" >> Website payments >> PayPal buttons >> select button type >> fill in the required details.

What is Stripe payment integration? ›

Low-code integrations

Checkout: Lets you add an embeddable payment form to your site or redirect users to a Stripe-hosted checkout page. You can configure Checkout programmatically through the API or configure it in the Dashboard. Stripe selects enabled payment methods from your Dashboard by default.

How do you integrate payment method in app? ›

Manual Coding - Developers can add the gateway's API manually, with custom code they've written themselves. SDKs - Software Development Kits (SDKs) are sets of pre-written code libraries and tools that developers can use to add payment gateways to mobile apps with minimal manual coding required.

How do you integrate a dummy payment gateway? ›

To configure a website to use the Dummy gateway, set the Payment Gateway Setting to Dummy.
  1. Go to Admin Console > Administration > System > Settings.
  2. In the search box, enter Payment Gateway and select it from the list.
  3. Select Dummy from the menu.
  4. Click Save.

Top Articles
Latest Posts
Article information

Author: Terence Hammes MD

Last Updated:

Views: 6458

Rating: 4.9 / 5 (49 voted)

Reviews: 88% of readers found this page helpful

Author information

Name: Terence Hammes MD

Birthday: 1992-04-11

Address: Suite 408 9446 Mercy Mews, West Roxie, CT 04904

Phone: +50312511349175

Job: Product Consulting Liaison

Hobby: Jogging, Motor sports, Nordic skating, Jigsaw puzzles, Bird watching, Nordic skating, Sculpting

Introduction: My name is Terence Hammes MD, I am a inexpensive, energetic, jolly, faithful, cheerful, proud, rich person who loves writing and wants to share my knowledge and understanding with you.