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.
📊 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 logicPorts- Abstract interfaces defining external dependenciesAdapters- Concrete implementations for AWS and StripeBootstrap- Dependency injection and Lambda handler setup
Billing Flows
1. Card Attachment → Plan Promotion
When a user adds a payment method:
- Stripe sends
payment_method.attachedevent - Service ensures metered subscription exists
- API key moves from
FREE_10KtoMETEREDusage plan - DynamoDB updated with new plan status
2. Payment Failure → Plan Demotion
When payment fails:
- Stripe sends
invoice.payment_failedevent - Service cancels metered subscription
- API key moves back to
FREE_10Kusage plan - User continues with free tier limits
3. Hourly Usage Reporting
Every hour:
- Lambda triggered by CloudWatch schedule
- Fetches usage from API Gateway for all metered users
- Calculates delta from last reported checkpoint
- Reports usage to Stripe with idempotency
- 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
- Product Requirements - Business requirements and goals
- Technical Contract - Cross-repository integration spec
- Implementation Plan - Development roadmap and testing strategy
- Architecture Flows - Sequence diagrams for key workflows
- Class Diagram - System architecture overview
Contributing
We welcome contributions! Please follow these guidelines:
Branch Naming
feat/issue-N-description- New featuresfix/issue-N-description- Bug fixesdocs/issue-N-description- Documentationtest/issue-N-description- Test improvementschore/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
- Create feature branch from
main - Write tests for new functionality
- Ensure all tests pass (
make test-all) - Run pre-commit checks (
poetry run pre-commit run --all-files) - Create PR with clear description
- Link issues with
Closes #NorRefs #N
License
This project is proprietary software. All rights reserved. See LICENSE for details.
Support
- Issues: GitHub Issues
- Discussions: GitHub Discussions
- Security: Report vulnerabilities via GitHub Security
Built for Production • Serverless First
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file augint_billing_lib-3.1.0.tar.gz.
File metadata
- Download URL: augint_billing_lib-3.1.0.tar.gz
- Upload date:
- Size: 88.0 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.12.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
20ed840010f03061cc682b4f247cb5e25211372b3b7c1001f8f45522809c7dcd
|
|
| MD5 |
69dcb1931f33f04c26ea196480c47fdb
|
|
| BLAKE2b-256 |
583c00034f1c3b8eb608a7699f55d72f6a48da4ffd3277146498562f800e158a
|
Provenance
The following attestation bundles were made for augint_billing_lib-3.1.0.tar.gz:
Publisher:
pipeline.yaml on svange/augint-billing-lib
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
augint_billing_lib-3.1.0.tar.gz -
Subject digest:
20ed840010f03061cc682b4f247cb5e25211372b3b7c1001f8f45522809c7dcd - Sigstore transparency entry: 426497888
- Sigstore integration time:
-
Permalink:
svange/augint-billing-lib@39b2ade006b3073eb9698574faf74f2e697d2a5d -
Branch / Tag:
refs/heads/main - Owner: https://github.com/svange
-
Access:
private
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
pipeline.yaml@39b2ade006b3073eb9698574faf74f2e697d2a5d -
Trigger Event:
push
-
Statement type:
File details
Details for the file augint_billing_lib-3.1.0-py3-none-any.whl.
File metadata
- Download URL: augint_billing_lib-3.1.0-py3-none-any.whl
- Upload date:
- Size: 121.0 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.12.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
2dfc6519ce4523d935250e2997426efcf627ddd2226cbff70f0ccd79c7ecaf33
|
|
| MD5 |
88f6037a92baf7b7b2cf5f99d87c350f
|
|
| BLAKE2b-256 |
5eaadf923778086b01254a16bb12a1dbd5cb8f4cee08a08f824dd58f62c03a77
|
Provenance
The following attestation bundles were made for augint_billing_lib-3.1.0-py3-none-any.whl:
Publisher:
pipeline.yaml on svange/augint-billing-lib
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
augint_billing_lib-3.1.0-py3-none-any.whl -
Subject digest:
2dfc6519ce4523d935250e2997426efcf627ddd2226cbff70f0ccd79c7ecaf33 - Sigstore transparency entry: 426497891
- Sigstore integration time:
-
Permalink:
svange/augint-billing-lib@39b2ade006b3073eb9698574faf74f2e697d2a5d -
Branch / Tag:
refs/heads/main - Owner: https://github.com/svange
-
Access:
private
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
pipeline.yaml@39b2ade006b3073eb9698574faf74f2e697d2a5d -
Trigger Event:
push
-
Statement type: