# PayRam webhook signature verification in Django

> Three traps to avoid in Django: CSRF, touching request.POST first, and the trailing slash in the URL. This guide gives a tested view.

- Canonical URL: https://payramhost.com/en/docs/webhook-django/
- Other languages: 中文: https://payramhost.com/docs/webhook-django/
- Published: 2026-11-11 · Last updated: 2026-11-29
- Site: PayRamHost (independently operated; not affiliated with PayRam)

> 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 Django 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

- Django 3.2 or later (tested on Django 6.1).
- Put the project API key in the environment variable `PAYRAM_API_KEY`; do not write it into `settings.py` and commit it.
- Register an HTTPS callback address for the project in the PayRam dashboard and set it to active; see the [webhook guide](https://payramhost.com/en/docs/webhook-guide/#setup).
- With several projects, verify each with its own API key; see [multiple projects](https://payramhost.com/en/docs/multi-project-setup/).

## 2. The complete code

File: `payments/views.py`

```python
# payments/views.py
import hashlib
import hmac
import json
import os

from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST

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())


@csrf_exempt  # 回调来自 PayRam 服务器，没有 CSRF token
@require_POST
def payram_webhook(request):
    raw = request.body  # 原始字节；不要先读 request.POST，也不要重新序列化 JSON
    if not is_valid(raw, request.headers.get("X-Payram-Signature", "")):
        return HttpResponse("invalid signature", status=401)

    event = json.loads(raw)
    # 以 reference_id + status 做幂等：同一条通知可能重复到达
    handle_event(event)

    return HttpResponse("ok")  # 尽快返回 2xx，耗时的事交给任务队列


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

Register the route in `urls.py`. The callback address must match the route **exactly, including the trailing slash**:

```python
# urls.py
from django.urls import path
from payments.views import payram_webhook

urlpatterns = [
    path("payram/webhook/", payram_webhook),
]

# callback address: https://your-domain/payram/webhook/
```

## 4. Why it is written this way

- **`request.body` is the raw bytes.** Do not read `request.POST` first, and do not compute the signature from re-serialised JSON.
- **`@csrf_exempt` is essential.** The callback comes from PayRam’s servers and carries no CSRF token. Our test runs with `CsrfViewMiddleware` enabled and CSRF checks enforced to confirm the view is correctly exempt. Exempt only this view; do not turn off CSRF protection globally.
- **The trailing slash in the URL.** With the default `APPEND_SLASH`, Django redirects a request without the slash to the one with it, and a POST does not survive a redirect. Register the callback address in exactly the same form as the route.
- **Encode before comparing.** `hmac.compare_digest` raises `TypeError` on non-ASCII characters when comparing `str` values, so an attacker could make the endpoint return 500 with a non-ASCII header. Convert to bytes first and you get a 401.
- **Django REST Framework:** do not access `request.data` before you read `request.body`.

## 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](https://payramhost.com/en/docs/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](https://payramhost.com/en/docs/webhook-guide/#retry).
- **Use the status endpoint as a safety net.** If a notification is ever missed, reconcile with the [status endpoint](https://payramhost.com/en/docs/create-payment-api/).
- **Run it once with a real 1 US dollar payment.** See the [go-live checklist](https://payramhost.com/en/docs/go-live-checklist/).

## 7. FAQ

### Why do I get 403 (CSRF verification failed)?

The view is missing `@csrf_exempt`, or the decorators are in the wrong order. `@csrf_exempt` must be the outermost one (the topmost line).

### Can I use Django REST Framework?

Yes. But DRF’s `request.data` reads and parses the request stream, after which getting the raw bytes fails. Take the raw bytes from `request.body` first, verify, and parse yourself.

### How do I make sure the same notification is not handled twice?

Use `reference_id` plus `status` as a unique constraint: keep a log table with a unique index on those two fields and try to insert before handling; a failed insert means it was already handled. Details are in the [webhook guide](https://payramhost.com/en/docs/webhook-guide/#idempotent).

## Related reading

- [Webhook guide](https://payramhost.com/en/docs/webhook-guide.md): 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](https://payramhost.com/en/docs/payment-statuses.md): 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](https://payramhost.com/en/docs/create-payment-api.md): 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](https://payramhost.com/en/docs/go-live-checklist.md): 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.

- [Webhook](https://docs.payram.com/api-integration/payments-api/webhook)
- [Payment Status](https://docs.payram.com/api-integration/payments-api/payment-status)
- [Payout Webhooks](https://docs.payram.com/api-integration/payouts-apis/payout-webhooks)
