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.

摘自幫助中心

如果網絡撤銷了包含某筆付款的區塊,會怎樣?

區塊鏈在極少數情況下會替換其最新的區塊。如包含某筆付款的區塊被替換,該付款會回到確認中,等待確認,我們亦會在新的區塊鏈上重新尋找該付款。您的端點會收到 `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% 手續費。