Skip to main content

A Python SDK for monetizing AI/autonomous agents with subscription and pay-per-use models

Project description

AI Agent Payments SDK

aiagent_payments Logo

Beta Buy Me a Coffee

A plug-and-play Python SDK for monetizing AI and autonomous agents. Easily add subscription, pay-per-use, and access control to your agentic, LLM, or SaaS apps—regardless of framework. Supports modular payment providers (Stripe, PayPal, Crypto, Mock) and pluggable storage (Memory, File, Database) with comprehensive health monitoring and validation.

Vision:

  • Make payments, access control, and usage tracking easy and robust for AI/agentic apps.
  • Provide a modular, extensible foundation for real-world, production-grade monetization.
  • Enable rapid prototyping and safe, compliant deployment for both indie hackers and enterprises.

Architecture & Design

  • Modular by Design: All providers and storage backends are pluggable and can be enabled/disabled via config or environment variables. Only enabled providers/storage are importable and usable; others will raise errors if used.
  • Extensible: Easy to add new payment providers, storage backends, or custom logic with capability reporting.

For a deep dive into the architecture, design decisions, and vision, see ARCHITECTURE_DECISION.md.


Features

  • Modular payment providers: Stripe, PayPal, Crypto, Mock
  • Pluggable storage: Memory, File, Database
  • Subscription, pay-per-use, and freemium models (SDK-managed subscriptions, not Stripe subscriptions)
  • CLI for setup, management, and analytics
  • Webhook support for Stripe/PayPal
  • Stripe Checkout Session support (hosted payment page URL)
  • Stripe Stablecoin payments (USDC, USDT, DAI, BUSD, GUSD)
  • Stripe Customer Management and Portal access
  • PayPal two-step payment flow (create_order → capture_order)
  • Usage tracking and analytics
  • Comprehensive health monitoring for all components
  • Input validation and error handling
  • Capability reporting for providers and storage
  • Robust logging, validation, and security
  • Configurable, code-level enable/disable for providers/storage (see below)
  • Comprehensive test suite with mock providers for development
  • Open-source friendly and extensible

Quickstart

from aiagent_payments import PaymentManager, PaymentPlan
from aiagent_payments.providers import create_payment_provider, StripeProvider, PayPalProvider, CryptoProvider, MockProvider
from aiagent_payments.storage import MemoryStorage, FileStorage, DatabaseStorage
from aiagent_payments.models import PaymentType, BillingPeriod

# Define a payment plan
plan = PaymentPlan(
    id="pro",
    name="Pro Plan",
    payment_type=PaymentType.SUBSCRIPTION,
    price=10.0,
    currency="USD",
    billing_period=BillingPeriod.MONTHLY,
    features=["premium"],
)

# Setup manager
provider = create_payment_provider("mock")  # or "stripe", "paypal", "crypto"
storage = MemoryStorage()
manager = PaymentManager(storage=storage, payment_provider=provider)
manager.create_payment_plan(plan)

# Subscribe a user (SDK manages subscription internally)
manager.subscribe_user("user@example.com", plan_id="pro")

Installation

  • Python: 3.10+
  • Install:
    pip install aiagent_payments
    
  • Optional extras:
    • stripe, paypalrestsdk, web3, sqlalchemy, alembic, flask, fastapi, uvicorn, crewai, python-dotenv
  • See requirements.txt and setup.py for full list.

Configuration

  • Enable/disable providers and storage in aiagent_payments/config.py:
    ENABLED_STORAGE = ["memory", "file", "database"]
    ENABLED_PROVIDERS = ["mock", "stripe", "paypal", "crypto"]
    
  • Or override via environment variables:
    export AIAgentPayments_EnabledStorage="memory,file,database"
    export AIAgentPayments_EnabledProviders="mock,stripe,paypal,crypto"
    
  • Use .env for local secrets (see example.env).
  • Note: Only enabled providers/storage are importable and usable; others will raise errors if used.

Usage

Basic Usage

