Webhooks you can trust: signatures, retries and acting once

How to check that a payment event really came from Nuxo, answer it in time, and act on it once, even when it is sent again or arrives late.

이 글은 영어로만 제공됩니다.

A sealed envelope with a lime check on its seal sliding into a server's lit slot, two fainter envelopes behind it for the earlier attempts

A webhook is how your server hears that a payment is paid, and so it is what ships the order. A forged one could ship it unpaid; one heard twice could ship it twice. Four habits make a webhook something you can act on without a second look: check the signature, answer at once, act once per event, and fulfil from the right events.

What arrives

Each delivery is a POST with a JSON body. The headers say what it is and carry its signature:

POST /webhooks/nuxo
Content-Type: application/json
X-Nuxo-Event: payment.paid
X-Nuxo-Delivery: 7c1e94b2-…-5f30
X-Nuxo-Timestamp: 1791540253
X-Nuxo-Signature: t=1791540253,v1=5f2c9e…

The body wraps the event: id is this delivery’s and stays the same through its retries; event_id is the event’s and stays the same if the event is sent again; event names it; data holds the record. Every amount in data is a string, exact to the last decimal: keep it as a string or a decimal type, never a float.

Check the signature before anything else

The signature is an HMAC-SHA256 of the timestamp, a dot and the raw body, made with your endpoint’s own secret. Work it out on your side and compare it in constant time. Three details decide whether the check holds:

  • Use the raw body, the bytes as they arrived. A body parsed and written back out is not the one that was signed.
  • Refuse an old timestamp. The timestamp is inside what is signed, so it cannot be changed; refusing one older than a few minutes stops a captured delivery from being played again. Each attempt, a retry a day later included, is signed afresh with its own time.
  • Accept any v1. While you rotate a secret, each delivery carries one signature per secret, for 7 days, so the old secret and the new one both check out.

In PHP:

<?php
// The raw body, as it arrived, and the X-Nuxo-Signature header
function nuxo_signature_ok(
    string $raw_body,
    string $header,
    string $secret
): bool {
    // No secret set: refuse all. An empty key
    // is one anyone can sign with.
    if ($secret === '') return false;
    $t = 0;
    $signatures = [];
    foreach (explode(',', $header) as $part) {
        $pair = explode('=', trim($part), 2);
        [$key, $value] = array_pad($pair, 2, '');
        if ($key === 't') $t = (int) $value;
        if ($key === 'v1') $signatures[] = $value;
    }
    // Older than 5 minutes: refuse
    if ($t === 0 || abs(time() - $t) > 300) return false;

    $signed = $t . '.' . $raw_body;
    $expected = hash_hmac('sha256', $signed, $secret);
    // One signature per secret during a rotation
    foreach ($signatures as $signature) {
        if (hash_equals($expected, $signature)) return true;
    }
    return false;
}

$raw_body = file_get_contents('php://input');
$header = $_SERVER['HTTP_X_NUXO_SIGNATURE'] ?? '';
$secret = (string) getenv('NUXO_WEBHOOK_SECRET');
if (!nuxo_signature_ok($raw_body, $header, $secret)) {
    http_response_code(400);
    exit;
}

In Python, with the raw body as bytes:

import hashlib, hmac, time

def nuxo_signature_ok(raw_body: bytes, header: str,
                      secret: str) -> bool:
    # No secret set: refuse all. An empty key
    # is one anyone can sign with.
    if not secret:
        return False
    parts = [p.strip().split("=", 1)
             for p in header.split(",") if "=" in p]
    t = next((v for k, v in parts if k == "t"), "")
    # Older than 5 minutes: refuse
    if not t.isdigit() or abs(time.time() - int(t)) > 300:
        return False
    signed = t.encode() + b"." + raw_body
    expected = hmac.new(secret.encode(), signed,
                        hashlib.sha256).hexdigest()
    # One signature per secret during a rotation
    return any(hmac.compare_digest(expected, v)
               for k, v in parts if k == "v1")

The same check in JavaScript is on the Webhooks page. Keep the secret where your keys live, never in the code: it is shown once, when you create the endpoint or rotate it.

Answer at once, work after

A delivery is done when your server answers with a 2xx. Answer within 5 seconds: store the event, answer, then do the work in a job of your own. A slower answer is still delivered but counts toward a pause, and no answer within 8 seconds is tried again.

A delivery your server does not take is sent again a minute later, then after 5 minutes, thirty, 2 hours and a day, 6 attempts in all. After ten deliveries in a row that failed or were slow, the endpoint is paused and you are told; turn it back on once it is fixed, and send again what it missed.

Act once on each event

The same event can reach you more than once: an attempt your server took but answered too late is tried again, and you can send any event again from the console. Keep the event_id of every event you act on, and when one comes back, answer 2xx and do nothing more.

도움말 센터에서

같은 이벤트가 서버에 두 번 올 수 있습니까?

네. 어떤 이벤트든 콘솔에서 그 이벤트를 받는 모든 엔드포인트로 다시 보낼 수 있으며, 같은 `event_id`로 옵니다. 따라서 `event_id`마다 한 번만 처리하세요. 언제든 엔드포인트로 서명된 테스트 이벤트를 보내 서버의 응답을 확인할 수도 있습니다.

답변 읽기

Do not count on the order either: a delivery that failed and is retried can arrive after a later event. Read what the event says the record is now, in data, rather than what it was the last time you heard. The body’s created is the time of this attempt, not of the event, so it does not order them.

Fulfil from the right events

  • Ship on the signed payment.paid, or payment.overpaid (paid, with more than asked), never on what your customer’s browser says.
  • payment.pending means the payment was seen and is waiting for its confirmations: tell your customer, do not ship yet.
  • payment.underpaid means it arrived short and nothing was credited yet.
  • Check livemode in data: test mode has endpoints of its own, but a check costs nothing.

도움말 센터에서

네트워크가 결제가 담긴 블록을 되돌리면 어떻게 됩니까?

드물지만 블록체인이 최근 블록을 다른 블록으로 대체할 수 있습니다. 결제가 담긴 블록에 그런 일이 생기면 결제는 확인을 기다리는 확인 중 상태로 돌아가고, 저희가 새 체인에서 그 결제를 다시 찾습니다. 엔드포인트에는 결제 ID, 네트워크, 그리고 저절로 복구되는 중인지 저희 검토가 필요한지가 담긴 `chain.reorg`가 전달됩니다. 주문은 서명된 `payment.paid`만 보고 처리하고, `chain.reorg`는 결제 완료였던 결제가 더 이상 완료 상태가 아니게 된 이유를 알리는 이벤트로 다루세요.

답변 읽기

Where your endpoint can be

An endpoint must be a public address over HTTPS, and redirects are not followed: point it at the final address. In test mode it can also be plain HTTP, for local development. Send it a signed test event from the console whenever you like, to see your server answer.

질문과 답변

Should I read the timestamp from the X-Nuxo-Timestamp header or from the signature?

From t= in the signature: it is the one the signature covers. X-Nuxo-Timestamp carries the same value, for your logs.

Does a test event carry an event ID?

No. A test delivery from the console has no event behind it, so it has no event_id: let your code answer it without storing anything.

직접 적용해 보기

공유 X LinkedIn

이제 직접 결제를 받아 보세요

지원하는 모든 코인과 네트워크를 한 번의 연동으로, 1% 고정 수수료에 받으세요.