Site icon StudyGyaan

Django Paypal Payment Gateway Integration with Working Example

Django Web Framework Tutorials

In the world of online payments, convenience and security are paramount. Integrating a payment gateway into your Django web application is crucial for businesses looking to accept online payments. In this blog post, we’ll guide you through the process of integrating PayPal, a widely used payment gateway, with your Django application.

Why Choose PayPal?

PayPal is a trusted and versatile payment gateway that offers several advantages:

  1. Security: PayPal is known for its robust security measures, including encryption, fraud detection, and buyer and seller protection.
  2. User Experience: PayPal offers a seamless checkout experience, allowing customers to make payments using their PayPal account or credit/debit cards.
  3. Global Reach: PayPal is available in over 200 countries and supports transactions in multiple currencies, making it suitable for international businesses.
  4. Developer-Friendly: PayPal provides comprehensive documentation, SDKs, and APIs for easy integration into web applications.

Step by Step Implementation

Now, let’s delve into the steps to integrate PayPal with your Django application.

Step 1: Create a PayPal Business Account

If you don’t already have one, sign up for a PayPal Business account at PayPal’s official website. This account will allow you to receive payments for your products or services.

Step 2: Install Required Packages

In your Django project, you’ll need to install the paypalrestsdk Python package to interact with the PayPal API. You can install it using pip:

pip install paypalrestsdk

Step 3: Configuration

Configure your Django settings to store your PayPal API credentials securely. Use environment variables to store sensitive information. Add your PayPal API credentials to your project’s settings:

# settings.py

PAYPAL_CLIENT_ID = 'your_paypal_client_id'
PAYPAL_SECRET = 'your_paypal_secret'

You can read this blog to get your paypal client id and secret key.

Step 4: Create Views for PayPal Create and Execution Payment

In your Django application, create views for handling payments, including creating a payment view, success view, and failure view. Design templates for your payment forms and success/failure pages.

This example covers creating a payment view, success view, and failure view.

To initiate a payment, create a PayPal payment object in your Django view. You’ll use the paypalrestsdk library for this purpose. Here’s a simplified example:

# views.py

import paypalrestsdk
from django.conf import settings
from django.shortcuts import render, redirect
from django.urls import reverse

paypalrestsdk.configure({
    "mode": "sandbox",  # Change to "live" for production
    "client_id": settings.PAYPAL_CLIENT_ID,
    "client_secret": settings.PAYPAL_SECRET,
})

def create_payment(request):
    payment = paypalrestsdk.Payment({
        "intent": "sale",
        "payer": {
            "payment_method": "paypal",
        },
        "redirect_urls": {
            "return_url": request.build_absolute_uri(reverse('execute_payment')),
            "cancel_url": request.build_absolute_uri(reverse('payment_failed')),
        },
        "transactions": [
            {
                "amount": {
                    "total": "10.00",  # Total amount in USD
                    "currency": "USD",
                },
                "description": "Payment for Product/Service",
            }
        ],
    })

    if payment.create():
        return redirect(payment.links[1].href)  # Redirect to PayPal for payment
    else:
        return render(request, 'payment_failed.html')

After the payment is made on PayPal’s site, the user will be redirected to your return_url. You need to create a view that handles the execution of the payment.

# views.py

def execute_payment(request):
    payment_id = request.GET.get('paymentId')
    payer_id = request.GET.get('PayerID')

    payment = paypalrestsdk.Payment.find(payment_id)

    if payment.execute({"payer_id": payer_id}):
        return render(request, 'payment_success.html')
    else:
        return render(request, 'payment_failed.html')

def payment_checkout(request):
    return render(request, 'checkout.html')

Step 5: Create Templates and URL’s

Let’s create the templates for the success and failure pages:

templates/payment_success.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Payment Successful</title>
</head>
<body>
    <h1>Payment Successful</h1>
    <p>Thank you for your purchase!</p>
</body>
</html>

templates/payment_failed.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Payment Failed</title>
</head>
<body>
    <h1>Payment Failed</h1>
    <p>Your payment was not completed. Please try again.</p>
</body>
</html>

To initiate a payment, you can create a button in one of your HTML templates and link it to the create_payment view:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Checkout</title>
</head>
<body>
    <h1>Checkout Page</h1>
    
    <form action="{% url 'create_payment' %}" method="POST">
        {% csrf_token %}
        <button type="submit">Pay with PayPal</button>
    </form>
</body>
</html>

In your project’s urls.py, add URL patterns for your views:

# urls.py 

from django.urls import path
from . import views

urlpatterns = [
    path('checkout/', views.payment_checkout, name='checkout_payment'),
    path('create_payment/', views.create_payment, name='create_payment'),
    path('execute_payment/', views.execute_payment, name='execute_payment'),
]

With these views, templates, and URL patterns in place, you can create a “Pay with PayPal” button on your checkout.html page that, when clicked, will initiate the PayPal checkout process. After successful payment or cancellation, users will be redirected to the respective success or failure pages.

Step 7: Test Your Integration

Before going live, thoroughly test your PayPal integration in the sandbox environment provided by PayPal. You can use PayPal’s test accounts for this purpose.  Go to http://localhost:8000/checkout, if you cancel payment http://localhost:8000/cancel and on successfuel payment http://localhost:8000/success

Step 8: Go Live

Once you’ve tested your integration and are satisfied with the results, switch your PayPal account to live mode, update your API credentials in your Django settings, and start accepting real payments.

Conclusion

Integrating PayPal payment gateway with Django can simplify the process of accepting online payments on your website. With PayPal’s reputation for security and global reach, it’s a great choice for businesses of all sizes. By following the steps outlined in this guide, you can enhance your website’s functionality and offer a seamless payment experience to your customers. So, get started with PayPal and Django today, and watch your online business thrive!

Find this project on Github.

Read our blog on How to Protect Sensitive Data in Python Projects like Django and Flask

As you are using sensitive data in your project, like api keys and secrets. You need protect it.
Blogs You Might to Read!
Exit mobile version