@antelopejs/interface-payment 0.0.0-stage → 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +190 -0
- package/README.md +127 -2
- package/dist/antelope.test.d.ts +2 -0
- package/dist/antelope.test.js +10 -0
- package/dist/antelope.test.js.map +1 -0
- package/dist/errors.d.ts +78 -0
- package/dist/errors.js +101 -0
- package/dist/errors.js.map +1 -0
- package/dist/functions.d.ts +228 -0
- package/dist/functions.js +232 -0
- package/dist/functions.js.map +1 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +20 -0
- package/dist/index.js.map +1 -0
- package/dist/tests/payment-charges.test.d.ts +1 -0
- package/dist/tests/payment-charges.test.js +188 -0
- package/dist/tests/payment-charges.test.js.map +1 -0
- package/dist/tests/payment.test.d.ts +1 -0
- package/dist/tests/payment.test.js +115 -0
- package/dist/tests/payment.test.js.map +1 -0
- package/dist/tests/support.d.ts +63 -0
- package/dist/tests/support.js +149 -0
- package/dist/tests/support.js.map +1 -0
- package/dist/types.d.ts +388 -0
- package/dist/types.js +87 -0
- package/dist/types.js.map +1 -0
- package/docs/1.introduction.md +91 -0
- package/docs/2.payments.md +233 -0
- package/docs/3.customers-and-methods.md +133 -0
- package/docs/4.webhooks.md +170 -0
- package/docs/5.provider-capability-matrix.md +147 -0
- package/docs/tsconfig.json +14 -0
- package/package.json +79 -4
- package/skills/taking-payments/SKILL.md +232 -0
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
# Payments
|
|
2
|
+
|
|
3
|
+
Two ways to take a payment: a hosted checkout page the provider renders, or a
|
|
4
|
+
payment created directly against a method you already hold. Both produce a
|
|
5
|
+
`Payment`, and everything after creation — capture, cancel, refund, events — is
|
|
6
|
+
the same for either.
|
|
7
|
+
|
|
8
|
+
## Status
|
|
9
|
+
|
|
10
|
+
`PaymentStatus` is the normalised lifecycle. Providers report far more states
|
|
11
|
+
than this; these are the ones a backend branches on.
|
|
12
|
+
|
|
13
|
+
| Status | Meaning | What to do |
|
|
14
|
+
| ----------------- | ------------------------------------------------------------- | ------------------------------------- |
|
|
15
|
+
| `pending` | Accepted, nothing outstanding from the payer, not yet settled | Wait for a webhook |
|
|
16
|
+
| `requires_action` | The payer must be sent to `redirectUrl` | Redirect them |
|
|
17
|
+
| `authorized` | Funds held, not taken | `CapturePayment` or `CancelPayment` |
|
|
18
|
+
| `succeeded` | Captured | Deliver |
|
|
19
|
+
| `failed` | Declined, errored, or expired unpaid | Map `failure.code` to payer-safe copy |
|
|
20
|
+
| `canceled` | Voided before capture, by you or by the payer abandoning | Release the order |
|
|
21
|
+
|
|
22
|
+
`succeeded`, `failed` and `canceled` are terminal — `isTerminalPaymentStatus`
|
|
23
|
+
classifies them. The rest will change again, either because the payer acts or
|
|
24
|
+
because the provider settles.
|
|
25
|
+
|
|
26
|
+
`redirectUrl` is present exactly when the status is `requires_action`, and
|
|
27
|
+
`failure` exactly when it is `failed`. Those are invariants the conformance suite
|
|
28
|
+
checks, so you can branch on the status alone.
|
|
29
|
+
|
|
30
|
+
## Hosted checkout
|
|
31
|
+
|
|
32
|
+
The provider hosts the page, collects the method and takes the payment. This is
|
|
33
|
+
how most backends should take a one-off payment: no card data reaches your
|
|
34
|
+
servers, and the provider handles 3DS, wallets and local methods for you.
|
|
35
|
+
|
|
36
|
+
```ts
|
|
37
|
+
import {
|
|
38
|
+
CreateCheckoutSession,
|
|
39
|
+
GetCheckoutSession,
|
|
40
|
+
} from "@antelopejs/interface-payment";
|
|
41
|
+
import { randomUUID } from "node:crypto";
|
|
42
|
+
|
|
43
|
+
const idempotencyKey = randomUUID();
|
|
44
|
+
await orders.update(orderId, { idempotencyKey });
|
|
45
|
+
|
|
46
|
+
const session = await CreateCheckoutSession(
|
|
47
|
+
{
|
|
48
|
+
amount: { value: 4999, currency: "EUR" },
|
|
49
|
+
reference: orderId,
|
|
50
|
+
successUrl: `https://shop.example/orders/${orderId}/thanks`,
|
|
51
|
+
cancelUrl: `https://shop.example/orders/${orderId}/cart`,
|
|
52
|
+
description: "Order #1042",
|
|
53
|
+
},
|
|
54
|
+
idempotencyKey,
|
|
55
|
+
);
|
|
56
|
+
|
|
57
|
+
await orders.update(orderId, { sessionId: session.id });
|
|
58
|
+
response.redirect(session.redirectUrl);
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
When the payer comes back to `successUrl`, read the session:
|
|
62
|
+
|
|
63
|
+
```ts
|
|
64
|
+
const session = await GetCheckoutSession(order.sessionId);
|
|
65
|
+
if (session.payment) {
|
|
66
|
+
const payment = await GetPayment(session.payment);
|
|
67
|
+
// render payment.status
|
|
68
|
+
}
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
**The return is a prompt, not a report.** The payer's browser is not a
|
|
72
|
+
trustworthy reporter: they can navigate to `successUrl` themselves, close the tab
|
|
73
|
+
before the redirect, or lose the connection. Render what `GetCheckoutSession`
|
|
74
|
+
says, and fulfil the order from the webhook.
|
|
75
|
+
|
|
76
|
+
`CheckoutSession.payment` is absent until the provider has created a payment
|
|
77
|
+
behind the session, which for some providers is only once the payer has acted.
|
|
78
|
+
Providers whose session and payment are one object return the same identifier in
|
|
79
|
+
both fields — which is fine, because identifiers are opaque.
|
|
80
|
+
|
|
81
|
+
## Direct payments
|
|
82
|
+
|
|
83
|
+
`CreatePayment` takes a payment without a hosted page. Two uses: charging a saved
|
|
84
|
+
method with nobody present, and taking a payment through a form you host.
|
|
85
|
+
|
|
86
|
+
```ts
|
|
87
|
+
const payment = await CreatePayment(
|
|
88
|
+
{
|
|
89
|
+
amount: { value: 4999, currency: "EUR" },
|
|
90
|
+
reference: orderId,
|
|
91
|
+
paymentMethod: savedMethodId,
|
|
92
|
+
customer: customerId,
|
|
93
|
+
offSession: true,
|
|
94
|
+
},
|
|
95
|
+
idempotencyKey,
|
|
96
|
+
);
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
`offSession` says nobody can be prompted. The provider will not return
|
|
100
|
+
`requires_action`; it declines instead. Leave it unset when the payer is at the
|
|
101
|
+
keyboard, and pass a `returnUrl` so they can be sent through authentication.
|
|
102
|
+
|
|
103
|
+
### A decline is a result, not an exception
|
|
104
|
+
|
|
105
|
+
```ts
|
|
106
|
+
const payment = await CreatePayment(request, idempotencyKey);
|
|
107
|
+
|
|
108
|
+
if (payment.status === "failed") {
|
|
109
|
+
logger.warn({ failure: payment.failure }, "payment declined");
|
|
110
|
+
return render("payment-failed", {
|
|
111
|
+
reason:
|
|
112
|
+
"The payment could not be completed. Please try another payment method.",
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
`PaymentFailure.message` is for server logs, not for the payer. Use your own
|
|
118
|
+
customer-facing copy, optionally selected by `failure.code`; do not expose the
|
|
119
|
+
provider's message or `providerCode` in the response.
|
|
120
|
+
|
|
121
|
+
`CreatePayment` rejects only when the call itself could not be made — bad
|
|
122
|
+
credentials, a malformed request, an unreachable provider. A card declined by the
|
|
123
|
+
issuer is a `Payment` with status `failed` and a populated `failure`.
|
|
124
|
+
|
|
125
|
+
This is deliberate. The same decline can arrive synchronously from `CreatePayment`
|
|
126
|
+
or asynchronously as a `payment.failed` event, depending on the provider and the
|
|
127
|
+
method. Modelling one as an exception and the other as an event would mean
|
|
128
|
+
writing the handling twice and keeping the two in step. Instead both give you a
|
|
129
|
+
`Payment` with the same shape, so one function handles both.
|
|
130
|
+
|
|
131
|
+
`PaymentFailure.code` is coarse on purpose — `declined`, `insufficient_funds`,
|
|
132
|
+
`expired_card`, `incorrect_details`, `authentication_failed`, `canceled_by_payer`,
|
|
133
|
+
`expired`, `processing_error`. Providers report hundreds of decline reasons under
|
|
134
|
+
incompatible names, and a backend acts on very few of them. The provider's own
|
|
135
|
+
code travels verbatim in `providerCode` for a support ticket.
|
|
136
|
+
|
|
137
|
+
### Authentication and 3DS
|
|
138
|
+
|
|
139
|
+
There is no separate mechanism for 3DS or SCA. A payment that needs the payer to
|
|
140
|
+
authenticate comes back `requires_action` with a `redirectUrl`, which is the same
|
|
141
|
+
redirect the hosted flow uses:
|
|
142
|
+
|
|
143
|
+
```ts
|
|
144
|
+
if (payment.status === "requires_action") {
|
|
145
|
+
return response.redirect(payment.redirectUrl!);
|
|
146
|
+
}
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
Any payment can turn out to need it, which is why `returnUrl` is required unless
|
|
150
|
+
`offSession` is set.
|
|
151
|
+
|
|
152
|
+
## Authorize now, capture later
|
|
153
|
+
|
|
154
|
+
Set `authorizeOnly` to hold funds without taking them — the usual shape for
|
|
155
|
+
physical goods, where you charge on dispatch.
|
|
156
|
+
|
|
157
|
+
```ts
|
|
158
|
+
const authorized = await CreatePayment(
|
|
159
|
+
{
|
|
160
|
+
amount,
|
|
161
|
+
reference: orderId,
|
|
162
|
+
paymentMethod,
|
|
163
|
+
offSession: true,
|
|
164
|
+
authorizeOnly: true,
|
|
165
|
+
},
|
|
166
|
+
idempotencyKey,
|
|
167
|
+
);
|
|
168
|
+
// authorized.status === "authorized", authorized.amountCaptured.value === 0
|
|
169
|
+
|
|
170
|
+
const captured = await CapturePayment(authorized.id, captureKey, {
|
|
171
|
+
value: 3999,
|
|
172
|
+
currency: "EUR",
|
|
173
|
+
});
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
Omit the amount to capture everything authorized. Capturing less releases the
|
|
177
|
+
remainder: there is no second capture against the same authorization here,
|
|
178
|
+
because not every provider allows one. If you need to capture in instalments,
|
|
179
|
+
authorize per instalment.
|
|
180
|
+
|
|
181
|
+
`CancelPayment` voids an uncaptured payment and releases the hold.
|
|
182
|
+
|
|
183
|
+
Authorizations expire — after days, and by a rule that differs per provider and
|
|
184
|
+
per card network. Capture promptly, and treat an expired authorization as a
|
|
185
|
+
`payment.canceled` or `payment.failed` event rather than assuming the hold lasts.
|
|
186
|
+
|
|
187
|
+
## Refunds
|
|
188
|
+
|
|
189
|
+
```ts
|
|
190
|
+
const refund = await RefundPayment(
|
|
191
|
+
{
|
|
192
|
+
payment: payment.id,
|
|
193
|
+
amount: { value: 700, currency: "EUR" },
|
|
194
|
+
reason: "requested_by_customer",
|
|
195
|
+
},
|
|
196
|
+
idempotencyKey,
|
|
197
|
+
);
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
Omit `amount` to refund everything not yet refunded. Several partial refunds
|
|
201
|
+
against one payment are allowed, up to the captured amount; `Payment.amountRefunded`
|
|
202
|
+
tracks the running total, so the remaining refundable amount is
|
|
203
|
+
`amountCaptured.value - amountRefunded.value`.
|
|
204
|
+
|
|
205
|
+
**Refunds settle asynchronously on every provider this interface targets**, so
|
|
206
|
+
the usual result of `RefundPayment` is a `Refund` with status `pending`. The
|
|
207
|
+
terminal state arrives as a `refund.succeeded` or `refund.failed` event. Do not
|
|
208
|
+
treat the call returning as the money having moved — a refund can still fail
|
|
209
|
+
after being accepted, and a backend that credits the customer on the call alone
|
|
210
|
+
will occasionally credit them for a refund that never landed.
|
|
211
|
+
|
|
212
|
+
`RefundStatus` is `pending`, `succeeded` or `failed`. `Refund.failure` is present
|
|
213
|
+
exactly when the status is `failed`.
|
|
214
|
+
|
|
215
|
+
`RefundReason` is `duplicate`, `fraudulent`, `requested_by_customer` or `other`.
|
|
216
|
+
Providers that have no reason field take it as a note; providers that have one
|
|
217
|
+
map the first three onto it. Either way the reason is for the provider's records
|
|
218
|
+
and your own, not for the payer.
|
|
219
|
+
|
|
220
|
+
## Errors
|
|
221
|
+
|
|
222
|
+
| Error | When |
|
|
223
|
+
| --------------------------- | -------------------------------------------------------------------------------------------------------------------------- |
|
|
224
|
+
| `PaymentNotFoundError` | No record under that identifier, including one the provider cannot parse |
|
|
225
|
+
| `CustomerNotFoundError` | No customer or payment method under that identifier |
|
|
226
|
+
| `InvalidPaymentStateError` | Well-formed, but not applicable to this payment's state — capturing something not authorized, refunding more than captured |
|
|
227
|
+
| `WebhookVerificationError` | A delivery's signature does not verify |
|
|
228
|
+
| `UnsupportedOperationError` | The provider does not offer the operation at all |
|
|
229
|
+
| `PaymentError` | The base class; every error above is one |
|
|
230
|
+
|
|
231
|
+
`UnsupportedOperationError` should be rare — the feature set is chosen so a
|
|
232
|
+
typical backend never meets one. An implementation that raises it says so in its
|
|
233
|
+
README, and raises it for every call to that function, never conditionally.
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
# Customers and saved payment methods
|
|
2
|
+
|
|
3
|
+
A customer is a container the provider associates saved payment methods with.
|
|
4
|
+
Save a method once, charge it later with nobody present.
|
|
5
|
+
|
|
6
|
+
This is what makes recurring billing portable without modelling subscriptions: a
|
|
7
|
+
backend selling monthly access saves a method, runs its own billing cycle, and
|
|
8
|
+
charges off-session each period. That works on every provider here. A provider's
|
|
9
|
+
own subscription object does not — see the
|
|
10
|
+
[capability matrix](./5.provider-capability-matrix.md).
|
|
11
|
+
|
|
12
|
+
## Only the identifier round-trips
|
|
13
|
+
|
|
14
|
+
```ts
|
|
15
|
+
const customer = await CreateCustomer(
|
|
16
|
+
{ email: user.email, name: user.fullName },
|
|
17
|
+
idempotencyKey,
|
|
18
|
+
);
|
|
19
|
+
await users.update(user.id, { paymentCustomerId: customer.id });
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
Store the identifier against your own user record. **Do not read the payer's
|
|
23
|
+
details back out of the provider.** `email`, `name` and `metadata` are stored
|
|
24
|
+
only by providers that have a first-class customer object; PayPal's vault and
|
|
25
|
+
Adyen's `shopperReference` treat the identifier as a key they hang tokens on and
|
|
26
|
+
store nothing else, so `GetCustomer` there returns the identifier alone.
|
|
27
|
+
|
|
28
|
+
The conformance suite asserts the identifier round-trips and nothing more, which
|
|
29
|
+
is exactly the guarantee the contract makes. `GetCustomer` is for confirming a
|
|
30
|
+
customer still exists, not for reading a profile you did not store yourself.
|
|
31
|
+
|
|
32
|
+
## Saving a method
|
|
33
|
+
|
|
34
|
+
A method is saved as a side effect of a payment, not by a call of its own — no
|
|
35
|
+
provider here lets you vault a card without the payer presenting it.
|
|
36
|
+
`savePaymentMethod` sits on both payment paths and requires `customer` on either.
|
|
37
|
+
|
|
38
|
+
Through hosted checkout:
|
|
39
|
+
|
|
40
|
+
```ts
|
|
41
|
+
const session = await CreateCheckoutSession(
|
|
42
|
+
{
|
|
43
|
+
amount,
|
|
44
|
+
reference: orderId,
|
|
45
|
+
successUrl,
|
|
46
|
+
cancelUrl,
|
|
47
|
+
customer: user.paymentCustomerId,
|
|
48
|
+
savePaymentMethod: true,
|
|
49
|
+
},
|
|
50
|
+
idempotencyKey,
|
|
51
|
+
);
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
On a direct payment, the same flag:
|
|
55
|
+
|
|
56
|
+
```ts
|
|
57
|
+
const payment = await CreatePayment(
|
|
58
|
+
{
|
|
59
|
+
amount,
|
|
60
|
+
reference: orderId,
|
|
61
|
+
paymentMethod: presentedMethod,
|
|
62
|
+
customer: user.paymentCustomerId,
|
|
63
|
+
savePaymentMethod: true,
|
|
64
|
+
returnUrl: "https://shop.example/payment-return",
|
|
65
|
+
},
|
|
66
|
+
idempotencyKey,
|
|
67
|
+
);
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
Set `returnUrl` to your application's return route even when charging a saved
|
|
71
|
+
method on-session. If the result is `requires_action`, redirect the payer to
|
|
72
|
+
`payment.redirectUrl`, then read the payment on the server after they return.
|
|
73
|
+
|
|
74
|
+
Either way the method appears in `ListPaymentMethods` once the payment reaches
|
|
75
|
+
`succeeded` or `authorized` — not at session creation, not when the payer
|
|
76
|
+
returns, and not as soon as `CreatePayment` resolves. Settlement is
|
|
77
|
+
asynchronous; list after the payment has settled, or after the
|
|
78
|
+
`payment.succeeded` event.
|
|
79
|
+
|
|
80
|
+
## Charging off-session
|
|
81
|
+
|
|
82
|
+
```ts
|
|
83
|
+
const [method] = await ListPaymentMethods(user.paymentCustomerId);
|
|
84
|
+
if (!method) return dunning.noMethodOnFile(user);
|
|
85
|
+
|
|
86
|
+
const payment = await CreatePayment(
|
|
87
|
+
{
|
|
88
|
+
amount: { value: 999, currency: "EUR" },
|
|
89
|
+
reference: `sub-${user.id}-${period}`,
|
|
90
|
+
customer: user.paymentCustomerId,
|
|
91
|
+
paymentMethod: method.id,
|
|
92
|
+
offSession: true,
|
|
93
|
+
},
|
|
94
|
+
`renewal-${user.id}-${period}`,
|
|
95
|
+
);
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
The idempotency key is derived from the billing period, so a retried or
|
|
99
|
+
duplicated renewal job replays within the provider-defined replay window.
|
|
100
|
+
After expiration, reconcile uncertain payments before retrying: the same key
|
|
101
|
+
may create another charge.
|
|
102
|
+
|
|
103
|
+
An off-session charge can still fail — the card expired, the bank wants the payer
|
|
104
|
+
to authenticate, there is no money. It comes back `failed`, never
|
|
105
|
+
`requires_action`, because there is nobody to send anywhere. Handle it by asking
|
|
106
|
+
the payer to return and pay on-session.
|
|
107
|
+
|
|
108
|
+
## What a saved method tells you
|
|
109
|
+
|
|
110
|
+
```ts
|
|
111
|
+
export interface PaymentMethod {
|
|
112
|
+
id: string;
|
|
113
|
+
type: "card" | "wallet" | "bank_account" | "other";
|
|
114
|
+
customer: string;
|
|
115
|
+
card?: CardDetails;
|
|
116
|
+
createdAt: number;
|
|
117
|
+
}
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
`card` is present when `type` is `card`: brand, last four digits, expiry month
|
|
121
|
+
and year. Enough for a payer to recognise which card they saved, and nothing
|
|
122
|
+
more — never the PAN, and never a token you could charge outside the provider.
|
|
123
|
+
|
|
124
|
+
A PayPal vault entry is a `wallet` and carries no `card`. Branch on `type` rather
|
|
125
|
+
than assuming `card` is there.
|
|
126
|
+
|
|
127
|
+
## Removing
|
|
128
|
+
|
|
129
|
+
`DetachPaymentMethod` removes one method and leaves the customer.
|
|
130
|
+
`DeleteCustomer` removes the customer and detaches every method saved against it.
|
|
131
|
+
Payments already taken are unaffected and stay readable by their identifiers —
|
|
132
|
+
deleting a customer is not a way to erase a payment history, and refunds against
|
|
133
|
+
past payments keep working.
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
# Webhooks and events
|
|
2
|
+
|
|
3
|
+
Every provider this interface targets settles some payments asynchronously. A
|
|
4
|
+
backend that reads only what its own calls return will report a payment pending
|
|
5
|
+
that succeeded twenty minutes ago. Webhooks are not optional here — they are the
|
|
6
|
+
only way to learn a terminal state.
|
|
7
|
+
|
|
8
|
+
## Verifying a delivery
|
|
9
|
+
|
|
10
|
+
In an `@antelopejs/interface-api` controller, read all headers from the request
|
|
11
|
+
context. `handle` below is your application's idempotent event handler.
|
|
12
|
+
|
|
13
|
+
```ts
|
|
14
|
+
import { Context, HTTPResult, Post, RawBody } from "@antelopejs/interface-api";
|
|
15
|
+
import type { RequestContext } from "@antelopejs/interface-api";
|
|
16
|
+
import { VerifyWebhook, WebhookVerificationError } from "@antelopejs/interface-payment";
|
|
17
|
+
|
|
18
|
+
@Post()
|
|
19
|
+
async webhook(@RawBody() body: Buffer, @Context() context: RequestContext) {
|
|
20
|
+
let event;
|
|
21
|
+
try {
|
|
22
|
+
event = await VerifyWebhook({ body, headers: context.rawRequest.headers });
|
|
23
|
+
} catch (error) {
|
|
24
|
+
if (error instanceof WebhookVerificationError) return new HTTPResult(403, "Unauthorized");
|
|
25
|
+
throw error;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
if (!event) return new HTTPResult(200, "Ignored");
|
|
29
|
+
|
|
30
|
+
await handle(event);
|
|
31
|
+
return new HTTPResult(200, "OK");
|
|
32
|
+
}
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
`WebhookRequest.body` is typed `Uint8Array` rather than `Buffer` so this
|
|
36
|
+
package's published types carry no ambient Node dependency — a consumer
|
|
37
|
+
compiling without `@types/node` would otherwise fail inside `node_modules`. A
|
|
38
|
+
Node `Buffer` is a `Uint8Array`, and is what an HTTP handler hands you, so pass
|
|
39
|
+
it straight through.
|
|
40
|
+
|
|
41
|
+
**The body must be the raw bytes.** Signature schemes cover the bytes as sent, so
|
|
42
|
+
a body that has been through `JSON.parse` and re-serialised will not verify —
|
|
43
|
+
key order and whitespace change. Use a raw body handler on this route.
|
|
44
|
+
|
|
45
|
+
Node's `rawRequest.headers` provides lowercase names and preserves the
|
|
46
|
+
`string | string[] | undefined` values accepted by `WebhookRequest.headers`.
|
|
47
|
+
There is no `@Headers()` decorator in the API interface.
|
|
48
|
+
|
|
49
|
+
Three outcomes, and they are distinct on purpose:
|
|
50
|
+
|
|
51
|
+
| Outcome | Meaning | Respond |
|
|
52
|
+
| -------------------------- | ------------------------------------------ | ------------------- |
|
|
53
|
+
| A `PaymentEvent` | A genuine delivery this interface models | 200, after handling |
|
|
54
|
+
| `undefined` | Genuine, but not one of the modelled types | 200 |
|
|
55
|
+
| `WebhookVerificationError` | Could not be established as genuine | 403, act on nothing |
|
|
56
|
+
|
|
57
|
+
**"Genuine" is not always a signature check.** Stripe, Adyen and PayPal sign, so
|
|
58
|
+
verification is the signature over the raw bytes. Mollie and Mangopay do not
|
|
59
|
+
sign: the delivery is a bare record identifier, and the implementation
|
|
60
|
+
establishes it by reading that record back from the provider. A body naming no
|
|
61
|
+
record, or one the provider will not confirm, raises `WebhookVerificationError`
|
|
62
|
+
on those providers just as a bad signature does on the others. Your handler is
|
|
63
|
+
the same either way — which is the point.
|
|
64
|
+
|
|
65
|
+
### Where an event's fields may come from
|
|
66
|
+
|
|
67
|
+
This is the part that bites, and it is a rule for implementations rather than
|
|
68
|
+
for callers.
|
|
69
|
+
|
|
70
|
+
**Every field of the returned event must come from data the implementation has
|
|
71
|
+
authenticated.** Establishing a delivery and populating an event are two steps,
|
|
72
|
+
and the first proves different things on different providers:
|
|
73
|
+
|
|
74
|
+
| Style | What establishing proves | What the event may be built from |
|
|
75
|
+
| ------------------------------ | ---------------------------- | -------------------------------- |
|
|
76
|
+
| Signed (Stripe, Adyen, PayPal) | The whole body is authentic | The body |
|
|
77
|
+
| Re-fetched (Mollie, Mangopay) | A record with that id exists | **The record read back, only** |
|
|
78
|
+
|
|
79
|
+
A re-fetch proves the identifier. It proves nothing about any other field in the
|
|
80
|
+
body — not the event type, not the amount, not the status. So on a re-fetch
|
|
81
|
+
provider the body is a pointer and nothing else: the event's `type`, the kind of
|
|
82
|
+
record it is, and every field of `payment`, `refund` or `dispute` come from the
|
|
83
|
+
record that was read.
|
|
84
|
+
|
|
85
|
+
The failure mode is writing a re-fetch provider by analogy with a signed one,
|
|
86
|
+
which is what a careful implementer does. Mangopay's delivery carries
|
|
87
|
+
`RessourceId`, `EventType` and `Date`, and `EventType` maps neatly onto
|
|
88
|
+
`PaymentEvent.type` — so an implementation that re-fetches to establish the
|
|
89
|
+
delivery and then reads `EventType` from the body accepts an unauthenticated
|
|
90
|
+
payment-state forgery. Anyone who can reach the endpoint posts a real payment id
|
|
91
|
+
with a succeeded event type; the read confirms the id exists; verification
|
|
92
|
+
passes; the backend ships goods for a payment the provider's own record says is
|
|
93
|
+
pending or failed.
|
|
94
|
+
|
|
95
|
+
Mollie is safe here by accident rather than by design — its body is only
|
|
96
|
+
`id=tr_xxx`, so there is nothing else to trust even if an implementer wanted to.
|
|
97
|
+
Mangopay is the live case, and a provider added later is the general one.
|
|
98
|
+
|
|
99
|
+
The `undefined` case is the common one. Providers send dozens of event types —
|
|
100
|
+
account updates, payout notifications, report completions — and an interface that
|
|
101
|
+
threw on all of them would make every implementation reject genuine traffic,
|
|
102
|
+
which providers answer by retrying for days. Verified-but-unmodelled is a normal
|
|
103
|
+
result, not a problem.
|
|
104
|
+
|
|
105
|
+
## The event set
|
|
106
|
+
|
|
107
|
+
```ts
|
|
108
|
+
"payment.pending" "payment.authorized" "payment.succeeded"
|
|
109
|
+
"payment.failed" "payment.canceled" "refund.succeeded"
|
|
110
|
+
"refund.failed" "dispute.opened"
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
The `payment.*` types are exactly the `PaymentStatus` values a backend learns
|
|
114
|
+
about asynchronously. `requires_action` has no event because it is known
|
|
115
|
+
synchronously, from the call that created the payment — no provider tells you
|
|
116
|
+
later that a payer needs to authenticate.
|
|
117
|
+
|
|
118
|
+
`payment.canceled` covers abandonment and expiry, not just a `CancelPayment` you
|
|
119
|
+
made yourself. An abandoned checkout is the most common outcome of a hosted
|
|
120
|
+
session, and without this event a backend leaks orders that sit pending forever.
|
|
121
|
+
|
|
122
|
+
`payment.authorized` is what tells an auth-then-capture backend that the hold
|
|
123
|
+
landed. Without it the auth/capture flow would only work synchronously, which on
|
|
124
|
+
a redirect-first provider means not at all.
|
|
125
|
+
|
|
126
|
+
Exactly one of `payment`, `refund` and `dispute` is set, matching the type
|
|
127
|
+
prefix, and it carries the object's state at the moment the provider sent it.
|
|
128
|
+
|
|
129
|
+
## Handling
|
|
130
|
+
|
|
131
|
+
```ts
|
|
132
|
+
const HANDLERS = {
|
|
133
|
+
"payment.succeeded": (event) => orders.fulfil(event.payment!.reference),
|
|
134
|
+
"payment.failed": (event) => orders.declined(event.payment!.reference),
|
|
135
|
+
"payment.canceled": (event) => orders.release(event.payment!.reference),
|
|
136
|
+
"payment.authorized": (event) => orders.readyToShip(event.payment!.reference),
|
|
137
|
+
"payment.pending": (event) =>
|
|
138
|
+
orders.awaitingSettlement(event.payment!.reference),
|
|
139
|
+
"refund.succeeded": (event) => refunds.settled(event.refund!.id),
|
|
140
|
+
"refund.failed": (event) => refunds.retry(event.refund!.id),
|
|
141
|
+
"dispute.opened": (event) => disputes.open(event.dispute!),
|
|
142
|
+
};
|
|
143
|
+
|
|
144
|
+
async function handle(event) {
|
|
145
|
+
if (await events.seen(event.id)) return;
|
|
146
|
+
await HANDLERS[event.type]?.(event);
|
|
147
|
+
await events.record(event.id);
|
|
148
|
+
}
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
Two rules, and both bite in production:
|
|
152
|
+
|
|
153
|
+
**De-duplicate on `event.id`.** Providers redeliver. A delivery your handler
|
|
154
|
+
acknowledged can arrive again because the acknowledgement was lost, and a
|
|
155
|
+
handler that ships an order twice is a real loss.
|
|
156
|
+
|
|
157
|
+
**Do not assume an event is newer than what you hold.** Providers deliver out of
|
|
158
|
+
order, and a `payment.pending` can land after the `payment.succeeded` for the
|
|
159
|
+
same payment. Guard on your own record's state, or re-read with `GetPayment`
|
|
160
|
+
before acting on a transition backwards.
|
|
161
|
+
|
|
162
|
+
## Disputes
|
|
163
|
+
|
|
164
|
+
`dispute.opened` reports that a payer has challenged a captured payment, so a
|
|
165
|
+
backend can react — hold the goods, notify someone, flag the account.
|
|
166
|
+
|
|
167
|
+
Responding to a dispute is not modelled. The evidence a provider wants, the
|
|
168
|
+
format, the deadlines and the appeal path differ so much between them that an
|
|
169
|
+
abstraction would be a thin wrapper nobody could use portably. Respond through
|
|
170
|
+
the provider's own interface or its dashboard.
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
# Provider capability matrix
|
|
2
|
+
|
|
3
|
+
This interface is not the lowest common denominator, and it is not Stripe with
|
|
4
|
+
the names changed. It is the set of flows a typical backend needs where all four
|
|
5
|
+
provider families can plausibly implement each one.
|
|
6
|
+
|
|
7
|
+
The bar: a backend on this interface can change provider. An implementation may
|
|
8
|
+
decline a flow and throw `UnsupportedOperationError`, but the feature set is
|
|
9
|
+
chosen so that declining is uncommon.
|
|
10
|
+
|
|
11
|
+
Only Stripe is implemented in the AntelopeJS ecosystem today. The other three
|
|
12
|
+
families are paper constraints on the shape — each was checked against its public
|
|
13
|
+
API before a proxy was added, and full coverage is expected of none of them.
|
|
14
|
+
|
|
15
|
+
## The four families
|
|
16
|
+
|
|
17
|
+
| Family | Model | What it pulls the design towards |
|
|
18
|
+
| ------------------------ | ---------------------------------------------------------- | --------------------------------------------------------------------------- |
|
|
19
|
+
| **Stripe** | Intent-based | The reference for the feature set |
|
|
20
|
+
| **PayPal** | Order-based, not intent-based; different capture semantics | The strongest test of whether the abstraction is real |
|
|
21
|
+
| **Adyen / Checkout.com** | Closest to Stripe | `shopperReference`-style recurring rather than first-class customer objects |
|
|
22
|
+
| **Mollie / Mangopay** | Lighter, redirect-first | Mangopay is wallet-based and the likeliest to decline a flow |
|
|
23
|
+
|
|
24
|
+
## What is in, and what each family does behind it
|
|
25
|
+
|
|
26
|
+
✅ native · ⚠️ implementable with work · ❌ would have to decline
|
|
27
|
+
|
|
28
|
+
| Contract | Stripe | PayPal | Adyen | Mollie | Mangopay |
|
|
29
|
+
| ---------------------------------- | --------------------------- | ------------------------- | ------------------------- | ------------------------------- | --------------------- |
|
|
30
|
+
| `CreateCheckoutSession` | ✅ Checkout Session | ✅ Orders + approve link | ✅ Sessions | ✅ Payments (`_links.checkout`) | ✅ Web PayIn |
|
|
31
|
+
| `GetCheckoutSession` | ✅ retrieve | ✅ get order | ✅ payment details | ✅ get payment | ✅ get PayIn |
|
|
32
|
+
| `CreatePayment` (on-session) | ✅ PaymentIntent | ✅ Order + capture | ✅ `/payments` | ✅ Payments | ✅ Direct PayIn |
|
|
33
|
+
| `CreatePayment` (off-session) | ✅ `off_session` | ✅ vault token | ✅ ContAuth | ✅ `sequenceType: recurring` | ✅ recurring PayIn |
|
|
34
|
+
| `authorizeOnly` + `CapturePayment` | ✅ `capture_method: manual` | ✅ authorize then capture | ✅ manual capture | ✅ authorize + capture | ⚠️ PreAuthorization |
|
|
35
|
+
| Partial capture | ✅ | ✅ | ✅ | ✅ | ⚠️ lower-amount PayIn |
|
|
36
|
+
| `CancelPayment` | ✅ cancel | ✅ void | ✅ `/cancels` | ✅ cancel | ✅ cancel PreAuth |
|
|
37
|
+
| `RefundPayment` full + partial | ✅ | ✅ | ✅ | ✅ | ✅ |
|
|
38
|
+
| `GetRefund` | ✅ | ✅ | ⚠️ read from notification | ✅ | ✅ |
|
|
39
|
+
| `CreateCustomer` | ✅ Customers | ⚠️ identifier only | ⚠️ `shopperReference` | ✅ Customers | ✅ Users |
|
|
40
|
+
| `GetCustomer` | ✅ | ⚠️ identifier only | ⚠️ identifier only | ✅ | ✅ |
|
|
41
|
+
| `ListPaymentMethods` | ✅ PaymentMethods | ✅ Vault tokens | ✅ stored methods | ✅ Mandates | ✅ Cards |
|
|
42
|
+
| `DetachPaymentMethod` | ✅ detach | ✅ delete token | ✅ disable | ✅ revoke mandate | ✅ deactivate |
|
|
43
|
+
| `DeleteCustomer` | ✅ | ⚠️ detach all tokens | ⚠️ disable all | ✅ | ⚠️ deactivate user |
|
|
44
|
+
| `VerifyWebhook` | ✅ signed | ✅ verify-signature call | ✅ HMAC | ⚠️ unsigned; re-fetch | ⚠️ re-fetch |
|
|
45
|
+
|
|
46
|
+
Nothing in the contract is ❌ for any family. That is the test the feature set was
|
|
47
|
+
chosen to pass.
|
|
48
|
+
|
|
49
|
+
## The two places the contract bent to fit
|
|
50
|
+
|
|
51
|
+
These are design changes made _because_ of the four-family audit, not despite it.
|
|
52
|
+
|
|
53
|
+
### Customers are an identifier, not a profile
|
|
54
|
+
|
|
55
|
+
PayPal and Adyen have no first-class customer object. PayPal's vault hangs tokens
|
|
56
|
+
off a `customer_id` you mint yourself; Adyen's `shopperReference` is a string you
|
|
57
|
+
choose. Neither stores an email or a name you can read back.
|
|
58
|
+
|
|
59
|
+
Modelling `Customer` as a record with retrievable attributes would have made two
|
|
60
|
+
of five implementations return a mostly-empty object and quietly break backends
|
|
61
|
+
that read `customer.email`. So `Customer` guarantees the identifier and nothing
|
|
62
|
+
else, `email` and `name` are documented as write-where-supported, and the
|
|
63
|
+
conformance suite asserts only that the identifier round-trips.
|
|
64
|
+
|
|
65
|
+
What a customer _is_ here is a container for saved payment methods — which is
|
|
66
|
+
exactly what `shopperReference` is. The flow survives the audit; the data model
|
|
67
|
+
had to shrink to survive it.
|
|
68
|
+
|
|
69
|
+
### Unsigned webhooks still verify
|
|
70
|
+
|
|
71
|
+
Mollie does not sign webhooks. The delivery is a payment identifier and nothing
|
|
72
|
+
else, and the documented way to trust it is to call the API and read the current
|
|
73
|
+
state. Mangopay is similar.
|
|
74
|
+
|
|
75
|
+
`VerifyWebhook` is therefore specified by its _outcome_ — a normalised event you
|
|
76
|
+
can trust — rather than as a signature check. A Mollie implementation fetches the
|
|
77
|
+
payment inside `VerifyWebhook` and returns a full event; a Stripe implementation
|
|
78
|
+
checks the HMAC and reads the body. Both satisfy the same contract, and a backend
|
|
79
|
+
writes one handler.
|
|
80
|
+
|
|
81
|
+
Had the contract been `VerifyWebhookSignature(body, signature) => boolean`,
|
|
82
|
+
Mollie would have had to decline it.
|
|
83
|
+
|
|
84
|
+
The residual risk in this bend is that establishing a delivery and populating an
|
|
85
|
+
event prove different things. A signature authenticates the whole body; a
|
|
86
|
+
re-fetch authenticates one record and says nothing about the rest of the body.
|
|
87
|
+
The contract therefore requires that on a re-fetch provider every field of the
|
|
88
|
+
event comes from the record read back, and that the body is treated as a pointer
|
|
89
|
+
only — see [Webhooks](./4.webhooks.md). Without that rule, a Mangopay module
|
|
90
|
+
written by analogy with the Stripe one accepts a forged payment state.
|
|
91
|
+
|
|
92
|
+
This rule is **specified but not enforced by the conformance suite**: forging a
|
|
93
|
+
delivery is not portable across providers, and the suite has no endpoint to
|
|
94
|
+
receive a genuine one at, so `VerifyWebhook`'s success path is untested
|
|
95
|
+
altogether. It is held by review of each implementation.
|
|
96
|
+
|
|
97
|
+
## What is out, and why
|
|
98
|
+
|
|
99
|
+
### Subscriptions, invoicing, proration, dunning, tax, coupons
|
|
100
|
+
|
|
101
|
+
The largest single judgement call. Provider subscription objects diverge more
|
|
102
|
+
than any other area: billing anchors, proration arithmetic, trial handling,
|
|
103
|
+
dunning schedules and tax engines are all different, and several families have no
|
|
104
|
+
equivalent at all. An interface over them would be one most implementations
|
|
105
|
+
decline.
|
|
106
|
+
|
|
107
|
+
What _is_ portable is the mechanism underneath: save a payment method, charge it
|
|
108
|
+
off-session on your own schedule. A backend selling recurring access runs its own
|
|
109
|
+
cycle on `ListPaymentMethods` + `CreatePayment`, and that works on all five.
|
|
110
|
+
Filed as a follow-up rather than dropped — if a portable subset emerges, it would
|
|
111
|
+
build on saved methods rather than on provider subscription objects.
|
|
112
|
+
|
|
113
|
+
### Marketplace and split payments
|
|
114
|
+
|
|
115
|
+
Stripe Connect, PayPal Commerce Platform, Adyen for Platforms and Mangopay's
|
|
116
|
+
wallets are incompatible models, not different spellings of one. Connect splits a
|
|
117
|
+
charge; Mangopay moves money between wallets it holds; PayPal routes to
|
|
118
|
+
merchants. A backend doing this is deep in one provider's model and should use
|
|
119
|
+
that provider's own interface.
|
|
120
|
+
|
|
121
|
+
### Dispute management
|
|
122
|
+
|
|
123
|
+
An event, not an API. Evidence formats, deadlines and appeal paths differ so much
|
|
124
|
+
that a portable submission call would be a wrapper nobody could use. `dispute.opened`
|
|
125
|
+
tells a backend to react; responding goes through the provider.
|
|
126
|
+
|
|
127
|
+
### Payment links and in-person terminals
|
|
128
|
+
|
|
129
|
+
Payment links are a dashboard feature more than an API one, and terminal
|
|
130
|
+
integrations are hardware-bound and provider-specific.
|
|
131
|
+
|
|
132
|
+
## How this is kept honest
|
|
133
|
+
|
|
134
|
+
`src/tests/payment.test.ts` ships in the package and runs against whichever
|
|
135
|
+
provider module is wired in. It is written against the contract, not against
|
|
136
|
+
Stripe's behaviour, and it is what the second provider will be held to.
|
|
137
|
+
|
|
138
|
+
Most of it needs no fixture and cannot pass without touching a live provider:
|
|
139
|
+
session creation, customer lifecycle, idempotency replay, unknown-identifier
|
|
140
|
+
errors, webhook signature rejection.
|
|
141
|
+
|
|
142
|
+
The charge tests need a chargeable test payment method, which has no portable way
|
|
143
|
+
to mint — a card is entered by a payer, and every provider publishes its own test
|
|
144
|
+
token instead. The provider module supplies one through
|
|
145
|
+
`ANTELOPE_PAYMENT_TEST_METHOD`, and those tests skip, visibly and by name, when
|
|
146
|
+
it is absent. That is test _data_ supplied at the boundary, not a stub standing
|
|
147
|
+
in for provider behaviour.
|