Payments
There are two ways to take a payment. The provider can render a hosted checkout
page, or you can create a payment directly against a method you already hold.
Both produce a Payment. Everything after creation is the same for either path:
capture, cancel, refund, and events.
Status
PaymentStatus is the normalised lifecycle. Providers report far more states
than these six. These are the ones a backend branches on.
| Status | Meaning | What to do |
|---|---|---|
pending | Accepted, nothing outstanding from the payer, not yet settled | Wait for a webhook |
requires_action | The payer must be sent to redirectUrl | Redirect them |
authorized | Funds held, not taken | CapturePayment or CancelPayment |
succeeded | Captured | Deliver |
failed | Declined, errored, or expired unpaid | Map failure.code to payer-safe copy |
canceled | Voided before capture, by you or by the payer abandoning | Release the order |
succeeded, failed, and canceled are terminal, and isTerminalPaymentStatus
returns true for them. The other statuses change again, when the payer acts or
when the provider settles.
redirectUrl is present exactly when the status is requires_action, and
failure exactly when it is failed. The conformance suite checks both
invariants, so you can branch on the status alone.
Hosted checkout
The provider hosts the page, collects the method, and takes the payment. Use hosted checkout for most one-off payments. No card data reaches your servers, and the provider handles 3DS, wallets, and local methods.
import {
CreateCheckoutSession,
GetCheckoutSession,
} from "@antelopejs/interface-payment";
import { randomUUID } from "node:crypto";
const idempotencyKey = randomUUID();
await orders.update(orderId, { idempotencyKey });
const session = await CreateCheckoutSession(
{
amount: { value: 4999, currency: "EUR" },
reference: orderId,
successUrl: `https://shop.example/orders/${orderId}/thanks`,
cancelUrl: `https://shop.example/orders/${orderId}/cart`,
description: "Order #1042",
},
idempotencyKey,
);
await orders.update(orderId, { sessionId: session.id });
response.redirect(session.redirectUrl);
To set the language of the hosted page, pass locale, one of the
PAYMENT_LOCALES values. auto lets the provider pick from the payer's browser.
A provider without a matching language falls back to its own default.
When the payer comes back to successUrl, read the session:
import { GetCheckoutSession, GetPayment } from "@antelopejs/interface-payment";
export async function readOrderPayment(order: { sessionId: string }) {
const session = await GetCheckoutSession(order.sessionId);
if (session.payment) {
const payment = await GetPayment(session.payment);
// render payment.status
}
}
The return is a prompt, not a report. The payer's browser does not report the
outcome reliably. The payer can open successUrl directly, close the tab before
the redirect, or lose the connection. Render what GetCheckoutSession returns,
and fulfil the order from the webhook.
CheckoutSession.payment is absent until the provider has created a payment
behind the session. For some providers, that happens only after the payer has
acted. A provider whose session and payment are one object returns the same
identifier in both fields. Identifiers are opaque, so that causes no problem.
Direct payments
CreatePayment takes a payment without a hosted page. It has two uses: charging
a saved method with nobody present, and taking a payment through a form you host.
import { CreatePayment } from "@antelopejs/interface-payment";
export async function chargeSavedMethod(
orderId: string,
savedMethodId: string,
customerId: string,
idempotencyKey: string,
) {
const payment = await CreatePayment(
{
amount: { value: 4999, currency: "EUR" },
reference: orderId,
paymentMethod: savedMethodId,
customer: customerId,
offSession: true,
},
idempotencyKey,
);
return payment;
}
offSession says that nobody can be prompted. The provider does not return
requires_action. It declines instead. Leave offSession unset when the payer is
present, and pass a returnUrl so the provider can send them through
authentication.
A decline is a result, not an exception
const payment = await CreatePayment(request, idempotencyKey);
if (payment.status === "failed") {
logger.warn({ failure: payment.failure }, "payment declined");
return render("payment-failed", {
reason:
"The payment could not be completed. Please try another payment method.",
});
}
PaymentFailure.message is for server logs, not for the payer. Show your own
copy to the payer, optionally selected by failure.code. Do not expose the
provider's message or providerCode in the response.
CreatePayment rejects only when the call itself could not be made, for example
because of bad credentials, a malformed request, or an unreachable provider. A
card that the issuer declines is a Payment with status failed and a populated
failure.
The interface does this on purpose. The same decline can arrive synchronously
from CreatePayment or asynchronously as a payment.failed event, depending on
the provider and the method. If one were an exception and the other an event,
you would write the handling twice and keep the two copies in step. Both give
you a Payment with the same shape instead, so one function handles both.
PaymentFailure.code is coarse on purpose. Its values are declined,
insufficient_funds, expired_card, incorrect_details,
authentication_failed, canceled_by_payer, expired, and processing_error.
Providers report hundreds of decline reasons under incompatible names, and a
backend acts on very few of them. The provider's own code travels verbatim in
providerCode, for a support ticket.
Payer authentication
There is no separate mechanism for 3DS or SCA. A payment that needs the payer to
authenticate comes back requires_action with a redirectUrl. The hosted flow
uses the same redirect:
if (payment.status === "requires_action" && payment.redirectUrl) {
return response.redirect(payment.redirectUrl);
}
Any payment can turn out to need authentication. For that reason returnUrl is
required unless offSession is set.
Authorize now, capture later
To hold funds without taking them, set authorizeOnly. Physical goods usually
work this way, with the charge taken on dispatch.
import {
CapturePayment,
CreatePayment,
type Amount,
} from "@antelopejs/interface-payment";
export async function authorizeThenCapture(
amount: Amount,
orderId: string,
paymentMethod: string,
idempotencyKey: string,
captureKey: string,
) {
const authorized = await CreatePayment(
{
amount,
reference: orderId,
paymentMethod,
offSession: true,
authorizeOnly: true,
},
idempotencyKey,
);
// authorized.status === "authorized", authorized.amountCaptured.value === 0
const captured = await CapturePayment(authorized.id, captureKey, {
value: 3999,
currency: "EUR",
});
return captured;
}
Omit the amount to capture everything authorized. Capturing less releases the remainder. The interface allows one capture per authorization, because not every provider allows a second one. To capture in instalments, authorize each instalment separately.
CapturePayment throws InvalidPaymentStateError when the payment is not
authorized or the amount exceeds what was authorized.
CancelPayment voids an uncaptured payment and releases the hold. It throws
InvalidPaymentStateError when the payment was already captured or reached
another terminal status.
Authorizations expire after some days, by a rule that differs per provider and
per card network. Capture promptly. Expect an expired authorization to arrive as
a payment.canceled or payment.failed event, and do not assume the hold lasts.
Refunds
import { RefundPayment, type Payment } from "@antelopejs/interface-payment";
export async function refundPart(payment: Payment, idempotencyKey: string) {
const refund = await RefundPayment(
{
payment: payment.id,
amount: { value: 700, currency: "EUR" },
reason: "requested_by_customer",
},
idempotencyKey,
);
return refund;
}
Omit amount to refund everything not yet refunded. The amount must be in the
payment's currency. You can make several partial refunds against one payment, up
to the captured amount. Payment.amountRefunded tracks the running total, so the
remaining refundable amount is amountCaptured.value - amountRefunded.value.
Refunding more than that throws InvalidPaymentStateError.
Refunds settle asynchronously on every provider this interface targets. The
usual result of RefundPayment is a Refund with status pending. The terminal
state arrives as a refund.succeeded or refund.failed event. Do not treat the
returned call as money that has moved. A refund can still fail after the provider
accepts it. A backend that credits the customer on the call alone sometimes
credits them for a refund that never landed.
RefundStatus is pending, succeeded, or failed. Refund.failure is present
exactly when the status is failed.
RefundReason is duplicate, fraudulent, requested_by_customer, or other.
A provider with no reason field takes it as a note. A provider with a reason field
maps the first three values onto it. Either way, the reason is for the provider's
records and your own, not for the payer.
Errors
| Error | When |
|---|---|
PaymentNotFoundError | No payment, refund, or checkout session under that identifier, including an identifier the provider cannot parse |
CustomerNotFoundError | No customer or payment method under that identifier, including an identifier the provider cannot parse |
InvalidPaymentStateError | Well-formed, but not applicable to the payment's state, such as capturing a payment that is not authorized or over-refunding |
WebhookVerificationError | A webhook delivery cannot be established as genuine |
UnsupportedOperationError | The implementation does not offer the operation at all |
PaymentError | The base class. Every error above extends it |
Every error has an optional providerCode, the provider's own error code,
verbatim and opaque. InvalidPaymentStateError also has an optional status,
the status the payment was actually in. UnsupportedOperationError has
operation, the name of the unavailable function.
UnsupportedOperationError is rare. The feature set is chosen so that a typical
backend never meets it. An implementation that raises it says so in its README,
and raises it for every call to that function, never conditionally.