Introduction To Online Payments in Django

  • By Deepali Shinkar
  • October 31, 2024
  • Django
Introduction To Online Payments in Django 

Introduction To Online Payments in Django 

Django is a popular web framework that’s well-suited for building e-commerce sites and applications requiring online payments. Thanks to Django’s flexible architecture and a vast selection of libraries, integrating payment gateways is relatively straightforward. Introduction to online payments in Django! This introduction covers integration, tools, and best practices for implementing secure payment systems in your projects. By adding online payment capabilities, you can enable users to complete transactions directly on your platform. 

 

Steps to Integrate Online Payments in Django 

1. Setting Up Your Django Project 

Start by creating a new Django project and application where you will handle the payment processes. Create a new project in a virtual environment. 

Step 1: Install virtualenv 

If you don’t have virtualenv installed, you can install it using pip: pip install virtualenv 

Step 2: Create a Virtual Environment 

Navigate to your Django project directory, or create a new directory for your  project: 

mkdir my_django_project  

cd my_django_project 

Then create a virtual environment. You can name it venv, env, or anything you like. 

# Using virtualenv virtualenv venv 

# OR using Python 3’s built-in venv 

python3 -m venv venv

 

Step 3: Activate the Virtual Environment 

To start using the virtual environment, you need to activate it. venv\Scripts\activate.bat 

After creating a virtual environment, we create a project using the command and  directory path of the project : 

django-admin startproject mypaymentapp 

cd mypaymentapp 

Then create a new application : 

 python manage.py startapp payments 

Install required dependencies: 

pip install django stripe

 

2. Choosing a Payment Gateway 

Popular payment gateways include: 

  • Stripe: Great for developers, and offers simple API integration.
    PayPal: Ideal for sites where users might already have PayPal accounts.
    Braintree: A good choice for recurring payments and high transaction volume. 

For this guide, we’ll focus on Stripe, as it’s developer-friendly and supports a variety of payment methods. 

 

3. Configuring Payment Settings 

After choosing your gateway, get API keys from the payment provider’s dashboard. Store these keys securely in Django’s settings file. 

# mypaymentapp/settings.py 

STRIPE_SECRET_KEY = “your_secret_key” 

STRIPE_PUBLISHABLE_KEY = “your_publishable_key” 

 

4. Creating Payment Models 

To record transactions, create a Payment model that captures essential information. 

# payments/models.py 

from django.db import models 

from django.conf import settings 

class Payment(models.Model): 

user=models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) amount = models.DecimalField(max_digits=10, decimal_places=2) 

timestamp = models.DateTimeField(auto_now_add=True) 

success = models.BooleanField(default=False) 

stripe_charge_id = models.CharField(max_length=100) 

def __str__(self): 

return f”Payment {self.id} by {self.user}” 

Run the migration commands to create this model in your database. 

python manage.py makemigrations 

python manage.py migrate

 

5. Creating Payment Views and Forms 

In your view, set up a function to handle the payment process. 

# payments/views.py 

from django.conf import settings 

from django.shortcuts import render, redirect 

from django.views.decorators.csrf import csrf_exempt 

import stripe 

from .models import Payment 

stripe.api_key = settings.STRIPE_SECRET_KEY 

def initiate_payment(request): 

 if request.method == “POST”: 

 amount = 5000 # $50.00 

 payment_intent = stripe.PaymentIntent.create( 

 amount=amount, 

 currency=”usd”, 

 payment_method_types=[“card”] 

 ) 

  

 return render(request, “payments/checkout.html”, {  “client_secret”: payment_intent.client_secret, 

 “amount”: amount, 

 }) 

 return render(request, “payments/initiate_payment.html”)

 

For Free, Demo classes Call:  020-71177359

Registration Link: Click Here!

 

6. Creating Payment Templates 

Create templates to handle the payment form and feedback to the user. 

  1. initiate_payment.html: A page with a button to start the payment. 2. checkout.html: The page with Stripe’s Checkout form. 

checkout.html 

<!– templates/payments/checkout.html –> 

<html> 

 <head> 

 <title>Checkout</title> 

 <script src=”https://js.stripe.com/v3/”></script> 

 </head> 

 <body> 

 <h1>Complete your payment of $50.00</h1> 

 <form id=”payment-form”> 

 <div id=”card-element”></div> 

 <button type=”submit”>Pay</button> 

 </form> 

 <script type=”text/javascript”> 

 var stripe = Stripe(“{{ stripe_publishable_key }}”); 

 var elements = stripe.elements(); 

 var card = elements.create(“card”); 

 card.mount(“#card-element”); 

 document.querySelector(“form”).addEventListener(“submit”, function (e) {  e.preventDefault(); 

 stripe.confirmCardPayment(“{{ client_secret }}”, { 

 payment_method: { 

 card: card, 

 billing_details: { 

 name: “{{ user.username }}” 

 } 

 } 

 }).then(function(result) { 

 if (result.error) { 

 // Display error to the customer 

 console.error(result.error.message); 

 } else { 

 // Payment succeeded, redirect or show success 

 window.location.href = “/payment-success/”; 

 } 

 }); 

 }); 

 </script> 

 </body> 

</html>

 

7. Handling Payment Success and Failures 

In your view, add functions to handle redirection after successful or failed payments. 

# payments/views.py 

def payment_success(request): 

return render(request, “payments/success.html”) 

def payment_failure(request): 

return render(request, “payments/failure.html”) 

Add routes in your urls.py to point to these views. 

# payments/urls.py 

from django.urls import path 

from . import views 

urlpatterns = [ 

 path(“initiate/”, views.initiate_payment, name=”initiate_payment”),  path(“success/”, views.payment_success, name=”payment_success”),  path(“failure/”, views.payment_failure, name=”payment_failure”), ]

 

8. Testing the Integration 

To test the integration: 

  • Use Stripe’s test API keys in settings.py. 
  • Add a sample test card (e.g., 4242 4242 4242 4242) in the Stripe Checkout form. 
  • Verify successful transactions in the Stripe Dashboard. 

 

9. Securing Your Payment Integration 

Follow these security practices: 

  • Ensure all sensitive keys are stored securely (consider using environment variables). 
  • Use HTTPS in production. 
  • Regularly update dependencies and review your application’s security settings. 

 

Wrapping Up 

Integrating payments in Django with Stripe enables you to handle transactions smoothly within your application. By following these steps, you can set up a secure, user-friendly payment flow and customize it as needed for specific business requirements.

 

Do visit our channel: Click Here

 

Author:-
Deepali Shinkar
Call the Trainer and Book your free demo Class For Django

Call now!!! | SevenMentor Pvt Ltd.

© Copyright 2021 | SevenMentor Pvt Ltd.

Submit Comment

Your email address will not be published. Required fields are marked *

*
*