from aiagent_payments import PaymentManager, PaymentPlan
# ...see Quickstart above...

Advanced Usage

Health Monitoring

from aiagent_payments.providers import StripeProvider
from aiagent_payments.storage import DatabaseStorage

# Check provider health
stripe_provider = StripeProvider(api_key="sk_test_...")
status = stripe_provider.check_health()
print(f"Provider healthy: {status.is_healthy}")

# Check storage health
storage = DatabaseStorage("payments.db")
status = storage.check_health()
print(f"Storage healthy: {status.is_healthy}")

# Get capabilities
capabilities = stripe_provider.get_capabilities()
print(f"Supports refunds: {capabilities.supports_refunds}")

Input Validation

from aiagent_payments.exceptions import ValidationError

try:
    # This will raise ValidationError for empty user_id
    pm.check_access("", "feature_name")
except ValidationError as e:
    print(f"Validation error: {e}")

CLI Usage

python cli/main.py --help

Stripe Checkout Sessions

You can generate a Stripe-hosted Checkout Session URL for your users:

from aiagent_payments.providers import StripeProvider
from aiagent_payments.models import PaymentPlan

stripe_provider = StripeProvider(api_key="sk_test_...")
plan = PaymentPlan(
    id="pro",
    name="Pro Plan",
    description="Premium access",
    payment_type=PaymentType.SUBSCRIPTION,
    price=10.0,
    currency="USD",
)
success_url = "https://yourapp.com/success"
cancel_url = "https://yourapp.com/cancel"
checkout_result = stripe_provider.create_checkout_session(
    user_id="user@example.com",
    plan=plan,
    success_url=success_url,
    cancel_url=cancel_url,
    metadata={"source": "web_checkout"}
)

# Use the checkout_url in your web application
checkout_url = checkout_result["url"]
session_id = checkout_result["session_id"]

Stripe Stablecoin Payments

Accept cryptocurrency payments using stablecoins like USDC, USDP, and USDG:

from aiagent_payments.providers import StripeProvider

stripe_provider = StripeProvider(api_key="sk_test_...")

# Create a stablecoin payment intent
payment_intent = stripe_provider.create_stablecoin_payment_intent(
    user_id="user@example.com",
    amount=25.00,
    currency="USD",
    stablecoin="usdc",
    metadata={"service": "ai_analysis"}
)

# Create a stablecoin checkout session (hosted payment page)
checkout_url = stripe_provider.create_stablecoin_checkout_session(
    user_id="user@example.com",
    amount=25.00,
    currency="USD",
    stablecoin="usdc",
    success_url="https://yourapp.com/success",
    cancel_url="https://yourapp.com/cancel"
)

# Process the payment
transaction = stripe_provider.process_stablecoin_payment(
    user_id="user@example.com",
    amount=15.99,
    currency="USD",
    stablecoin="usdp"
)

# Get supported stablecoins
stablecoins = stripe_provider.get_supported_stablecoins()
# ['usdc', 'usdp', 'usdg']

# Customer management
customer = stripe_provider.create_customer(
    user_id="user@example.com",
    email="customer@example.com",
    name="John Doe"
)

portal_url = stripe_provider.create_customer_portal_session(
    customer_id=customer["id"],
    return_url="https://yourapp.com/account"
)

Important: Stripe stablecoin payments are currently only available to a limited set of US businesses. You must:

  1. Have a US-based Stripe account
  2. Request access to Crypto payment method in your Payment methods settings
  3. Wait for Stripe's approval
  4. Have the crypto_payments capability active

For more details, see Stripe's stablecoin documentation.

PayPal Two-Step Payment Flow

PayPal Checkout requires user approval, so the SDK provides a two-step flow:

from aiagent_payments.providers import PayPalProvider

paypal_provider = PayPalProvider(
    client_id="your_client_id",
    client_secret="your_client_secret",
    sandbox=True,
    return_url="https://yourapp.com/return",
    cancel_url="https://yourapp.com/cancel"
)

