Skip to main content

The official Python SDK for SettleSettle — Revenue OS for African developers

Project description

SettleSettle Python SDK

The official Python SDK for SettleSettle — the Revenue OS for African developers. Securely monetize your apps via local fiat rails (Paystack, Flutterwave) or stablecoin payments (Solana USDC) with built-in credit wallets, subscription engines, and automated event tracking.


Features

  • Sync & Async Support: Supports both synchronous (Django, Flask, Celery) and asynchronous (FastAPI, Starlette) Python frameworks.
  • Credit Wallets: Effortlessly manage credit packages, debits, credits, and ledger histories.
  • Subscriptions Engine: Add recurring pricing, trial period checks, and subscription access control.
  • Omni-Billing: Single unified API for fiat, crypto, credit, and subscription setups.
  • Usage-Based Tracking: Non-blocking background event buffering and reporting.
  • Rewarded Ad Support: Verified rewarded ad slot integrations to monetize users with zero-credit fallbacks.

Installation

pip install settlesettle

Quick Start

1. Initialize the Client

Set the SETTLESETTLE_API_KEY environment variable:

export SETTLESETTLE_API_KEY="ss_live_..."

Or pass it directly:

from settlesettle import SettleSettle

settle = SettleSettle(api_key="ss_live_...")

Usage Examples

Synchronous (Django / Flask)

from settlesettle import SettleSettle, InsufficientCreditsError

# Reads SETTLESETTLE_API_KEY from environment
settle = SettleSettle()

def process_ai_query(user_id: str, prompt: str):
    try:
        # 1. Debit the wallet for the action cost
        settle.wallet.debit(user_id, amount=10, description="AI Query")
    except InsufficientCreditsError as e:
        return {
            "error": "insufficient_credits",
            "current_balance": e.current_balance,
            "requested": e.requested_amount,
        }

    # 2. Run the actual business logic
    result = run_ai_query(prompt)

    # 3. Track the usage event (non-blocking, buffered)
    settle.events.track(
        user_id=user_id,
        event_type="AI_QUERY",
        metadata={"prompt_length": len(prompt)}
    )

    return {"result": result}

Asynchronous (FastAPI)

from contextlib import asynccontextmanager
from fastapi import FastAPI, HTTPException
from settlesettle import AsyncSettleSettle, InsufficientCreditsError

# Initialize async client
settle = AsyncSettleSettle()

@asynccontextmanager
async def lifespan(app: FastAPI):
    yield
    # Flush buffered events and close HTTP connections on shutdown
    await settle.destroy()

app = FastAPI(lifespan=lifespan)

@app.post("/query")
async def query(user_id: str, prompt: str):
    try:
        await settle.wallet.debit(user_id, amount=10, description="AI Query")
    except InsufficientCreditsError as e:
        raise HTTPException(
            status_code=402,
            detail={
                "error": "insufficient_credits",
                "current_balance": e.current_balance,
                "requested": e.requested_amount,
            }
        )

    result = await run_ai_query(prompt)
    
    # Non-blocking event tracking
    settle.events.track(user_id, "AI_QUERY")
    
    return {"result": result}

Context Manager (Scripts & Cron Jobs)

from settlesettle import SettleSettle

# Context manager guarantees events are flushed and resources freed on exit
with SettleSettle() as settle:
    balance = settle.wallet.get_balance("user_123")
    print(f"Credits remaining: {balance.balance}")

Error Handling

All SDK exceptions inherit from SettleSettleError:

from settlesettle import (
    SettleSettleError,
    AuthenticationError,
    InsufficientCreditsError,
    ValidationError,
    RateLimitError,
)

try:
    settle.wallet.debit("user_123", amount=100)
except InsufficientCreditsError as e:
    # Trigger payment modal or display rewarded ad slot
    pass
except ValidationError as e:
    # Invalid request inputs
    print(f"Validation failed: {e.fields}")
except AuthenticationError:
    # Invalid API key
    pass
except RateLimitError as e:
    # Back off
    pass
except SettleSettleError as e:
    # Catch-all
    pass

Development and Testing

  1. Clone the repository and install development dependencies in editable mode:

    pip install -e ".[dev]"
    
  2. Run tests with pytest:

    pytest
    
  3. Run linting & formatting with ruff:

    ruff check settlesettle/
    ruff format settlesettle/
    
  4. Run type verification with mypy:

    mypy settlesettle/
    

License

MIT

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

settlesettle-0.1.0.tar.gz (25.1 kB view details)

Uploaded Source

Built Distribution

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

settlesettle-0.1.0-py3-none-any.whl (19.3 kB view details)

Uploaded Python 3

File details

Details for the file settlesettle-0.1.0.tar.gz.

File metadata

  • Download URL: settlesettle-0.1.0.tar.gz
  • Upload date:
  • Size: 25.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.5

File hashes

Hashes for settlesettle-0.1.0.tar.gz
Algorithm Hash digest
SHA256 2aa25368ef6aab409c7e588495aa42cb7801ad0ca57986216ed9e1be34ae9375
MD5 17890fb932dd387d5a03d311efa6d529
BLAKE2b-256 13cfe60465528bd7352a27d6dfbc5e8eca126ee88e1a21dc06ac2b4804f4ab19

See more details on using hashes here.

File details

Details for the file settlesettle-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: settlesettle-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 19.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.5

File hashes

Hashes for settlesettle-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 3717c8a10cefb64c57bbc4931f560f206189902ee201f6aafb516a58f4d79bf1
MD5 391e44eaa774323707e3fef45b61c1d5
BLAKE2b-256 f4d02c328f3d99b2e84121918f019178e980e74236501548a20979436edb2b2e

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