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.7.2.tar.gz (42.7 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.7.2-py3-none-any.whl (45.7 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: augint_billing_lib-2.7.2.tar.gz
  • Upload date:
  • Size: 42.7 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.7.2.tar.gz
Algorithm Hash digest
SHA256 2e7ec043c36299ae68768ea03a30a65f55c785e4faa63ff35d3cf922a75a5ccc
MD5 3121c7b420aff7a5c2c46268c28b8da4
BLAKE2b-256 1c6e73c01e3b5c08c68690ca1d82fc50e241d003ea080caf33ae250f2283b323

See more details on using hashes here.

Provenance

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

File metadata

File hashes

Hashes for augint_billing_lib-2.7.2-py3-none-any.whl
Algorithm Hash digest
SHA256 e75ae063a1afbcc6ceb8286b72c1a32b53943c2f3bc0258989784868388c21e3
MD5 8e21bd8f13e5d80f4495d3eed9def77f
BLAKE2b-256 1f2c234d7390022a83c9c3292792c1b19058bfc3cfd9cab9abd90799470013c9

See more details on using hashes here.

Provenance

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