Skip to content

stephenombuya/Subscription-Service-Management

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Subscription Service Management (SaaS Platform)

Overview

This project is a back-end system for managing subscription-based services, such as software or media platforms. It enables businesses to offer subscription plans, process recurring payments, and manage user accounts effectively.

Technologies Used

  • Java: Main programming language.
  • Spring Boot: Framework for building RESTful APIs.
  • MySQL: Database for storing user accounts, subscription plans, and transactions.
  • Spring Data JPA: ORM for database interactions.
  • Spring Security: For authentication and authorization.
  • Stripe/PayPal SDK: For payment processing and recurring billing.
  • Swagger/OpenAPI: For API documentation.

System Structure

1. Architecture Pattern

  • Layered Architecture (N-tier architecture)
  • Main layers:
    • Controller Layer: Handles HTTP requests.
    • Service Layer: Implements business logic.
    • Repository Layer: Manages database interactions.
    • Security Layer: Ensures authentication and authorization.

2. Package Structure

com.saasplatform
│── controller      # Handles HTTP requests
│── service         # Contains business logic
│── repository      # Database access
│── model           # Entity classes representing database tables
│── dto             # Data Transfer Objects for API requests/responses
│── config          # Configuration files (Security, Database, etc.)
│── exception       # Custom exception handling
│── util            # Utility classes (e.g., email notifications, validators)

3. Database Schema

  • Users: Stores customer and admin details (ID, name, email, role, etc.).
  • Subscription Plans: Stores plan details (ID, name, price, billing cycle, features).
  • Subscriptions: Tracks active and canceled subscriptions (ID, user, plan, status, start/end date).
  • Payments: Manages transactions, invoices, and billing history.
  • Usage Analytics: Tracks customer engagement, churn rate, and revenue.

Features

1. Subscription Plan Management

  • Admins can create, update, and remove subscription plans.
  • Pricing, billing cycles, and plan features are configurable.

2. User Registration & Payments

  • Customers can register, log in, and manage their accounts.
  • Secure payment processing through Stripe or PayPal.

3. Subscription Management

  • Users can subscribe to plans, upgrade, downgrade, or cancel subscriptions.
  • Manage payment methods and billing preferences.

4. Recurring Billing

  • Automated handling of recurring payments.
  • Manage failed payments, retry logic, and account suspensions.

5. Usage Analytics

  • Track customer engagement, revenue, and churn rate.
  • Generate reports for business insights.

6. Admin Dashboard

  • Manage users, subscriptions, payments, and performance metrics.
  • Monitor system activity and subscription trends.

Installation & Setup

Prerequisites

  • Java 17+
  • MySQL Server
  • Maven

Steps to Run

  1. Clone the repository:
    git clone https://github.com/stephenombuya/Subscription-Service-Management
    cd subscription-saas
  2. Configure MySQL database in application.properties:
    spring.datasource.url=jdbc:mysql://localhost:3306/saas_db
    spring.datasource.username=root
    spring.datasource.password=yourpassword
  3. Install dependencies:
    mvn clean install
  4. Run the application:
    mvn spring-boot:run

API Documentation

After starting the application, access API docs at:

Subscription Service Management - SaaS Backend

A production-grade Spring Boot backend system for managing subscription-based SaaS services. Built with Java 17, Spring Boot 3.2, MySQL, and Stripe.


Features

Feature Description
JWT Authentication Access tokens + refresh tokens with configurable expiry
Rate Limiting Per-IP token-bucket rate limiting via Bucket4j
Role-Based Access ADMIN and CUSTOMER roles with method-level security
Subscription Management Subscribe, upgrade/downgrade, cancel, reactivate
Recurring Billing Stripe integration with webhooks for payment events
Email Notifications Async emails for verification, billing, renewals
Scheduled Jobs Auto-expire subscriptions, send renewal reminders
Analytics Dashboard Churn rate, MRR, engagement scores
Swagger UI Full interactive API documentation
Comprehensive Testing Unit + integration tests with H2 in-memory DB

Tech Stack

  • Java 17 + Spring Boot 3.2
  • Spring Security (JWT, method security)
  • Spring Data JPA + MySQL 8
  • Bucket4j (rate limiting)
  • JJWT 0.12 (JWT)
  • Stripe Java SDK (payments)
  • SpringDoc OpenAPI 2 (Swagger)
  • MapStruct + Lombok
  • JUnit 5 + Mockito + H2 (tests)

Project Structure

com.saasplatform
├── controller/          # REST controllers (Auth, Plans, Subscriptions, Payments, Admin, Webhooks)
├── service/             # Business logic
├── repository/          # Spring Data JPA repositories
├── model/               # JPA entities (User, SubscriptionPlan, Subscription, Payment, UsageAnalytics)
├── dto/
│   ├── request/         # Incoming request DTOs (validated with Jakarta Bean Validation)
│   └── response/        # Outgoing response DTOs
├── security/            # JWT filter, rate limiting filter, UserDetailsService
├── config/              # SecurityConfig, OpenApiConfig, AppConfig
├── exception/           # Custom exceptions + GlobalExceptionHandler
└── util/                # DataSeeder (seeds admin + plans on startup)

Quick Start

Prerequisites

  • Java 17+
  • MySQL 8+ running locally
  • Maven 3.8+
  • (Optional) Stripe account for real payment processing

1. Clone & Configure

