You need to agree to share your contact information to access this model

This repository is publicly accessible, but you have to accept the conditions to access its files and content.

Log in or Sign Up to review the conditions and access this model content.

E-commerce Ordering & Payment System

A production-style Django REST Framework backend developed for a Backend Engineer assessment.

This project demonstrates backend engineering practices including:

  • Clean architecture
  • REST API design
  • JWT authentication
  • Database modeling
  • Inventory management
  • Order processing
  • Payment gateway integration
  • Design patterns
  • Redis caching
  • Automated testing
  • API documentation
  • Docker deployment

Overview

The system is an e-commerce backend where users can:

  • Register and authenticate using JWT
  • Browse categories and products
  • Create orders
  • Reserve inventory during checkout
  • Make payments through Stripe or bKash
  • Track order and payment status

The project is designed with scalability and maintainability in mind by separating responsibilities:

API Layer
    |
Serializer Layer
    |
Service Layer
    |
Business Logic
    |
Database / External Providers

Architecture Overview

                    Client

                      |

              Django REST API

                      |

        ----------------------------

        |                          |

  Serializer Layer          Service Layer

        |                          |

        -------- Business Logic ----

                      |

              Database Layer

                      |

        PostgreSQL + Redis

                      |

        External Payment Providers

              Stripe / bKash

Technology Stack

Backend

  • Python 3.12+
  • Django 6.x
  • Django REST Framework
  • PostgreSQL 16
  • Redis 7
  • SimpleJWT
  • Stripe SDK
  • bKash Tokenized Checkout API
  • drf-spectacular
  • Docker
  • Gunicorn

Supported Development Environment

Tested on:

  • Arch Linux
  • Ubuntu Linux

Features

Authentication

Implemented:

  • Custom User model
  • JWT authentication
  • Registration
  • Login
  • Token refresh
  • Profile management
  • Permission control

Endpoints:

POST   /api/auth/register/
POST   /api/auth/login/
POST   /api/auth/token/refresh/
GET    /api/auth/profile/
PATCH  /api/auth/profile/

Category Management

The category system supports hierarchical product organization.

Example:

Electronics

β”œβ”€β”€ Laptop

β”‚   β”œβ”€β”€ Gaming Laptop
β”‚   └── Business Laptop

└── Mobile

Implemented:

  • Self-referencing category model
  • Parent-child relationships
  • Recursive tree generation
  • DFS traversal
  • Redis caching

Endpoint:

GET /api/categories/tree/

Product Management

Implemented:

  • Product CRUD
  • Category relationship
  • Filtering
  • Search
  • Pagination
  • Ordering
  • Permission-based access

Product model:

Product

id
category
name
sku
description
price
stock
status
created_at
updated_at

Database protections:

  • Price validation
  • Foreign key integrity
  • Indexed lookup fields

Order Management

The order system handles:

  • Order creation
  • Order item creation
  • Stock validation
  • Inventory locking
  • Transaction safety
  • Order lifecycle management

Order statuses:

PENDING
PAID
PROCESSING
SHIPPED
COMPLETED
CANCELLED

Order processing flow:

Customer

   |

Create Order

   |

Validate Stock

   |

Lock Inventory

(select_for_update)

   |

Create Order Items

   |

Calculate Total

   |

Create Payment

   |

Payment Confirmation

   |

Order Status = PAID

Critical operations use:

transaction.atomic()

select_for_update()

to prevent inventory race conditions.


Database Design

The system uses PostgreSQL with relational database modeling.

Entity Relationship Overview

User

 |

 |

Order

 |

 |

OrderItem

 |

 |

Product

 |

 |

Category



Order

 |

 |

Payment

Category Model

Category

id
name
slug
parent_id
created_at
updated_at

Supports:

  • Nested categories
  • Recursive traversal
  • Cached category trees

Product Model

Product

id
category_id
name
sku
price
stock
status
created_at
updated_at

Database protections:

  • Non-negative price constraint
  • Foreign key relationships
  • Query optimization indexes

Order Model

Order

id
user_id
total_amount
status
created_at
updated_at

Payment Model

Payment

id
order_id
provider
status
amount
transaction_id
provider_payment_id
created_at
updated_at