# Step 1: Create order
order_response = paypal_provider.create_order(
    user_id="user_123",
    amount=25.99,
    currency="USD",
    return_url="https://yourapp.com/success",
    cancel_url="https://yourapp.com/cancel"
)

# Step 2: Get approval link and redirect user
approval_link = next(
    link['href'] for link in order_response['links'] 
    if link['rel'] == 'approve'
)

# Step 3: Capture after user approval (via webhook or return URL)
transaction = paypal_provider.capture_order(
    user_id="user_123",
    order_id=order_response['id']
)

Examples

The examples are organized into logical categories and have been curated to ensure they work end-to-end:

Basic Examples

Advanced Examples

Real-World Examples

Integration Examples

LangGraph Examples

All examples are tested and work without external API keys or dependencies. See the examples directory for more details.


Documentation


CLI Reference

  • python cli/main.py setup — Initialize storage and plans
  • python cli/main.py list-plans — List available payment plans
  • python cli/main.py subscribe --user user@example.com --plan pro — Subscribe a user
  • python cli/main.py status --user user@example.com — Show user subscription/status
  • See python cli/main.py --help for all commands and options

Extending the SDK

  • Add new providers: Implement PaymentProvider in aiagent_payments/providers/ with required methods including _get_capabilities(), _validate_configuration(), and _perform_health_check().
  • Add new storage: Implement StorageBackend in aiagent_payments/storage/ with required methods including _get_capabilities(), _validate_configuration(), and _perform_health_check().
  • Register in __init__.py and update config as needed.

Testing & Development

  • Run all tests:
    pytest --maxfail=3 --disable-warnings -v
    
  • Lint and format:
    make lint
    make format
    
  • Contribute: See CONTRIBUTORS.md
  • CI/CD runs on Python 3.12.

Compliance & Legal

  • Disclaimer: This SDK is provided as-is, with no warranty. You are responsible for compliance with all laws and payment provider terms (including Stripe, PayPal, and crypto APIs). You must supply your own API keys for production use of Stripe, PayPal, and Crypto providers.
  • Fallback/mock modes are for dev/test only and log warnings in production.
  • See DISCLAIMER.md for full details.

Roadmap & Limitations

  • See "Known Limitations and Roadmap" in this repo for planned features and current limitations.
  • Contributions welcome! See TODOs in code and open issues.

Get Involved

We welcome contributions, bug reports, and feedback from the AI agent developer community. Open an issue or pull request, or join the discussion to help shape the future of agent monetization.

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

aiagent_payments-0.0.1b1.tar.gz (110.6 kB view details)

Uploaded Source

Built Distribution

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

aiagent_payments-0.0.1b1-py3-none-any.whl (115.0 kB view details)

Uploaded Python 3

File details

Details for the file aiagent_payments-0.0.1b1.tar.gz.

File metadata

  • Download URL: aiagent_payments-0.0.1b1.tar.gz
  • Upload date:
  • Size: 110.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.12.11

File hashes

Hashes for aiagent_payments-0.0.1b1.tar.gz
Algorithm Hash digest
SHA256 7a96f3373535fdeb01c123c18932787de428afdc1f7c5eba956b3d242211d0a1
MD5 eeb41a9c10abf51cdfb40a95d4c1702d
BLAKE2b-256 1f611c605f41438e8c4a542baaafe5dda2fdfa4cf834192219abf1b9cc9958a7

See more details on using hashes here.

File details

Details for the file aiagent_payments-0.0.1b1-py3-none-any.whl.

File metadata

File hashes

Hashes for aiagent_payments-0.0.1b1-py3-none-any.whl
Algorithm Hash digest
SHA256 e57d4868ec10010e7f815f783591d986d545d67ca4d7454e8e1aee5a99581ca0
MD5 f5dcda346961eb1d38c25506d449f87e
BLAKE2b-256 40319c4ab1dee0af271c96856250813ba6838176a931ce294e22415530946fce

See more details on using hashes here.

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