---
title: Accept crypto in a Python service
description: Integrate GaaPay from Python: sign requests with hmac/hashlib, create orders in FastAPI, and verify webhook signatures with compare_digest before delivering.
url: https://gaapay.com/integrations/python
updated: 2026-12-04
language: en
type: guide
---

# Accept crypto in a Python service

> Python’s standard library covers signing (`hmac`, `hashlib`) and constant-time comparison (`hmac.compare_digest`). The only tricky part is reading the raw request body in FastAPI before any JSON parsing.

There is no official Python SDK and no wheel to trust: the signing contract is small enough to implement in a file you can read. This guide uses FastAPI, but the same functions work in Flask or Django.

## 1 · Sign and create

```py
import hashlib, hmac, json, os, time, uuid
import httpx

API = "https://api.gaapay.com"

def headers(method: str, path: str, raw: str) -> dict:
    ts, nonce = str(int(time.time())), str(uuid.uuid4())
    payload = f"{ts}\n{nonce}\n{method}\n{path}\n{raw}"
    sig = hmac.new(os.environ["GAAPAY_SECRET"].encode(),
                   payload.encode(), hashlib.sha256).hexdigest()
    return {
        "x-gaapay-app": os.environ["GAAPAY_APP"],
        "x-gaapay-timestamp": ts,
        "x-gaapay-nonce": nonce,
        "x-gaapay-signature": sig,
    }

async def create_order(amount: str, ref: str):
    path = "/api/v1/orders"
    raw = json.dumps({"amount": amount, "merchant_order_ref": ref}, separators=(",", ":"))
    async with httpx.AsyncClient() as client:
        r = await client.post(API + path, content=raw,
                              headers={**headers("POST", path, raw),
                                       "content-type": "application/json"})
        r.raise_for_status()
        return r.json()
```

> **Compact JSON:** — Use the same separators you signed. Python’s default `json.dumps` adds spaces; `separators=(",", ":")` keeps the bytes stable and matches what most HTTP clients send.

## 2 · Verify the webhook

```py
from fastapi import FastAPI, Request, HTTPException
import hashlib, hmac, json

app = FastAPI()
SECRET = os.environ["GAAPAY_WEBHOOK_SECRET"].encode()

@app.post("/webhooks/gaapay")
async def gaapay_webhook(request: Request):
    raw = await request.body()          # bytes, before any parsing
    ts = request.headers["x-gaapay-timestamp"]
    signature = request.headers["x-gaapay-signature"].removeprefix("v1=")
    expected = hmac.new(SECRET, f"{ts}.".encode() + raw, hashlib.sha256).hexdigest()
    if not hmac.compare_digest(expected, signature):
        raise HTTPException(401, "bad signature")
    event = json.loads(raw)
    if event["type"] == "payment.succeeded":
        await fulfil(event["data"]["order_id"])
    return {"ok": True}
```

## Python-specific pitfalls

- `await request.body()` must run before any middleware parses JSON, or the signature will not match.
- `hmac.compare_digest` exists for a reason: `==` on strings is not constant-time.
- Do not use `Decimal` formatting that strips trailing zeros when sending `amount`: send the exact string you display.
- If you run `uvicorn` behind nginx, keep the body untouched — request-body rewriting breaks HMAC.

## Python questions

### Is there an async SDK?

No. `httpx` plus the two functions above is the integration; fewer moving parts, no version pinning.

### Flask instead of FastAPI?

Use `request.get_data(cache=False)` to capture raw bytes, then the same `hmac.compare_digest` check.

### How do I test without real money?

Use sandbox keys (`sk_test_`). The sandbox simulates success, underpay and late payment; the signature flow is identical.

[Open the console](/console) — **Copy the sandbox keys**: The sandbox is the default. Create an app, create an order, watch a webhook arrive — then flip one environment variable.

## Related

- https://gaapay.com/docs/auth
- https://gaapay.com/docs/verify
- https://gaapay.com/integrations/node
- https://gaapay.com/docs/api
