[data-reveal]{opacity:1!important;transform:none!important}
Webhooks and events
Payment

Webhooks and events

Verify a webhook delivery with VerifyWebhook, learn the normalised event set, and handle repeated and out-of-order events.

Every provider this interface targets settles some payments asynchronously. A backend that reads only what its own calls return can report a payment as pending twenty minutes after it succeeded. Webhooks are required here, because they are the only way to learn a terminal state.

Verifying a delivery

In an @antelopejs/interface-api controller, read all headers from the request context. In the example, handle is your application's idempotent event handler.

import { Context, HTTPResult, Post, RawBody } from "@antelopejs/interface-api";
import type { RequestContext } from "@antelopejs/interface-api";
import { VerifyWebhook, WebhookVerificationError } from "@antelopejs/interface-payment";

@Post()
async webhook(@RawBody() body: Buffer, @Context() context: RequestContext) {
  let event;
  try {
    event = await VerifyWebhook({ body, headers: context.rawRequest.headers });
  } catch (error) {
    if (error instanceof WebhookVerificationError) return new HTTPResult(403, "Unauthorized");
    throw error;
  }

  if (!event) return new HTTPResult(200, "Ignored");

  await handle(event);
  return new HTTPResult(200, "OK");
}

WebhookRequest.body has the type Uint8Array, not Buffer, so the published types of this package need no ambient Node.js types. Without that choice, a consumer that compiles without @types/node would fail inside node_modules. A Node.js Buffer is a Uint8Array, and an HTTP handler gives you a Buffer, so pass it straight through.

The body must be the raw bytes. A signature covers the bytes as sent. A body that has been through JSON.parse and serialised again does not verify, because key order and whitespace change. Use a raw body handler on this route.

Node.js gives rawRequest.headers lowercase names, and its values have the string | string[] | undefined type that WebhookRequest.headers accepts. The API interface has no @Headers() decorator.

VerifyWebhook has three distinct outcomes:

OutcomeMeaningRespond
A PaymentEventA genuine delivery this interface models200, after handling
undefinedGenuine, but not one of the modelled types200
WebhookVerificationErrorCould not be established as genuine403, act on nothing

"Genuine" is not always a signature check. Stripe, Adyen, and PayPal sign their deliveries, so verification checks the signature over the raw bytes. Mollie and Mangopay do not sign. Their delivery is a bare record identifier, and the implementation establishes it by reading that record back from the provider. On those providers, a body that names no record, or a record the provider does not confirm, raises WebhookVerificationError, just as a bad signature does on the others. Your handler is the same for both kinds of provider, and that is the reason for the design.

Where an event's fields may come from

This rule is for implementations, not for callers, and it is the easiest one to get wrong.

Every field of the returned event must come from data the implementation has authenticated. Establishing a delivery and populating an event are two steps. The first step proves different things on different providers:

StyleWhat establishing provesWhat the event may be built from
Signed (Stripe, Adyen, PayPal)The whole body is authenticThe body
Re-fetched (Mollie, Mangopay)A record with that id existsThe record read back, only

A re-fetch proves the identifier. It proves nothing about any other field in the body: not the event type, not the amount, and not the status. On a re-fetch provider, the body is a pointer and nothing else. The event's type, the kind of record, and every field of payment, refund, or dispute come from the record that the implementation read.

The failure mode is an implementation for a re-fetch provider written by analogy with a signed one, and a careful implementer can make this mistake. A Mangopay delivery carries RessourceId, EventType, and Date, and EventType maps neatly onto PaymentEvent.type. Suppose an implementation re-fetches to establish the delivery and then reads EventType from the body. It accepts an unauthenticated forgery of the payment state. Anyone who can reach the endpoint posts a real payment id with a succeeded event type. The read confirms that the id exists, and verification passes. The backend then ships goods for a payment that the provider's own record says is pending or failed.

Mollie avoids this problem by accident, not by design. Its body is only id=tr_xxx, so there is nothing else for an implementer to trust. Mangopay is the real case, and any provider added later is the general case.

The undefined outcome is the common one. Providers send dozens of event types, such as account updates, payout notifications, and report completions. If the interface threw on all of them, every implementation would reject genuine traffic, and providers answer a rejection by retrying for days. A verified but unmodelled delivery is a normal result.

The event set

"payment.pending"    "payment.authorized"  "payment.succeeded"
"payment.failed"     "payment.canceled"    "refund.succeeded"
"refund.failed"      "dispute.opened"

The payment.* types are exactly the PaymentStatus values that a backend learns asynchronously. requires_action has no event, because the call that created the payment returns it synchronously. No provider tells you later that a payer needs to authenticate.

payment.canceled covers abandonment and expiry as well as a CancelPayment you made yourself. An abandoned checkout is the most common outcome of a hosted session. Without this event, a backend keeps orders pending forever.

payment.authorized tells a backend that authorizes and then captures that the hold is in place. Without it, the authorize and capture flow would work only synchronously. On a provider that redirects first, it would not work at all.

Exactly one of payment, refund, and dispute is set, matching the type prefix. It carries the object's state at the moment the provider sent the event, which may already be stale.

Handling

import type {
  PaymentEvent,
  PaymentEventType,
} from "@antelopejs/interface-payment";

const HANDLERS: Record<PaymentEventType, (event: PaymentEvent) => unknown> = {
  "payment.succeeded": ({ payment }) =>
    payment && orders.fulfil(payment.reference),
  "payment.failed": ({ payment }) =>
    payment && orders.declined(payment.reference),
  "payment.canceled": ({ payment }) =>
    payment && orders.release(payment.reference),
  "payment.authorized": ({ payment }) =>
    payment && orders.readyToShip(payment.reference),
  "payment.pending": ({ payment }) =>
    payment && orders.awaitingSettlement(payment.reference),
  "refund.succeeded": ({ refund }) => refund && refunds.settled(refund.id),
  "refund.failed": ({ refund }) => refund && refunds.retry(refund.id),
  "dispute.opened": ({ dispute }) => dispute && disputes.open(dispute),
};

async function handle(event: PaymentEvent) {
  if (await events.seen(event.id)) return;
  await HANDLERS[event.type](event);
  await events.record(event.id);
}

Follow two rules. Production traffic breaks both if you ignore them.

De-duplicate on event.id. Providers redeliver. A delivery that your handler acknowledged can arrive again because the acknowledgement was lost. A handler that ships an order twice loses real money.

Do not assume an event is newer than what you hold. Providers deliver out of order, and a payment.pending can arrive after the payment.succeeded for the same payment. Guard on your own record's state, or read the payment again with GetPayment before you act on a backwards transition.

Disputes

dispute.opened reports that a payer has challenged a captured payment. A backend can then react: hold the goods, notify someone, or flag the account.

The interface does not model the response to a dispute. Providers differ so much in the evidence they want, its format, the deadlines, and the appeal path that an abstraction would be a thin wrapper nobody could use portably. Respond through the provider's own interface or its dashboard.