PayRamHost hosted onboarding is paused · Guides keep updatingGet notified when it reopens →

Docs / FastAPI example

PayRam webhook signature verification in FastAPI

FastAPI parses the request body before your function runs. This guide shows how to verify the signature first.

Last updated · By the PayRamHost editors · Markdown version

PayRamHost hosted merchant onboarding has been paused since 29 November 2026. Where this guide mentions PayRamHost, it describes the situation before the pause; the PayRam usage it explains still applies.

The short version: a PayRam webhook signature is an HMAC-SHA256 of the raw request body, keyed with your project API key, sent in the header X-Payram-Signature: sha256=<hex>. In FastAPI the key is to get the raw bytes untouched by the framework and compute the signature over them. Below is a complete, tested version.

1. Before you start

  • Python 3.9 or later with FastAPI and uvicorn installed (tested on FastAPI 0.162).
  • Put the project API key in the environment variable PAYRAM_API_KEY.
  • Register an HTTPS callback address for the project in the PayRam dashboard and set it to active; see the webhook guide.
  • With several projects, verify each with its own API key; see multiple projects.

2. The complete code

File: main.py

# main.py
import hashlib
import hmac
import json
import os

from fastapi import BackgroundTasks, FastAPI, Header, HTTPException, Request, Response

app = FastAPI()
API_KEY = os.environ["PAYRAM_API_KEY"].encode()  # 项目 API 密钥,只放在环境变量里


def is_valid(raw: bytes, header: str) -> bool:
    expected = "sha256=" + hmac.new(API_KEY, raw, hashlib.sha256).hexdigest()
    # 两边都转成 bytes 再比较:str 里有非 ASCII 字符时 compare_digest 会抛 TypeError
    return hmac.compare_digest(header.encode(), expected.encode())


# 注意:这里不要声明 Pydantic 请求体参数。FastAPI 会在进入函数前先解析并校验 JSON,
# 一旦字段对不上就直接返回 422,签名都没机会校验。先验签,再自己解析。
@app.post("/payram/webhook")
async def payram_webhook(
    request: Request,
    background: BackgroundTasks,
    x_payram_signature: str = Header(default=""),  # 对应请求头 X-Payram-Signature
):
    raw = await request.body()  # 原始字节,不要重新序列化
    if not is_valid(raw, x_payram_signature):
        raise HTTPException(status_code=401, detail="invalid signature")

    event = json.loads(raw)
    # 以 reference_id + status 做幂等:同一条通知可能重复到达
    background.add_task(handle_event, event)  # 先返回 2xx,再在后台处理

    return Response(status_code=200)


def handle_event(event: dict) -> None:
    # TODO:查你自己的订单(invoice_id),状态是 FILLED 或 OVER_FILLED 才发货
    pass

The code in this guide was tested locally before publishing: test cases cover a valid signature, a tampered body, re-serialised JSON, a missing signature, a short signature, a wrong key and more, and we confirmed that the openssl command below produces the same signature as the code.

3. Setup and routing

Save as main.py and start the server. The callback address is https://your-domain/payram/webhook:

PAYRAM_API_KEY=your-project-api-key uvicorn main:app --port 8000

4. Why it is written this way

  • Do not declare a Pydantic body parameter. FastAPI parses and validates the JSON before your function runs and returns 422 if the fields do not match, so the signature never gets a chance to be checked. Verify first, then parse with json.loads yourself.
  • Get the raw bytes with await request.body(). Do not serialise the result of await request.json().
  • Header(default="") maps to X-Payram-Signature automatically. Underscores in the parameter name become hyphens.
  • Encode before comparing. The reason is the same as for Django: hmac.compare_digest raises TypeError on non-ASCII characters when comparing str values.
  • BackgroundTasks. Return 200 first and process afterwards; for anything long, still use a task queue.

5. Testing locally

The command below computes the correct signature with your key and sends a simulated callback to your local server. It should return 200; change any one character in BODY and send it again, and it should return 401. Use the key of a separate test project, not a production one.

export PAYRAM_API_KEY='your test project API key'
BODY='{"reference_id":"a1b2c3d4e5","invoice_id":"INV-0090","status":"FILLED"}'
SIG="sha256=$(printf '%s' "$BODY" | openssl dgst -sha256 -hmac "$PAYRAM_API_KEY" -hex | sed 's/^.* //')"
curl -i -X POST http://localhost:8000/payram/webhook \
  -H "Content-Type: application/json" \
  -H "X-Payram-Signature: $SIG" \
  -d "$BODY"

6. What to add before going live

  • Idempotency. The same notification can arrive twice. Use reference_id plus status as a unique key and answer 200 straight away if it was already handled.
  • Ship only after receipt. Ship only on FILLED or OVER_FILLED; see payment statuses.
  • Return 2xx first, then process. PayRam retries requests answered with 400 or above, or with no response within 60 seconds; the rules are in the webhook guide.
  • Use the status endpoint as a safety net. If a notification is ever missed, reconcile with the status endpoint.
  • Run it once with a real 1 US dollar payment. See the go-live checklist.

7. FAQ

Why did I get 422 Unprocessable Entity?

Your function declares a Pydantic model as the body, so FastAPI validated the JSON before the signature was checked. Remove the model parameter and use await request.body().

Can I use a plain synchronous def?

You can, but the simplest way to get the raw bytes is async def with await request.body().

How do I test it locally?

Use the curl command above, which computes the correct signature; change one character in the body and send it again, and you should get 401.

  • Webhook guide: How to receive PayRam webhooks: register an endpoint, verify X-Payram-Signature, understand retry rules and payment states, handle duplicates, with Node.js and Python examples.
  • Payment statuses: What PayRam's five payment statuses mean, how to handle underpaid (PARTIALLY_FILLED), overpaid (OVER_FILLED) and expired (CANCELLED) payments, and how to keep your order status in sync using webhooks and the status endpoint.
  • Create payments via API: Add crypto payments to your own site with the PayRam API: create a payment and get a payment link, send the customer to the payment page, confirm receipt with webhooks and the status endpoint, and reconcile by order number. With curl, Node.js and Python examples.
  • Go-live checklist: PayRam mainnet has no sandbox, so test with small real amounts before launch. This checklist covers, in order: checking the configuration, one payment per chain and coin, verifying sweeping, under- and overpayment and expiry, webhooks, refunds and payouts, the card channel, and where to look when something fails.

Sources

This guide is based on the PayRam official documentation below, checked on 2026-11-12. PayRamHost is an independently operated service and is not affiliated with PayRam. If anything differs, the official documentation prevails.