Reliability features:

  • Amount constraints
  • Unique transaction identifiers
  • Payment status protection
  • Webhook tracking

Payment Architecture

The payment system uses:

  • Strategy Pattern
  • Factory Pattern
  • Service Layer Pattern

Architecture:

                 PaymentService

                       |

          PaymentStrategyFactory

                       |

        ----------------------------

        |                          |

StripePaymentStrategy     BkashPaymentStrategy

        |                          |

   Stripe SDK              bKash Client

        |                          |

 Stripe API              bKash API

The order system does not directly depend on payment providers.


Stripe Integration

Implemented:

  • PaymentIntent creation
  • Client secret generation
  • Payment tracking
  • Webhook verification
  • Idempotent event processing
  • Automatic order updates

Webhook endpoint:

POST /api/payments/webhooks/stripe/

Flow:

Customer

↓

Create Payment

↓

Stripe PaymentIntent

↓

Stripe Webhook

↓

Signature Verification

↓

Webhook Processing

↓

Payment Update

↓

Order Status Update

bKash Integration

Implemented:

  • Token generation
  • Create checkout payment
  • Execute payment
  • Payment verification
  • Callback handling

Callback:

POST /api/payments/bkash/callback/

Flow:

Customer

↓

bKash Checkout

↓

Callback API

↓

PaymentService

↓

BkashPaymentStrategy

↓

Execute Payment

↓

Payment SUCCESS

↓

Order PAID

Payment Reliability

Payment processing handles asynchronous gateway communication.

Webhook Idempotency

Every webhook event is stored:

WebhookEvent

provider
event_id
event_type
processed
payload

Duplicate events are prevented using:

event_id UNIQUE constraint

This prevents:

  • Duplicate payment updates
  • Multiple order status transitions
  • Repeated side effects

Payment State Protection

Invalid state transitions are prevented.

Example:

SUCCESS -> FAILED

is not allowed.

This protects against delayed or out-of-order webhook delivery.


Redis Usage

Redis is used for category tree caching.

Flow:

Request Category Tree

        |

Check Redis Cache

        |

    Cache Exists?

       /     \

     Yes      No

      |        |

Return     Generate Tree

             |

          Save Cache

Design Patterns Used

Service Layer Pattern

Business logic is separated from views.

Example:

APIView

   |

OrderService

   |

Models

Used in:

  • OrderService
  • PaymentService
  • CategoryService

Strategy Pattern

Payment providers implement a common interface:

PaymentStrategy

        |

-----------------

|               |

Stripe        bKash

Adding a new payment provider does not require changing order logic.


Factory Pattern

Provider selection is handled by:

PaymentStrategyFactory

The application depends on abstractions instead of concrete payment implementations.


Project Structure

ecommerce_backend/

β”œβ”€β”€ accounts/
β”œβ”€β”€ categories/
β”œβ”€β”€ products/
β”œβ”€β”€ orders/
β”œβ”€β”€ payments/
β”‚
β”‚   └── strategies/
β”‚       β”œβ”€β”€ base.py
β”‚       β”œβ”€β”€ factory.py
β”‚       β”œβ”€β”€ stripe.py
β”‚       └── bkash.py
β”‚
β”œβ”€β”€ common/
β”‚
β”œβ”€β”€ ecommerce_backend/
β”‚   β”œβ”€β”€ settings.py
β”‚   β”œβ”€β”€ urls.py
β”‚   └── wsgi.py
β”‚
β”œβ”€β”€ Dockerfile
β”œβ”€β”€ docker-compose.yml
β”œβ”€β”€ entrypoint.sh
β”œβ”€β”€ requirements.txt
β”œβ”€β”€ schema.yml
β”œβ”€β”€ manage.py
└── README.md

Installation

Clone repository:

git clone <repository-url>

cd ecommerce_backend

Create environment:

python -m venv .venv

source .venv/bin/activate

Install dependencies:

pip install --upgrade pip

pip install -r requirements.txt

Environment Variables

Create:

cp .env.example .env

Example:

SECRET_KEY=your_secret_key
DEBUG=True

DB_NAME=ecommerce_backend
DB_USER=ecommerce_user
DB_PASSWORD=password
DB_HOST=localhost
DB_PORT=5432

REDIS_HOST=localhost
REDIS_PORT=6379

