Skip to content

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

Β 

History

4 Commits

Folders and files

Repository files navigation

E-Commerce Backend API

Complete e-commerce backend system built with Spring Boot 3, MongoDB, and Mock Payment Service.

🎯 Features

  • βœ… Product Management (Create, List, Search)
  • βœ… Shopping Cart (Add, View, Clear)
  • βœ… Order Management (Create from cart, View details)
  • βœ… Payment Processing (Mock service with webhook)
  • βœ… Stock Management (Automatic updates)
  • βœ… Complete Order Flow (Products β†’ Cart β†’ Order β†’ Payment β†’ Status Update)

πŸ—οΈ Architecture

E-Commerce API (Port 8080) ←→ Mock Payment Service (Port 8081)
           ↓
      MongoDB (Port 27017)

Two Applications:

  1. Main E-Commerce API - Handles products, cart, orders, and payments
  2. Mock Payment Service - Simulates payment processing and webhook callbacks

πŸ“‹ Prerequisites

  • Java 17 or higher
  • Maven 3.6+
  • MongoDB (running on localhost:27017)

πŸš€ Setup Instructions

1. Install MongoDB

macOS (using Homebrew):

brew tap mongodb/brew
brew install mongodb-community
brew services start mongodb-community

Verify MongoDB is running:

mongosh

2. Clone and Build

cd /Users/princeshakya/Desktop/E-Commerce

Build Main Application:

mvn clean install

Build Payment Service:

cd payment-service
mvn clean install
cd ..

3. Run Applications

Terminal 1 - Start Mock Payment Service:

cd payment-service
mvn spring-boot:run

Terminal 2 - Start Main E-Commerce API:

mvn spring-boot:run

Verify both services are running:

πŸ“š API Endpoints

Product APIs

Method Endpoint Description
POST /api/products Create a new product
GET /api/products Get all products
GET /api/products/{id} Get product by ID
GET /api/products/search?q=laptop Search products (Bonus)

Cart APIs

Method Endpoint Description
POST /api/cart/add Add item to cart
GET /api/cart/{userId} Get user's cart
DELETE /api/cart/{userId}/clear Clear cart

Order APIs

Method Endpoint Description
POST /api/orders Create order from cart
GET /api/orders/{orderId} Get order details
GET /api/orders/user/{userId} Get user order history (Bonus)
POST /api/orders/{orderId}/cancel Cancel order if not paid (Bonus)

Payment APIs

Method Endpoint Description
POST /api/payments/create Create payment
POST /api/webhooks/payment Payment webhook (called by payment service)

πŸ§ͺ Testing with Postman

Import Collection

  1. Import E-Commerce-API.postman_collection.json
  2. Collection includes all endpoints with sample requests
  3. Variables: userId, productId, orderId are auto-populated

Complete Order Flow Test

Step 1: Create Products

POST http://localhost:8080/api/products
{
  "name": "Laptop",
  "description": "Gaming Laptop",
  "price": 50000.0,
  "stock": 10
}

Step 2: Add to Cart

POST http://localhost:8080/api/cart/add
{
  "userId": "user123",
  "productId": "<productId from step 1>",
  "quantity": 2
}

Step 3: View Cart

GET http://localhost:8080/api/cart/user123

Step 4: Create Order

POST http://localhost:8080/api/orders
{
  "userId": "user123"
}

Note: Cart will be cleared, stock will be reduced

Step 5: Create Payment

POST http://localhost:8080/api/payments/create
{
  "orderId": "<orderId from step 4>",
  "amount": 100000.0
}

Step 6: Wait 3 seconds for webhook

Payment service will automatically:

  • Wait 3 seconds (simulate processing)
  • Call webhook: POST http://localhost:8080/api/webhooks/payment
  • Update payment status (SUCCESS/FAILED)
  • Update order status (PAID/FAILED)

Step 7: Check Order Status

GET http://localhost:8080/api/orders/<orderId>

πŸ“Š Sample Data

Create Sample Products