git clone https://github.com/stephenombuya/Subscription-Service-Management
cd subscription-saas

Edit src/main/resources/application.properties:

# Database
spring.datasource.url=jdbc:mysql://localhost:3306/saas_db?createDatabaseIfNotExist=true
spring.datasource.username=root
spring.datasource.password=yourpassword

# JWT (change to a secure 256-bit base64 key in production)
app.jwt.secret=404E635266556A586E3272357538782F413F4428472B4B6250645367566B5970
app.jwt.expiration-ms=86400000        # 24 hours
app.jwt.refresh-expiration-ms=604800000  # 7 days

# Stripe
stripe.api.key=sk_test_YOUR_STRIPE_KEY
stripe.webhook.secret=whsec_YOUR_WEBHOOK_SECRET

# Email (Gmail example)
spring.mail.username=your-email@gmail.com
spring.mail.password=your-app-password

# Rate Limiting (100 requests/minute per IP)
app.rate-limit.capacity=100
app.rate-limit.refill-tokens=100
app.rate-limit.refill-duration-minutes=1

2. Build & Run

mvn clean install
mvn spring-boot:run

The app will:

  • Create the database schema automatically
  • Seed a default admin account: admin@saasplatform.com / Admin@123
  • Seed 3 default subscription plans (Starter, Professional, Enterprise)

3. Access API Docs

ddca1b9 (Initial commit: Subscription Service Management Backend)

http://localhost:8080/swagger-ui/index.html

=======

API Overview

Authentication (/api/v1/auth)

Method Endpoint Auth Description
POST /register Public Register new user
POST /login Public Login, returns JWT tokens
POST /refresh-token Public Refresh access token
GET /verify-email?token= Public Verify email address
POST /forgot-password Public Request password reset
POST /reset-password Public Reset password with token
POST /change-password Bearer Change password
POST /logout Bearer Invalidate refresh token

Subscription Plans (/api/v1/plans)

Method Endpoint Auth Description
GET / Public List all active plans
GET /{id} Public Get plan by ID
POST / Admin Create plan
PUT /{id} Admin Update plan
PATCH /{id}/deactivate Admin Deactivate plan
DELETE /{id} Admin Delete plan (no subscribers)

Subscriptions (/api/v1/subscriptions)

Method Endpoint Auth Description
POST / Bearer Subscribe to a plan
GET / Bearer Get own subscriptions
GET /{id} Bearer Get subscription detail
PATCH /{id}/change-plan Bearer Upgrade / downgrade plan
PATCH /{id}/cancel Bearer Cancel subscription
PATCH /{id}/reactivate Bearer Reactivate subscription

Payments (/api/v1/payments)

Method Endpoint Auth Description
GET / Bearer Paginated payment history
GET /{id} Bearer Get payment detail
POST /{id}/refund?amount= Bearer Process refund

Admin (/api/v1/admin)

Method Endpoint Auth Description
GET /dashboard Admin Stats, MRR, churn rate
GET /users Admin All users (paginated)
PATCH /users/{id}/lock Admin Lock user account
PATCH /users/{id}/unlock Admin Unlock user account
PATCH /users/{id}/promote Admin Promote to admin
GET /subscriptions Admin All subscriptions

Webhooks (/api/v1/webhooks)

Method Endpoint Auth Description
POST /stripe Public Stripe webhook handler

Authentication Flow

1. POST /api/v1/auth/register  →  Create account (email not yet verified)
2. Click link in email          →  GET /api/v1/auth/verify-email?token=...
3. POST /api/v1/auth/login      →  Returns { accessToken, refreshToken }
4. Use accessToken in header:   →  Authorization: Bearer <accessToken>
5. When expired:                →  POST /api/v1/auth/refresh-token

Rate Limiting

All endpoints (except /actuator) are rate-limited per IP address using a token bucket algorithm:

  • Default: 100 requests per minute per IP
  • Response headers: X-Rate-Limit-Remaining
  • 429 Too Many Requests when exceeded

Configure in application.properties:

app.rate-limit.capacity=100
app.rate-limit.refill-tokens=100
app.rate-limit.refill-duration-minutes=1

Stripe Integration

Setup

  1. Get your Stripe API keys from dashboard.stripe.com
  2. Set stripe.api.key in application.properties
  3. For webhooks, use Stripe CLI locally: stripe listen --forward-to localhost:8080/api/v1/webhooks/stripe

Handled Webhook Events

  • invoice.payment_succeeded — Activates subscription
  • invoice.payment_failed — Marks as past_due, suspends after 3 failures
  • customer.subscription.deleted — Cancels subscription
  • customer.subscription.updated — Syncs subscription status

Running Tests

# All tests
mvn test

# Only unit tests
mvn test -Dtest=*Test

# Only integration tests  
mvn test -Dtest=*IntegrationTest

Tests use an H2 in-memory database and do not require MySQL or Stripe.


Security Features

  • BCrypt password hashing (strength 12)
  • JWT with configurable expiry
  • Refresh tokens stored in DB (single active token per user)
  • Method-level @PreAuthorize security
  • CORS configured for cross-origin requests
  • Account locking for admin control
  • Email verification required before login

Contribution

Contributions are welcome! Feel free to submit a pull request or open an issue.

License

This project is licensed under the MIT License.

About

This project is a back-end system for managing subscription-based services, such as software or media platforms. It enables businesses to offer subscription plans, process recurring payments, and manage user accounts effectively.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages