Skip to main content

Python Merchant SDK for Sangria payment preflight and settlement

Project description

sangria-core

Python SDK for accepting x402 payments. Supports FastAPI.

Install

pip install sangria-core

Quick Start

FastAPI

from fastapi import FastAPI, Request
from sangria_sdk import SangriaMerchantClient
from sangria_sdk.adapters.fastapi import require_sangria_payment

app = FastAPI()
client = SangriaMerchantClient(
    base_url="https://api.sangria.net",
    api_key="sg_live_...",
)

@app.get("/premium")
@require_sangria_payment(client, amount=0.01, description="Premium content")
async def premium(request: Request):
    # request.state.sangria_payment.transaction == "0x..."
    return {"data": "premium content"}

Bypass Payments

Skip payment for certain requests. This is useful if you want to let API key users access your endpoints for free while charging anonymous or agent-based callers via x402:

@app.get("/premium")
@require_sangria_payment(
    client,
    amount=0.01,
    bypass_if=lambda req: req.headers.get("x-api-key") is not None,
)
async def premium(request: Request):
    return {"data": "premium content"}

If your bypass_if callback raises, the SDK logs the exception (via logging.getLogger("sangria_sdk"), prefixed [sangria-sdk]) and falls through to the normal payment-required flow — the request is not bypassed. This is intentional: the SDK fails closed so a crashing callback cannot silently leak free access to paid endpoints. Write callbacks defensively against missing headers, unavailable stores, etc.

How It Works

The @require_sangria_payment decorator handles the x402 negotiation loop:

  1. First request (no PAYMENT-SIGNATURE header): calls Sangria's /v1/generate-payment endpoint, returns 402 Payment Required with payment terms and a base64-encoded PAYMENT-REQUIRED response header.
  2. Retry (with PAYMENT-SIGNATURE header): forwards the signed payload to Sangria's /v1/settle-payment endpoint. On success, stores the result in request.state.sangria_payment and calls your handler.

Errors

The SDK raises a SangriaError (or subclass) when the Sangria backend is unreachable, times out, or returns a non-2xx status. Business-level payment failures (bad signature, insufficient funds) are not errors — they flow through as normal 402 responses.

SangriaError                   # base — catch-all
├── SangriaConnectionError     # DNS, refused, socket error
│   └── SangriaTimeoutError    # client-side timeout
└── SangriaAPIStatusError      # backend returned non-2xx (has .status_code, .response)

Every error carries .operation ("generate" or "settle") so you know which call failed.

from fastapi import Request
from fastapi.responses import JSONResponse
from sangria_sdk import SangriaError

@app.exception_handler(SangriaError)
async def sangria_error_handler(_request: Request, exc: SangriaError):
    return JSONResponse(
        status_code=503,
        content={"error": "Payment provider unavailable"},
    )

API Contract

POST /v1/generate-payment

Request:

{ "amount": 10000, "resource": "/premium", "description": "Premium content" }

Response (402):

{
  "x402Version": 2,
  "accepts": [{
    "scheme": "exact",
    "network": "eip155:84532",
    "amount": "10000",
    "asset": "0x036CbD53842c5426634e7929541eC2318f3dCF7e",
    "payTo": "0xWalletAddress",
    "maxTimeoutSeconds": 60
  }],
  "resource": { "url": "/premium", "description": "Premium content" }
}

POST /v1/settle-payment

Request:

{ "payment_payload": "<base64 EIP-712 signed authorization>" }

Response:

{ "success": true, "transaction": "0x...", "network": "base", "payer": "0x..." }

Requirements

  • Python >= 3.10
  • FastAPI >= 0.135.1
  • httpx >= 0.28.1

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

sangria_core-0.3.0.tar.gz (9.2 kB view details)

Uploaded Source

Built Distribution

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

sangria_core-0.3.0-py3-none-any.whl (11.4 kB view details)

Uploaded Python 3

File details

Details for the file sangria_core-0.3.0.tar.gz.

File metadata

  • Download URL: sangria_core-0.3.0.tar.gz
  • Upload date:
  • Size: 9.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.15

File hashes

Hashes for sangria_core-0.3.0.tar.gz
Algorithm Hash digest
SHA256 e5cbbd8b909a0829539d731d94575eb8cc88af4253f1edef3bc8174d64bfcb02
MD5 05197527f6e8442435db3bfd7d666ac7
BLAKE2b-256 f2e94ac55efcac769a9d4f09c57d9647212cfa9947450d2b2c534805b34eb5b0

See more details on using hashes here.

File details

Details for the file sangria_core-0.3.0-py3-none-any.whl.

File metadata

  • Download URL: sangria_core-0.3.0-py3-none-any.whl
  • Upload date:
  • Size: 11.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.15

File hashes

Hashes for sangria_core-0.3.0-py3-none-any.whl
Algorithm Hash digest
SHA256 ea4ce0fd60fbc4df7f1d090e694083c9f42a8064d5c989fd0cf0da991eba516b
MD5 2792592dbaad6b67e051dfaff763a436
BLAKE2b-256 c89a5a6a562a6025e63ac725de7a8c2e1dea78d48684f9780c0c69769ea39a09

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