[
  {
    "name": "Laptop",
    "description": "Gaming Laptop",
    "price": 50000.0,
    "stock": 10
  },
  {
    "name": "Mouse",
    "description": "Wireless Mouse",
    "price": 1000.0,
    "stock": 50
  },
  {
    "name": "Keyboard",
    "description": "Mechanical Keyboard",
    "price": 3000.0,
    "stock": 30
  }
]

πŸ” How It Works

Order Creation Flow

  1. User adds items to cart β†’ Validates product exists & stock available
  2. User creates order β†’
    • Validates cart not empty
    • Checks all items in stock
    • Creates order with status CREATED
    • Creates order items (snapshot prices)
    • Reduces product stock
    • Clears cart
  3. User initiates payment β†’
    • Validates order status is CREATED
    • Creates payment with status PENDING
    • Calls mock payment service
  4. Payment service processes β†’
    • Waits 3 seconds
    • Sends webhook with status (SUCCESS/FAILED)
  5. Webhook updates β†’
    • Updates payment status
    • Updates order status (PAID/FAILED)

Payment Webhook Pattern

E-Commerce API                Mock Payment Service
      |                              |
      |---(1) Create Payment-------->|
      |<--(2) Payment Initiated------|
      |                              |
      |                         (Wait 3s)
      |                              |
      |<--(3) Webhook Callback------|
      |    (Payment Status)          |
      |                              |
   (Update Order Status)

πŸ› Error Handling

  • Validation Errors β†’ 400 Bad Request with field errors
  • Resource Not Found β†’ 404 Not Found
  • Business Logic Errors β†’ 400 Bad Request with message
    • Empty cart
    • Insufficient stock
    • Invalid order status
  • Server Errors β†’ 500 Internal Server Error

πŸ“ Project Structure

E-Commerce/
β”œβ”€β”€ src/main/java/com/example/ecommerce/
β”‚   β”œβ”€β”€ model/              # Entities (User, Product, Order, etc.)
β”‚   β”œβ”€β”€ repository/         # MongoDB Repositories
β”‚   β”œβ”€β”€ service/            # Business Logic
β”‚   β”œβ”€β”€ controller/         # REST Controllers
β”‚   β”œβ”€β”€ dto/                # Request/Response DTOs
β”‚   β”œβ”€β”€ exception/          # Exception Handling
β”‚   β”œβ”€β”€ config/             # Configuration
β”‚   └── webhook/            # Webhook Controllers
β”œβ”€β”€ payment-service/
β”‚   └── src/main/java/com/example/paymentservice/
β”‚       β”œβ”€β”€ controller/     # Mock Payment Controller
β”‚       β”œβ”€β”€ dto/            # DTOs
β”‚       └── config/         # Configuration
└── pom.xml

βœ… Grading Checklist

  • Product APIs (15 points)
  • Cart APIs (20 points)
  • Order APIs (25 points)
  • Payment Integration (30 points)
  • Order Status Update (10 points)
  • Code Quality (10 points) - Clean code, proper structure
  • Postman Collection (10 points)

🎁 Bonus Features Implemented

  1. Order History - GET /api/orders/user/{userId} - View all orders for a user (+5 points)
  2. Product Search - GET /api/products/search?q=<query> - Search products by name (+5 points)
  3. Order Cancellation - POST /api/orders/{orderId}/cancel - Cancel order if not paid, restore stock (+5 points)

πŸ”§ Troubleshooting

MongoDB Connection Error

Error: MongoSocketOpenException

Solution: Ensure MongoDB is running

brew services start mongodb-community

Port Already in Use

Error: Port 8080 is already in use

Solution: Kill process or change port in application.yaml

Payment Service Not Responding

Error calling payment service

Solution: Ensure payment service is running on port 8081

πŸ“ Notes

  • Mock Payment Service: 90% success rate (randomly fails 10% of time for testing)
  • Stock Management: Automatic stock reduction on order creation
  • Cart Behavior: Cart cleared automatically after order creation
  • Order Status: CREATED β†’ PAID (on success) or FAILED (on failure)
  • Payment Status: PENDING β†’ SUCCESS or FAILED

πŸ‘¨β€πŸ’» Developer

Built for in-class assignment following Spring Boot best practices with clean architecture and proper error handling.

Built with πŸ’š by Prince Shakya

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages