Skip to main content

Billing service library for API usage tracking and Stripe integration.

Project description

Augint Billing Library

Production-ready Python library for Stripe-powered usage-based billing with AWS integration.

CI Pipeline PyPI Python Poetry Code style: Ruff License: Proprietary

📊 Live Dashboards

📖 Documentation 🧪 Unit Tests 🔬 Integration Tests 📊 Coverage Benchmarks 🔒 Security ⚖️ Compliance

Overview

A serverless billing library that seamlessly integrates Stripe payment processing with AWS API Gateway usage tracking. Designed for SaaS applications with tiered pricing models, providing automatic plan transitions based on payment status and real-time usage reporting.

Key Features

  • 🎯 Usage-Based Billing - Track API usage and automatically bill based on consumption
  • 💳 Stripe Integration - Complete payment processing with subscriptions and metered billing
  • 🔄 Automatic Plan Transitions - Move users between free and paid tiers based on payment status
  • 📊 Real-Time Usage Reporting - Hourly synchronization with Stripe for accurate billing
  • 🏗️ Clean Architecture - Ports & adapters pattern for maintainable, testable code
  • 🚀 Serverless Ready - Optimized for AWS Lambda with minimal cold start overhead
  • 🛡️ Production Hardened - Retry logic, circuit breakers, and comprehensive error handling

Quick Start

Installation

pip install augint-billing-lib

Basic Usage

from augint_billing_lib import bootstrap

# Process a Stripe webhook event
result = bootstrap.process_event_and_apply_plan_moves({
    "type": "payment_method.attached",
    "data": {"object": {"customer": "cus_123"}}
})

# Report usage to Stripe
reports = bootstrap.report_current_hour_usage()

CLI Commands

# Show environment configuration
poetry run ai-billing env-dump

# Handle Stripe events locally
poetry run ai-billing handle-event --file tests/fixtures/setup_intent.succeeded.json

# Report usage to Stripe
poetry run ai-billing sync-usage

# Monitor Zero-Touch operations
poetry run ai-billing monitor dashboard

# Check infrastructure status
poetry run ai-billing infra status

Architecture

The library follows a Ports & Adapters (Hexagonal) architecture pattern:

graph TB
    subgraph "Core Domain"
        BS[BillingService]
        M[Models]
    end

    subgraph "Ports (Interfaces)"
        SP[StripePort]
        USP[UsageSourcePort]
        CRP[CustomerRepoPort]
        PAP[PlanAdminPort]
    end

    subgraph "Adapters (Implementations)"
        SA[StripeAdapter]
        UA[APIGatewayUsageAdapter]
        DRA[DynamoDBRepoAdapter]
        PAA[APIGatewayAdminAdapter]
    end

    subgraph "External Systems"
        S[Stripe API]
        AG[API Gateway]
        DD[DynamoDB]
    end

    BS --> SP
    BS --> USP
    BS --> CRP
    BS --> PAP

    SP -.-> SA
    USP -.-> UA
    CRP -.-> DRA
    PAP -.-> PAA

    SA --> S
    UA --> AG
    DRA --> DD
    PAA --> AG

Core Components

  • BillingService - Orchestrates billing operations and business logic
  • Ports - Abstract interfaces defining external dependencies
  • Adapters - Concrete implementations for AWS and Stripe
  • Bootstrap - Dependency injection and Lambda handler setup

Billing Flows

1. Card Attachment → Plan Promotion

When a user adds a payment method:

  1. Stripe sends payment_method.attached event
  2. Service ensures metered subscription exists
  3. API key moves from FREE_10K to METERED usage plan
  4. DynamoDB updated with new plan status

2. Payment Failure → Plan Demotion

When payment fails:

  1. Stripe sends invoice.payment_failed event
  2. Service cancels metered subscription
  3. API key moves back to FREE_10K usage plan
  4. User continues with free tier limits

3. Hourly Usage Reporting

Every hour:

  1. Lambda triggered by CloudWatch schedule
  2. Fetches usage from API Gateway for all metered users
  3. Calculates delta from last reported checkpoint
  4. Reports usage to Stripe with idempotency
  5. Updates DynamoDB with new checkpoint

Configuration

Required Environment Variables

# CloudFormation stack identifier
STACK_NAME=augint-billing-prod