STRIPE_SECRET_KEY=
STRIPE_WEBHOOK_SECRET=

BKASH_BASE_URL=
BKASH_APP_KEY=
BKASH_APP_SECRET=
BKASH_USERNAME=
BKASH_PASSWORD=
BKASH_CALLBACK_URL=

Never commit .env.


Database Setup

Run migrations:

python manage.py migrate

Create admin user:

python manage.py createsuperuser

Running Locally

Start Redis:

redis-cli ping

Expected:

PONG

Run server:

python manage.py runserver

Docker Deployment

Build and run:

docker compose up -d --build

Services:

backend

postgres

redis

Architecture:

              Nginx

                |

             Gunicorn

                |

        Django Application

          /           \

 PostgreSQL        Redis

Deployment Guide

Environment Configuration

  1. Copy the example environment file:
cp .env.example .env
  1. Configure the required variables:
  • Django SECRET_KEY
  • PostgreSQL credentials
  • Redis connection
  • Stripe API keys
  • bKash credentials
  1. Run database migrations:
python manage.py migrate

Frontend Deployment (Optional)

This project is a backend-focused assessment and does not include a frontend.

If a frontend is developed (e.g. React or Next.js), it can be deployed to Vercel and configured to consume this REST API.

Example architecture:

Vercel (Frontend)
        β”‚
        β–Ό
Django REST API
        β”‚
 β”œβ”€β”€ PostgreSQL
 └── Redis

Backend Access via ngrok

For local testing or payment webhook integration, expose the local Django server using ngrok.

Start the development server:

python manage.py runserver

Expose it:

ngrok http 8000

Example public URL:

https://xxxxx.ngrok-free.app

This URL can be used for testing external integrations such as Stripe webhooks and bKash callbacks.


Docker Deployment

Build and start all services:

docker compose up --build

The Docker Compose setup starts:

  • Django backend
  • PostgreSQL database
  • Redis cache

API Documentation

Generated using:

drf-spectacular

Swagger:

http://127.0.0.1:8000/api/docs/

Schema:

http://127.0.0.1:8000/api/schema/

Redoc:

http://127.0.0.1:8000/api/redoc/

API Summary

Module Endpoint
Authentication /api/auth/
Categories /api/categories/
Products /api/products/
Orders /api/orders/
Payments /api/payments/
Health /api/health/

Health Check

Endpoint:

GET /api/health/

Checks:

  • Django application
  • PostgreSQL
  • Redis

Response:

{
    "status": "ok",
    "database": "ok",
    "redis": "ok"
}

Testing

Run:

python manage.py test

Current:

42 tests passing

Coverage:

Authentication:

  • Registration
  • Login
  • JWT authentication
  • Permissions

Products:

  • CRUD
  • Validation
  • Filtering

Orders:

  • Order creation
  • Stock validation
  • User isolation

Payments:

  • Stripe webhook verification
  • Payment processing
  • bKash callback handling

Health:

  • Database connectivity
  • Redis connectivity

Security Features

Implemented:

  • JWT authentication
  • Password hashing
  • Environment-based secrets
  • Webhook signature verification
  • Database transaction protection
  • Permission-based APIs
  • User data isolation

Production Considerations

Before deployment:

  • Set DEBUG=False
  • Configure HTTPS
  • Configure CORS
  • Use managed PostgreSQL
  • Use managed Redis
  • Configure logging
  • Add monitoring
  • Run migrations safely

Future Improvements

Possible extensions:

  • Celery background jobs
  • Email notifications
  • Analytics dashboard
  • Recommendation system
  • Elasticsearch integration
  • CI/CD pipeline
  • Kubernetes deployment

System Documentation

System Architecture

The backend follows a layered architecture:

System Architecture


Database ERD

The database design includes:

  • Users
  • Categories
  • Products
  • Orders
  • OrderItems
  • Payments
  • Webhook Events

Database ERD


Payment Flow

Stripe Payment Flow

Stripe Payment Flow

bKash Payment Flow

bKash Payment Flow


License

MIT License

Developed as a Backend Engineer assessment project.

Downloads last month

-

Downloads are not tracked for this model. How to track
Inference Providers NEW
This model isn't deployed by any Inference Provider. πŸ™‹ Ask for provider support