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

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.1.tar.gz (25.0 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.1-py3-none-any.whl (19.2 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: settlesettle-0.1.1.tar.gz
  • Upload date:
  • Size: 25.0 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.1.tar.gz
Algorithm Hash digest
SHA256 783a3facfd113ee5391dcb609d05f9df8d9bea08c112b173139ca833043da9fd
MD5 bc0e42ad91ef2b26070af889ddae67a7
BLAKE2b-256 a4dd96a9a8bd53780099344ec95f6601a2ee2d326ad6c6d279a2923c984106db

See more details on using hashes here.

File details

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

File metadata

  • Download URL: settlesettle-0.1.1-py3-none-any.whl
  • Upload date:
  • Size: 19.2 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.1-py3-none-any.whl
Algorithm Hash digest
SHA256 0bcb1cd0fece59449f2d5400ae4998106817d308b07e724202cb5d7cd5797141
MD5 2a554f77962d5a1bcfc425ab40211991
BLAKE2b-256 6e742e26278a93e27b01900661e5631417fb53abf49d4c08c119c08469ee6535

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