# AWS region for resources
AWS_REGION=us-east-1

# Stripe authentication (use one)
STRIPE_SECRET_KEY=sk_live_...
# OR
STRIPE_SECRET_ARN=arn:aws:secretsmanager:...

Optional Environment Variables

# DynamoDB table name (default: {STACK_NAME}-customer-links)
TABLE_NAME=billing-customer-links

# API Gateway usage plan IDs
FREE_USAGE_PLAN_ID=FREE_10K        # Default free tier plan
METERED_USAGE_PLAN_ID=METERED      # Default paid tier plan

# API Gateway product ID (auto-discovered if not set)
API_USAGE_PRODUCT_ID=prod_123

Development

Setup

# Clone repository
git clone https://github.com/svange/augint-billing-lib.git
cd augint-billing-lib

# Install dependencies
poetry install

# Run tests
make test              # Unit tests only
make test-integration  # Integration tests
make test-e2e         # End-to-end tests
make test-all         # All tests

# Code quality
poetry run pre-commit run --all-files

Testing Strategy

The library uses a "Mock at the Boundaries" approach:

  • Unit tests mock external services (Stripe, AWS)
  • Integration tests use real adapters with mocked APIs
  • E2E tests validate complete workflows

Project Structure

src/augint_billing_lib/
├── adapters/          # Concrete implementations
│   ├── stripe.py      # Stripe API integration
│   ├── ddb_repo.py    # DynamoDB repository
│   ├── apigw_usage.py # Usage data collection
│   └── apigw_admin.py # Plan administration
├── ports.py           # Abstract interfaces
├── service.py         # Core business logic
├── models.py          # Data models
├── bootstrap.py       # Dependency injection
└── cli.py            # CLI commands

Documentation

Contributing

We welcome contributions! Please follow these guidelines:

Branch Naming

  • feat/issue-N-description - New features
  • fix/issue-N-description - Bug fixes
  • docs/issue-N-description - Documentation
  • test/issue-N-description - Test improvements
  • chore/issue-N-description - Maintenance

Commit Convention

Use conventional commits:

feat: add usage caching layer
fix: handle month boundary in usage reporting
docs: update stripe integration guide
test: add e2e payment flow tests
chore: update dependencies

Pull Request Process

  1. Create feature branch from main
  2. Write tests for new functionality
  3. Ensure all tests pass (make test-all)
  4. Run pre-commit checks (poetry run pre-commit run --all-files)
  5. Create PR with clear description
  6. Link issues with Closes #N or Refs #N

License

This project is proprietary software. All rights reserved. See LICENSE for details.

Support


Built for ProductionServerless First

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

augint_billing_lib-3.2.0.tar.gz (96.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

augint_billing_lib-3.2.0-py3-none-any.whl (133.4 kB view details)

Uploaded Python 3

File details

Details for the file augint_billing_lib-3.2.0.tar.gz.

File metadata

  • Download URL: augint_billing_lib-3.2.0.tar.gz
  • Upload date:
  • Size: 96.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.12.9

File hashes

Hashes for augint_billing_lib-3.2.0.tar.gz
Algorithm Hash digest
SHA256 68082e55e2481c4f1fd98d05496acb240d1fe6483ea5bebc244d280de6c3de27
MD5 a30f674a31a1b24f1cb092d4bb3f761e
BLAKE2b-256 1b9d13dcfca70715c7b192a388f14ae0987aa5ea1ec738bc36f2abb219b34260

See more details on using hashes here.

Provenance

The following attestation bundles were made for augint_billing_lib-3.2.0.tar.gz:

Publisher: pipeline.yaml on svange/augint-billing-lib

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file augint_billing_lib-3.2.0-py3-none-any.whl.

File metadata

File hashes

Hashes for augint_billing_lib-3.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 bb0895b10b9f78b52e4663093e9051a307342cc2beb9f6d52dd2e91f6bb8d5c7
MD5 adb0a23857a007ee87609d8f0694c97b
BLAKE2b-256 6f3b9ffd3331e78acd9c88baed148efea22d397d923ee42aa0f8d644134f7b2b

See more details on using hashes here.

Provenance

The following attestation bundles were made for augint_billing_lib-3.2.0-py3-none-any.whl:

Publisher: pipeline.yaml on svange/augint-billing-lib

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page