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.

ヘルプセンターより

同じイベントが、サーバーに2回届くことはありますか?

あります。どのイベントも、コンソールから、それを受け取るすべてのエンドポイントに再送でき、再送されたイベントには同じ`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.

ヘルプセンターより

支払いを含むブロックがネットワークで取り消されたら、どうなりますか?

まれに、ブロックチェーンが直近のブロックを置き換えることがあります。支払いを含むブロックでそれが起きた場合、支払いは「承認中」に戻って承認を待ち、当社が新しいチェーン上で改めてその支払いを探します。エンドポイントには`chain.reorg`が届き、支払いID、ネットワーク、自動で回復中か当社の確認が必要かが含まれます。注文の処理は署名付きの`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%です。