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

# Manage API keys
poetry run ai-billing promote --api-key ABC123
poetry run ai-billing demote --api-key ABC123

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-2.6.1.tar.gz (36.4 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-2.6.1-py3-none-any.whl (38.4 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: augint_billing_lib-2.6.1.tar.gz
  • Upload date:
  • Size: 36.4 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-2.6.1.tar.gz
Algorithm Hash digest
SHA256 2542a9f2dbcc183eedf394c011c3be2ff6bb0d9180591d30a2f79ef9747fd6be
MD5 59eb214b693ad7305c7438d6397bb6b1
BLAKE2b-256 5f566c2ab9930d7e259c13f9404bf2872cdd913235f4c6c23a0896f3d656fc75

See more details on using hashes here.

Provenance

The following attestation bundles were made for augint_billing_lib-2.6.1.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-2.6.1-py3-none-any.whl.

File metadata

File hashes

Hashes for augint_billing_lib-2.6.1-py3-none-any.whl
Algorithm Hash digest
SHA256 b60d6c005cb5e886e3670fd864ddf9d40e774824f7209109aba1a9a14140823a
MD5 44747b2a46e1ee0fcddd902eaf581104
BLAKE2b-256 03d4f15ced681b9f964a45b9ddb58971a9c7306b87fc695c119a45bda8cb28ca

See more details on using hashes here.

Provenance

The following attestation bundles were made for augint_billing_lib-2.6.1-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