@appweaver/skill 3.0.0 → 3.1.0

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.
@@ -0,0 +1,795 @@
1
+ # Payments
2
+
3
+ `@appweaver/payments` takes online payments through payment gateways: one-time payments confirmed by the client or
4
+ charged to a saved payment method, hosted checkout pages, authorizations captured later, refunds, saved payment
5
+ methods, recurring payments (plans, subscriptions, invoices), the signed webhooks of the gateways, and the emails of
6
+ the payments. The `stripe` driver of `@appweaver/stripe` reaches Stripe with the official `stripe` SDK. Several
7
+ gateways are usable at once, i.e. one Stripe account per legal entity, selected by the country or the currency of a
8
+ payment.
9
+
10
+ ```sh
11
+ weaver module add payments # or: npm install @appweaver/payments @appweaver/stripe
12
+ weaver generate # the models of the module join the Prisma schema
13
+ weaver migration new add_payments
14
+ ```
15
+
16
+ `weaver module add payments` ends with these two steps as its `Next steps`.
17
+
18
+ The module requires `@appweaver/data`, uses the `Queue` (the `payments` queue, so install `@appweaver/bullmq` in
19
+ production: the jobs of the `memory` queue are lost on a restart, and delivered again a minute later by a maintenance
20
+ job) and, for its routes and webhooks, `@appweaver/web`. It works without a server, i.e. in a worker.
21
+
22
+ How the money moves safely:
23
+
24
+ - **No card data on the server.** The client confirms a payment with the library of the gateway (Stripe.js, the
25
+ mobile SDKs) or on its hosted page. The application sees a payment method only as its brand, last four digits and
26
+ expiry.
27
+ - **The amount is set by the server.** No route of the module takes an amount from a client: the application calls
28
+ `createPayment` with the amount it computed from its own records, an order or a cart.
29
+ - **Integer minor units.** An amount is an integer of the minor units of its currency (`1999` for 19.99 USD, `500`
30
+ for 500 JPY), stored in `BigInt` columns, never a float.
31
+ - **The gateway is the source of truth.** A record only moves with what its gateway reports: the answer of a call, a
32
+ webhook, or the reconciliation. A redirect back to the application never marks a payment as paid.
33
+ - **Idempotent writes.** Every write to a gateway carries an idempotency key derived from its record, and a record is
34
+ stored before its gateway is called, so a retried request or a crash never charges twice.
35
+
36
+ ## Configuration
37
+
38
+ A gateway is an account at a payment provider, named by the application. Its name is stored with every record it
39
+ creates (`provider`) and ends the URL of its webhooks, so it is never renamed once it took a payment.
40
+
41
+ ```jsonc
42
+ {
43
+ "config": {
44
+ "payments": {
45
+ "gateways": {
46
+ // A gateway named after its driver needs no `driver`
47
+ "stripe": {
48
+ "secretKey": "${STRIPE_SECRET_KEY}",
49
+ "publicKey": "${STRIPE_PUBLIC_KEY}",
50
+ "webhookSecret": "${STRIPE_WEBHOOK_SECRET}"
51
+ }
52
+ },
53
+ "currency": "EUR",
54
+ "successUrl": "https://shop.example.com/checkout/done",
55
+ "cancelUrl": "https://shop.example.com/checkout",
56
+ "routes": { "enabled": true }
57
+ }
58
+ },
59
+ "environments": {
60
+ "test": {
61
+ "payments": { "defaultGateway": "fake" }
62
+ }
63
+ }
64
+ }
65
+ ```
66
+
67
+ | Gateway property | Description |
68
+ | ---------------- | ------------------------------------------------------------------------------------------------------ |
69
+ | `driver` | The driver reaching the provider, `stripe` or `fake`. Default: the name of the gateway |
70
+ | `secretKey` | The secret API key of the account (`sk_live_...`), required by the `stripe` driver |
71
+ | `publicKey` | The publishable key the client confirms a payment with (`pk_live_...`), returned with a `confirm` |
72
+ | `webhookSecret` | The signing secret of the webhook endpoint (`whsec_...`); without it every webhook is refused |
73
+ | `countries` | The countries whose payments the gateway takes, ISO 3166-1 alpha-2 codes |
74
+ | `currencies` | The currencies the gateway takes when no country selects one, ISO 4217 codes |
75
+ | `apiVersion` | The version of the provider API. Default: the one the driver is built for |
76
+ | `apiUrl` | The base URL of the provider API, i.e. of a mock server |
77
+ | `timeout` | The timeout of a request. Default: `payments.timeout` |
78
+ | `maxRetries` | The retries of a request failing on the network or with a server error. Default: `payments.maxRetries` |
79
+
80
+ Each property is also a variable, `PAYMENTS_GATEWAYS_<NAME>_<PROPERTY>` (`PAYMENTS_GATEWAYS_STRIPE_SECRET_KEY`), a
81
+ gateway named in camelCase spelled in upper snake case (`stripeUs` is `PAYMENTS_GATEWAYS_STRIPE_US_SECRET_KEY`). Every
82
+ key of the module is listed in the [configuration](./configuration.md#payments-payments_). The startup fails with
83
+ `CONFIGURATION_INVALID` for a default gateway that is not configured, for several gateways without
84
+ `payments.defaultGateway`, and in production without any gateway. A gateway whose driver package is not installed, or
85
+ a Stripe gateway without its `secretKey`, fails the first call using it.
86
+
87
+ ### Several gateways
88
+
89
+ Laws, acquirers and fees differ by country, so an application may take its payments through several accounts at
90
+ once. Each is a gateway of its own, with its own keys, webhook endpoint and customers:
91
+
92
+ ```jsonc
93
+ "payments": {
94
+ "defaultGateway": "stripeEu",
95
+ "gateways": {
96
+ "stripeEu": { "driver": "stripe", "secretKey": "${STRIPE_EU_SECRET_KEY}", "webhookSecret": "${STRIPE_EU_WEBHOOK_SECRET}", "publicKey": "pk_live_..." },
97
+ "stripeUs": { "driver": "stripe", "secretKey": "${STRIPE_US_SECRET_KEY}", "webhookSecret": "${STRIPE_US_WEBHOOK_SECRET}", "publicKey": "pk_live_...", "countries": ["US", "CA"] },
98
+ "stripeUk": { "driver": "stripe", "secretKey": "${STRIPE_UK_SECRET_KEY}", "webhookSecret": "${STRIPE_UK_WEBHOOK_SECRET}", "publicKey": "pk_live_...", "countries": ["GB"], "currencies": ["GBP"] }
99
+ }
100
+ }
101
+ ```
102
+
103
+ The gateway of a call is the first of:
104
+
105
+ 1. The `gateway` it names: `createPayment({ gateway: 'stripeUs', ... })`.
106
+ 2. The name returned by the resolver of the application, when one is set.
107
+ 3. The first gateway whose `countries` hold the `country` of the call.
108
+ 4. The first gateway whose `currencies` hold its currency.
109
+ 5. `payments.defaultGateway`, otherwise the only configured gateway.
110
+
111
+ ```ts
112
+ // src/payments/index.ts, an application file
113
+ import { setPaymentGatewayResolver } from '@appweaver/payments';
114
+
115
+ // Anything the config cannot express, i.e. the legal entity of the user. `undefined` leaves it to the config.
116
+ setPaymentGatewayResolver(({ country, currency, userId }) =>
117
+ country && EU_COUNTRIES.includes(country) ? 'stripeEu' : undefined
118
+ );
119
+ ```
120
+
121
+ A name that is not a configured gateway fails with `PAYMENT_GATEWAY_UNKNOWN`. A user is a separate customer at each
122
+ gateway (`PaymentCustomer` per `provider`), with their own saved payment methods there, and the plans are read per
123
+ gateway, the same `key` naming the same plan on each (`pro-monthly`). A record stays with the gateway that created it:
124
+ its refund, capture or cancellation always goes to its `provider`, whatever the selection rules are by then.
125
+
126
+ ### Stripe
127
+
128
+ 1. Install `@appweaver/stripe` and set the `secretKey` and the `publicKey` of the gateway from the Stripe dashboard
129
+ (Developers > API keys). The test keys (`sk_test_...`) of a sandbox move no money.
130
+ 2. Add a webhook endpoint (Developers > Webhooks) at `https://<host>/payments/webhooks/<gateway>`, the name of the
131
+ gateway at its end (`/payments/webhooks/stripe`), and set its signing secret as `webhookSecret`. Each gateway has
132
+ its own endpoint and secret.
133
+ 3. Select the events of the endpoint:
134
+
135
+ | Events | Moves |
136
+ | --------------------------------------------------------------------------------------------------------------------------- | ----------------------------- |
137
+ | `payment_intent.succeeded`, `.payment_failed`, `.canceled`, `.processing`, `.requires_action`, `.amount_capturable_updated` | The payments and their ledger |
138
+ | `refund.created`, `refund.updated`, `refund.failed` | The refunds |
139
+ | `charge.dispute.created`, `.updated`, `.closed`, `.funds_withdrawn`, `.funds_reinstated` | The disputes (chargebacks) |
140
+ | `payment_method.attached`, `.updated`, `.automatically_updated`, `.detached` | The saved payment methods |
141
+ | `customer.subscription.created`, `.updated`, `.deleted`, `.paused`, `.resumed`, `.trial_will_end` | The subscriptions |
142
+ | `invoice.finalized`, `invoice.paid`, `invoice.payment_failed`, `invoice.voided`, `invoice.marked_uncollectible` | The invoices and the renewals |
143
+ | `checkout.session.completed`, `.expired`, `.async_payment_succeeded`, `.async_payment_failed` | The hosted checkout pages |
144
+ | `customer.deleted` | A customer deleted at Stripe |
145
+
146
+ Any other event is stored as `ignored` and answered with `200`. Locally, forward the events with the Stripe CLI and
147
+ use the secret it prints:
148
+
149
+ ```sh
150
+ stripe listen --forward-to localhost:3000/payments/webhooks/stripe
151
+ ```
152
+
153
+ The driver creates PaymentIntents with automatic payment methods, Checkout Sessions, SetupIntents, Billing
154
+ subscriptions and customer portal sessions. `(await payments.gateway('stripe') as StripeGateway).client` is the client
155
+ of the SDK, for a call the module does not wrap. The health check of a Stripe gateway reads the balance of its account.
156
+
157
+ ## One-time payments
158
+
159
+ `PaymentsService` is defined with the database and a queue:
160
+
161
+ ```ts
162
+ import { inject } from '@appweaver/core';
163
+ import { PaymentsService } from '@appweaver/payments';
164
+
165
+ const payments = inject(PaymentsService);
166
+ ```
167
+
168
+ ### A payment the client confirms
169
+
170
+ The server creates the payment, the client confirms it with the `clientSecret` and the `publicKey` of the next action
171
+ in the card form of the gateway, and the result arrives in a webhook:
172
+
173
+ ```ts
174
+ // POST /api/orders/:id/pay, a route of the application
175
+ const { payment, nextAction } = await payments.createPayment({
176
+ amount: order.total, // minor units, computed by the server
177
+ currency: 'EUR',
178
+ userId: user.id,
179
+ email: user.email,
180
+ description: `Order ${order.number}`,
181
+ reference: String(order.id),
182
+ referenceType: 'order',
183
+ idempotencyKey: `order-${order.id}`, // the same order never creates a second payment
184
+ country: order.billingCountry // selects the gateway
185
+ });
186
+ return { paymentId: payment.id, nextAction };
187
+ // nextAction: { type: 'confirm', clientSecret: 'pi_..._secret_...', publicKey: 'pk_live_...' }
188
+ ```
189
+
190
+ ```ts
191
+ // The browser, with Stripe.js: the card never reaches the application
192
+ const stripe = await loadStripe(nextAction.publicKey);
193
+ const elements = stripe.elements({ clientSecret: nextAction.clientSecret });
194
+ elements.create('payment').mount('#payment');
195
+ await stripe.confirmPayment({ elements, confirmParams: { return_url } });
196
+ ```
197
+
198
+ ```ts
199
+ // src/payments/index.ts: the order is paid when the gateway says so
200
+ import { onPaymentEvent } from '@appweaver/payments';
201
+
202
+ onPaymentEvent('payment.succeeded', async ({ payment }) => {
203
+ if (payment?.referenceType === 'order') {
204
+ await injectService('Order').update(Number(payment.reference), {
205
+ status: 'Paid'
206
+ });
207
+ }
208
+ });
209
+ ```
210
+
211
+ | `createPayment` input | Description |
212
+ | ------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
213
+ | `amount` | The amount in minor units, a positive safe integer (`toMinorUnits(19.99, 'USD')` converts a decimal) |
214
+ | `currency` | ISO 4217 code. Default: `payments.currency` |
215
+ | `userId`, `email`, `name`, `locale` | The user paying, whose customer of the gateway is created on their first payment with these details; a payment without a `userId` (a guest) has no customer and no saved methods, and its emails go to its `email` |
216
+ | `gateway`, `country` | Select the gateway, see [several gateways](#several-gateways) |
217
+ | `paymentMethodId` | The ID of a saved `PaymentMethod` of the user, charged at once without the client |
218
+ | `offSession` | Charge the saved method while the user is away, i.e. from a job |
219
+ | `savePaymentMethod` | Save the payment method of the payment for later ones |
220
+ | `captureMethod` | `manual` only authorizes the amount, see [manual capture](#manual-capture). Default: `automatic` |
221
+ | `description`, `statementDescriptor` | What is paid for, and the text on the statement of the customer |
222
+ | `reference`, `referenceType` | What the payment is for in the application, found again with `findPayments(reference, type)` |
223
+ | `idempotencyKey` | A key of the caller: a second call with it returns the payment of the first one |
224
+ | `returnUrl` | Where the gateway sends the customer back after a redirect of their bank. Default: the return route |
225
+ | `metadata` | String values stored with the record and sent to the gateway |
226
+
227
+ The `nextAction` of a result tells the client what to do:
228
+
229
+ | `type` | The client |
230
+ | ---------- | ----------------------------------------------------------------------------------------- |
231
+ | `none` | Nothing: the payment is paid, authorized, processing or canceled, see its `status` |
232
+ | `confirm` | Confirms the `clientSecret` with the library of the gateway, created with the `publicKey` |
233
+ | `redirect` | Opens the `url`, a page of the gateway or of the bank of the customer |
234
+
235
+ A payment moves through `pending`, `requiresAction` (the bank wants a confirmation, i.e. 3D Secure), `processing`,
236
+ `authorized`, `succeeded`, `failed` and `canceled`. Only `succeeded` and `canceled` are final: a failed attempt may be
237
+ confirmed again with another card, on the same payment. `isFinalStatus(status)` and `canTransition(from, to)` tell.
238
+
239
+ ### Charging a saved payment method
240
+
241
+ ```ts
242
+ const { payment, nextAction } = await payments.createPayment({
243
+ amount: 4900,
244
+ userId: user.id,
245
+ paymentMethodId: method.id,
246
+ offSession: true // the user is not there to confirm
247
+ });
248
+ ```
249
+
250
+ The payment is `succeeded` at once, or the call throws `PAYMENT_DECLINED` with the `declineCode` of the bank in its
251
+ details, the payment recorded as `failed`. A bank wanting a confirmation leaves it `requiresAction` with a `confirm`
252
+ or `redirect` next action for the client.
253
+
254
+ ### Hosted checkout
255
+
256
+ `createCheckout` creates a page of the gateway where the customer pays, without any payment form in the application:
257
+
258
+ ```ts
259
+ const { payment, nextAction } = await payments.createCheckout({
260
+ amount: order.total,
261
+ currency: 'EUR',
262
+ userId: user.id,
263
+ email: user.email,
264
+ description: `Order ${order.number}`,
265
+ reference: String(order.id)
266
+ });
267
+ // nextAction: { type: 'redirect', url: 'https://checkout.stripe.com/...' }, the client opens the url
268
+ ```
269
+
270
+ The customer comes back to the return route of the module (`GET /payments/return/<id>`), which reads the payment from
271
+ its gateway, since they may be back before the webhook, and redirects to `payments.successUrl`, or to
272
+ `payments.cancelUrl` for a payment left unpaid, with `?paymentId=<id>&status=<status>`. The page there shows the
273
+ status and never fulfills an order: `payment.succeeded` does. `successUrl` and `cancelUrl` of the input replace the
274
+ return route. An expired page cancels its payment.
275
+
276
+ `cancelPayment` of a payment whose page is still open closes the page at the gateway first (`expireCheckout` of the
277
+ driver), so it cannot be paid afterwards. A page paid in the meantime is applied instead, and the call fails with
278
+ `PAYMENT_INVALID_STATE`: `payment.succeeded` then decides what happens with the money, i.e. a refund for an order
279
+ cancelled meanwhile. The `sample/webshop-api` application of the repository pays its orders this way
280
+ (`src/features/payments/order-payments.ts`).
281
+
282
+ ### Manual capture
283
+
284
+ ```ts
285
+ const { payment } = await payments.createPayment({
286
+ amount: 12000,
287
+ userId: user.id,
288
+ paymentMethodId: method.id,
289
+ captureMethod: 'manual'
290
+ }); // payment.status: 'authorized', announced as payment.authorized
291
+
292
+ await payments.capturePayment(payment.id); // all of it, or
293
+ await payments.capturePayment(payment.id, 9000); // a part, the rest released
294
+ await payments.cancelPayment(payment.id); // or release the authorization
295
+ ```
296
+
297
+ A gateway without the capability fails with `PAYMENT_CAPABILITY_UNSUPPORTED`, a payment that is not `authorized` with
298
+ `PAYMENT_INVALID_STATE`, an amount above the authorized one with `PAYMENT_AMOUNT_INVALID`.
299
+
300
+ ### Refunds
301
+
302
+ ```ts
303
+ await payments.refundPayment(payment.id); // what is left of it
304
+ const refund = await payments.refundPayment(payment.id, {
305
+ amount: 500,
306
+ reason: 'Damaged item',
307
+ idempotencyKey: `return-${itemId}`
308
+ });
309
+ ```
310
+
311
+ It returns the `PaymentTransaction` of the refund and raises the `amountRefunded` of the payment, whose status stays
312
+ `succeeded`. A refund above what is left fails with `PAYMENT_REFUND_EXCEEDED` (`details.refundable`), one of a payment
313
+ that is not paid with `PAYMENT_INVALID_STATE`. A refund made in the dashboard of the gateway arrives by webhook and is
314
+ recorded the same way.
315
+
316
+ ### Reading payments
317
+
318
+ | Method | Returns |
319
+ | ----------------------------------------- | ------------------------------------------------------------------------------------------- |
320
+ | `getPayment(id)` | The payment, `PAYMENT_NOT_FOUND` for an unknown one |
321
+ | `findPayments(reference, type?)` | The payments of what the application sells, the newest first |
322
+ | `listTransactions(id)` | The ledger of a payment: its authorization, charge, capture, refunds and disputes |
323
+ | `syncPayment(id)` | Reads the payment from its gateway and applies its state, returning it with its next action |
324
+ | `cancelPayment(id)` | Cancels a payment that is not paid, closing its hosted checkout page |
325
+ | `gateways()` / `selectGateway(selection)` | The names of the gateways, and the one a selection resolves to |
326
+ | `gateway(name?)` / `publicKey(name?)` | The driver of a gateway, and its public key |
327
+
328
+ ## Saved payment methods
329
+
330
+ ```ts
331
+ // The server starts a setup, the client confirms it like a payment
332
+ const nextAction = await payments.createSetup({
333
+ userId: user.id,
334
+ email: user.email
335
+ });
336
+ // The browser: stripe.confirmSetup({ elements, confirmParams: { return_url } })
337
+
338
+ const methods = await payments.listPaymentMethods(user.id); // the default one first
339
+ await payments.setDefaultPaymentMethod(methods[1].id); // charged by the subscriptions
340
+ await payments.detachPaymentMethod(methods[0].id); // removed at the gateway too
341
+ ```
342
+
343
+ The saved method arrives with a webhook of the gateway (`paymentMethod.attached`), the first one of a customer
344
+ becoming their default. `savePaymentMethod: true` of a payment saves the method it is paid with.
345
+ `ensureCustomer({ userId, email, name, locale })` returns the `PaymentCustomer` of a user at a gateway, created there
346
+ on the first call, a changed email, name or locale sent to the gateway; `findCustomer(userId, gateway?)` only reads it.
347
+
348
+ ## Subscriptions
349
+
350
+ The gateway owns the billing cycle: it renews a subscription, retries a failed renewal and sends the webhooks moving
351
+ the records. The application creates the prices at the gateway, reads them into plans, and subscribes its users.
352
+
353
+ ### Plans
354
+
355
+ A plan is a recurring price of a gateway. Create the prices in the Stripe dashboard (or with the API), give each a
356
+ **lookup key** (`pro-monthly`), which becomes the `key` of its plan, the same on every gateway. A price without one is
357
+ keyed by its ID. Then read them:
358
+
359
+ ```sh
360
+ weaver run payments-sync-plans # every gateway
361
+ weaver run payments-sync-plans stripe # one gateway
362
+ ```
363
+
364
+ `SubscriptionsService.syncPlans(gateway?)` does the same, i.e. at startup or from a scheduled job. A price that is
365
+ archived or gone makes its plan inactive. `listPlans(gateway?)` returns the active plans, the cheapest first.
366
+
367
+ ### Subscribing
368
+
369
+ ```ts
370
+ import { SubscriptionsService } from '@appweaver/payments';
371
+
372
+ const subscriptions = inject(SubscriptionsService);
373
+
374
+ // With a saved payment method, the default one of the customer or `paymentMethodId`
375
+ const { subscription, nextAction } = await subscriptions.subscribe({
376
+ userId: user.id,
377
+ email: user.email,
378
+ plan: 'pro-monthly',
379
+ quantity: 3, // i.e. seats
380
+ trialDays: 14 // default: the trial of the price
381
+ });
382
+
383
+ // Or on the page of the gateway, where the customer enters their card
384
+ const { nextAction } = await subscriptions.createCheckout({
385
+ userId: user.id,
386
+ email: user.email,
387
+ plan: 'pro-monthly'
388
+ }); // { type: 'redirect', url }
389
+ ```
390
+
391
+ A subscription is `incomplete` until its first payment is made: `subscribe` returns a `confirm` next action when the
392
+ bank wants it confirmed or the customer has no saved method, and the subscription starts with the webhook of the paid
393
+ invoice (`subscription.created`). An unknown plan fails with `PAYMENT_PLAN_UNKNOWN`.
394
+
395
+ | Status | Means |
396
+ | ------------ | ----------------------------------------------------------------------- |
397
+ | `incomplete` | Created, its first payment not made yet |
398
+ | `trialing` | In its trial, nothing charged yet |
399
+ | `active` | Paid |
400
+ | `pastDue` | A renewal failed, the gateway retries it (`pastDueAt` holds since when) |
401
+ | `unpaid` | The retries are exhausted, the gateway keeps it without access |
402
+ | `paused` | Paused at the gateway |
403
+ | `canceled` | Ended |
404
+
405
+ ### Access
406
+
407
+ ```ts
408
+ if (await subscriptions.isActive(user.id, 'pro-monthly')) {
409
+ // trialing or active, or pastDue for less than payments.subscriptions.gracePeriod
410
+ }
411
+ const subscription = await subscriptions.findSubscription(user.id); // the newest started and not canceled, or null
412
+ ```
413
+
414
+ ### Changing and canceling
415
+
416
+ ```ts
417
+ await subscriptions.changePlan(subscription.id, 'pro-yearly', { quantity: 5 }); // prorated by default
418
+ await subscriptions.cancel(subscription.id); // at the end of the paid period (cancelAtPeriodEnd)
419
+ await subscriptions.resume(subscription.id); // keep it after all
420
+ await subscriptions.cancel(subscription.id, false); // end it at once
421
+ const invoices = await subscriptions.listInvoices(subscription.id);
422
+ const url = await subscriptions.createPortalSession(
423
+ { userId: user.id },
424
+ returnUrl
425
+ );
426
+ ```
427
+
428
+ `createPortalSession` returns the URL of the page of the gateway (the Stripe customer portal) where the user manages
429
+ their payment methods, subscriptions and invoices themselves; what they change there arrives by webhook. A renewal is
430
+ a `Payment` of its own, linked to the subscription (`subscriptionId`) and its `PaymentInvoice`, announced as
431
+ `payment.succeeded` and `invoice.paid`. A canceled subscription fails a change with `PAYMENT_INVALID_STATE`.
432
+
433
+ ### One-time payments only
434
+
435
+ The subscriptions are on by default. An application taking one-time payments only, i.e. a webshop, turns them off and
436
+ gets three tables less:
437
+
438
+ ```jsonc
439
+ { "config": { "payments": { "subscriptions": { "enabled": false } } } }
440
+ ```
441
+
442
+ With `payments.subscriptions.enabled: false`:
443
+
444
+ - The `PaymentPlan`, `PaymentSubscription` and `PaymentInvoice` models are not loaded, so `weaver generate` writes no
445
+ table of theirs, and `Payment` and `PaymentCustomer` have no relation to them (`Payment` has no `subscriptionId`).
446
+ The other six models, the one-time payments, the saved payment methods, the refunds, the webhooks and the emails
447
+ work as before.
448
+ - Every method of the `SubscriptionsService` fails with `PAYMENT_SUBSCRIPTIONS_DISABLED`, but `createPortalSession`.
449
+ The `payments-sync-plans` task fails the same way.
450
+ - The `/payment-subscriptions/*`, `/payment-invoices/*` and `/payment-plans/*` routes are not registered, and the
451
+ generated client has no `subscribe`, `subscribeCheckout`, `cancelSubscription`, `resumeSubscription` or
452
+ `changePlan` on `client.payments`.
453
+ - The webhook events of the subscriptions and invoices are stored as `ignored`, no `subscription.*` or `invoice.*`
454
+ event is announced, and `paymentsReconcile` reads the payments only. A payment of a subscription started at the
455
+ gateway itself, for a known customer, is still recorded, as any other payment.
456
+
457
+ Set it before the first `weaver generate`. Changing it later changes the database: run `weaver generate` and
458
+ `weaver migration new <name>` again. Turning the subscriptions off drops the three tables **with their data**, and the
459
+ subscriptions running at the gateway keep charging the customers there, so cancel them first.
460
+
461
+ ## Events
462
+
463
+ `onPaymentEvent(type | type[] | '*', handler)` listens to what happens to the payments, whatever caused it: a call of
464
+ the application, a webhook, the dashboard of the gateway, the reconciliation. Register the handlers in an application
465
+ file or the `main` of a module. It returns a function removing the handler.
466
+
467
+ | Event | When | Records of the event |
468
+ | --------------------------------------------------- | ---------------------------------------------------------------------------------------------- | ------------------------------------------------------- |
469
+ | `payment.succeeded` | A payment is paid, a renewal included | `payment`, `paymentMethod`, `subscription` of a renewal |
470
+ | `payment.failed` | An attempt of a payment was refused | `payment` (`failureCode`, `failureMessage`) |
471
+ | `payment.requiresAction` | The bank holds a payment until the customer confirms it | `payment` |
472
+ | `payment.authorized` | A payment with the `manual` capture is authorized | `payment` |
473
+ | `payment.canceled` | A payment was canceled, expired on its checkout page, or left unpaid for `payments.pendingTtl` | `payment` |
474
+ | `refund.succeeded` / `refund.failed` | A refund was made, or failed at the bank | `payment`, `transaction` |
475
+ | `dispute.opened` / `dispute.closed` | A chargeback was opened, then won or lost (`transaction.status`) | `payment`, `transaction` |
476
+ | `paymentMethod.attached` / `paymentMethod.detached` | A payment method was saved or removed | `paymentMethod` |
477
+ | `subscription.created` | A subscription started: its trial began or its first payment was made | `subscription` |
478
+ | `subscription.updated` | Its plan, quantity, period or `cancelAtPeriodEnd` changed | `subscription` |
479
+ | `subscription.pastDue` | A renewal failed | `subscription` |
480
+ | `subscription.canceled` | It ended | `subscription` |
481
+ | `subscription.trialWillEnd` | Its trial ends in a few days | `subscription` |
482
+ | `invoice.paid` / `invoice.paymentFailed` | An invoice of a subscription was paid, or an attempt to collect it failed | `invoice`, `subscription`, `payment` |
483
+
484
+ A handler receives `{ id, type, gateway, userId, createdAt }` with the records the event is about, as they are when it
485
+ is delivered, and the `customer` of the gateway when known.
486
+
487
+ - An event is written in the transaction of the change it tells of, then delivered by a job of the `payments` queue:
488
+ it is never lost with a crash, and never announced for a change that was rolled back.
489
+ - Delivery is **at least once**. The `id` of an event is the same on every delivery, so a handler doing something that
490
+ must happen once (shipping, crediting) makes it idempotent, i.e. by a status of its own record or by storing the id.
491
+ - A handler that throws has the event delivered again to every handler, up to `payments.eventMaxAttempts` times with
492
+ an exponential backoff, then marked as `failed` (`PaymentEvent.status`, `lastError`).
493
+ - The handlers run outside of any request, so without a user and without the policies.
494
+
495
+ ## Emails
496
+
497
+ With a mailer (`@appweaver/nodemailer`), the module emails the customer of a payment, at the `email` and in the
498
+ `locale` of their `PaymentCustomer`. A payment of a guest, created with an `email` and no `userId`, has its emails sent
499
+ to that address, in the default locale:
500
+
501
+ | Email | Event | Template | Translations (`emails.payments.*`) | Switch (`payments.emails.*`) |
502
+ | --------------------- | ------------------------------------------------------- | ---------------------------------- | ---------------------------------- | ---------------------------- |
503
+ | Receipt | `payment.succeeded` | `emails/payment-receipt` | `receipt` | `receipt` |
504
+ | Failed payment | `payment.failed` | `emails/payment-failed` | `failed` | `failed` |
505
+ | Refund | `refund.succeeded` | `emails/payment-refunded` | `refunded` | `refunded` |
506
+ | Confirmation needed | `payment.requiresAction` of a subscription payment only | `emails/payment-action-required` | `actionRequired` | `actionRequired` |
507
+ | Canceled subscription | `subscription.canceled` | `emails/subscription-canceled` | `subscriptionCanceled` | `subscriptionCanceled` |
508
+ | Trial ending | `subscription.trialWillEnd` | `emails/subscription-trial-ending` | `trialEnding` | `trialEnding` |
509
+
510
+ The module ships the `.html` and `.subject` templates of each email, with the `layouts/email.html` layout and the
511
+ `partials/email-button.html` partial they share, and their English translations. All of it is replaced piece by piece
512
+ by the application:
513
+
514
+ - **A template**: a file of the same name in `templates/` of the application (`templates/emails/payment-receipt.html.hbs`,
515
+ or the layout to restyle every email) replaces the one of the module. A locale variant
516
+ (`payment-receipt.de.html.hbs`) works as for any template, see [templates](./templates.md).
517
+ - **A text**: the keys of `locales/<locale>.json` replace the ones of the module, and add the other languages:
518
+
519
+ ```json
520
+ {
521
+ "emails": {
522
+ "payments": {
523
+ "labels": {
524
+ "description": "Beschreibung",
525
+ "plan": "Tarif",
526
+ "reference": "Referenz",
527
+ "method": "Zahlungsmethode",
528
+ "date": "Datum",
529
+ "receipt": "Beleg",
530
+ "reason": "Grund",
531
+ "retry": "Nächster Versuch",
532
+ "link": "Zahlung bestätigen"
533
+ },
534
+ "receipt": {
535
+ "subject": "Ihr Beleg über {amount}",
536
+ "message": "Vielen Dank, wir haben Ihre Zahlung über {amount} erhalten.",
537
+ "receipt": "Beleg ansehen"
538
+ }
539
+ }
540
+ }
541
+ }
542
+ ```
543
+
544
+ The other keys are `failed`, `refunded`, `trialEnding` (`subject`, `message`, `hint`), `actionRequired` (`subject`,
545
+ `message`, `action`, `hint`) and `subscriptionCanceled` (`subject`, `message`).
546
+
547
+ The templates and the translations receive, already formatted for the locale: `amount` (`€19.99`), `description`,
548
+ `reference`, `plan` (the name of the plan), `method` (`visa •••• 4242`), `reason` (why a payment failed), `receipt`
549
+ (the URL of the receipt of the gateway), `link` (where the customer confirms a payment: the hosted invoice, otherwise
550
+ `payments.successUrl`), `date`, `retry` (the next attempt of a failed renewal) and `appName`.
551
+
552
+ Without `@appweaver/handlebars` an email is sent as the plain text of its translations. Nothing is sent without a
553
+ mailer, without an address of the customer or of the payment, or with `payments.emails.enabled: false`. An email is sent once its event
554
+ is delivered to the handlers, and a failing one is logged, never a reason to run the handlers again. To send the
555
+ emails yourself, turn them off and call the mailer from `onPaymentEvent`; `sendPaymentEmail(event)` sends the email of
556
+ an event on demand.
557
+
558
+ ## Routes
559
+
560
+ The webhook and return routes are always registered with `@appweaver/web`, at the root of the server, outside of the
561
+ API prefix and the OpenAPI document:
562
+
563
+ | Route | Purpose |
564
+ | ---------------------------------- | ------------------------------------------------------------------------------------------------------------ |
565
+ | `POST /payments/webhooks/:gateway` | The webhook endpoint of a gateway: verifies the signature over the raw body, stores the event, answers `200` |
566
+ | `GET /payments/return/:id` | Where a hosted page sends the customer back, redirecting to `payments.successUrl` or `cancelUrl` |
567
+
568
+ `payments.routes.enabled: true` adds the routes of the API (`/api` by default), for an authenticated user:
569
+
570
+ | Route | Purpose |
571
+ | ----------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- |
572
+ | `GET /payments/:id`, `POST /payments/query` | The payments of the user |
573
+ | `GET /payment-methods/:id`, `POST /payment-methods/query` | Their saved payment methods |
574
+ | `GET /payment-transactions/:id`, `POST /payment-transactions/query` | Their ledger entries: charges, refunds, disputes |
575
+ | `GET /payment-subscriptions/:id`, `POST /payment-subscriptions/query` | Their subscriptions |
576
+ | `GET /payment-invoices/:id`, `POST /payment-invoices/query` | Their invoices |
577
+ | `GET /payment-plans/:id`, `POST /payment-plans/query` | The active plans |
578
+ | `POST /payment-methods/setup` | Starts saving a payment method, answering `{ nextAction }` |
579
+ | `POST /payment-methods/:id/default`, `DELETE /payment-methods/:id` | Sets the default payment method, removes one |
580
+ | `POST /payment-subscriptions/subscribe` | Subscribes to `{ plan, quantity?, paymentMethodId? }`, answering `{ subscription, nextAction }` |
581
+ | `POST /payment-subscriptions/checkout` | Subscribes on the page of the gateway, answering the `redirect` next action |
582
+ | `POST /payment-subscriptions/:id/cancel`, `/:id/resume`, `/:id/plan` | Cancels (`{ atPeriodEnd? }`), keeps, or moves a subscription to `{ plan, quantity? }` |
583
+ | `POST /payments/portal` | Answers the `url` of the billing page of the gateway (`{ returnUrl? }`) |
584
+ | `POST /payments/:id/refund`, `/:id/capture`, `/:id/cancel`, `/:id/sync` | The admin roles only (`payments.routes.adminRoles`): refund `{ amount?, reason? }`, capture `{ amount? }`, cancel, read again |
585
+
586
+ - The routes of the subscriptions, the invoices and the plans are registered with `payments.subscriptions.enabled`
587
+ only, see [one-time payments only](#one-time-payments-only).
588
+ - The record routes are read-only, and their policies show a user their own records (`userId`), the admin roles the
589
+ records of everyone. A record of another user answers `404`. `isPaymentAdmin(user)` tells the admin roles.
590
+ - A model of the module the application defines its own routes for (`createRoutes({ modelName: 'Payment', ... })`)
591
+ keeps those, and the module adds none for it.
592
+ - The bodies of the user routes take `gateway` and `country` to select the gateway.
593
+ - There is no route creating a one-time payment, on purpose: the amount comes from the application. Add your own
594
+ route calling `createPayment` or `createCheckout`, as in [a payment the client confirms](#a-payment-the-client-confirms).
595
+ - The generated client calls the routes with `client.payments` (`subscribe`, `setupPaymentMethod`, `portal`,
596
+ `refund`, ...) and reads the records with their resource clients, see
597
+ [client.md](./client.md#paymentsclient). The bodies and the answers are the `Payments<Name>` models of the OpenAPI
598
+ document (`PaymentsSubscribeRequest`, `PaymentsNextAction`).
599
+
600
+ ## Data models
601
+
602
+ The module brings its models to the Prisma schema with `weaver generate`. Their names are taken, so an application
603
+ with its own `Payment` model renames it first.
604
+
605
+ | Model | Holds |
606
+ | --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
607
+ | `PaymentCustomer` | The customer of a user at a gateway: `provider`, `providerCustomerId`, `userId`, `email`, `name`, `locale` |
608
+ | `PaymentMethod` | A saved payment method: `type`, `brand`, `last4`, `expMonth`, `expYear`, `country`, `isDefault` |
609
+ | `Payment` | A payment: `status`, `amount`, `currency`, `amountCaptured`, `amountRefunded`, `captureMethod`, `disputed`, `email`, `reference`, `referenceType`, `failureCode`, `failureMessage`, `receiptUrl`, `metadata`, `paidAt` |
610
+ | `PaymentTransaction` | An entry of the ledger of a payment, append-only: `type` (`authorization`, `capture`, `charge`, `refund`, `dispute`), `status`, `amount`, `fee`, `reason`, `occurredAt` |
611
+ | `PaymentPlan` | A recurring price: `key`, `name`, `amount`, `currency`, `interval`, `intervalCount`, `trialDays`, `active` |
612
+ | `PaymentSubscription` | A subscription: `status`, `planKey`, `quantity`, `cancelAtPeriodEnd`, `currentPeriodStart`, `currentPeriodEnd`, `trialEnd`, `canceledAt`, `endedAt`, `pastDueAt` |
613
+ | `PaymentInvoice` | An invoice of a subscription: `status`, `number`, `amountDue`, `amountPaid`, `attemptCount`, `nextAttemptAt`, `hostedUrl`, `pdfUrl`, `paidAt` |
614
+ | `PaymentEvent` | The outbox of the events of `onPaymentEvent`: `type`, `status` (`pending`, `delivered`, `failed`), `attempts`, `lastError` |
615
+ | `PaymentWebhookEvent` | The inbox of the webhooks: `providerEventId`, `type`, `status` (`received`, `processed`, `failed`, `ignored`), `attempts`, `lastError`, `payload` |
616
+
617
+ - `PaymentPlan`, `PaymentSubscription` and `PaymentInvoice` exist with `payments.subscriptions.enabled` only, see
618
+ [one-time payments only](#one-time-payments-only).
619
+ - Every record carries the `provider` (the name of its gateway) and the ID of its object there
620
+ (`providerPaymentId`, `providerSubscriptionId`, ...), unique together.
621
+ - Every amount (`amount`, `amountCaptured`, `amountRefunded`, `fee`, `amountDue`, `amountPaid`) is a `bigInt` column of
622
+ minor units, read by the services as a number. `toMinorUnits(19.99, 'USD')`, `fromMinorUnits(1999, 'USD')`,
623
+ `formatAmount(1999, 'EUR', 'de')` and `currencyExponent('JPY')` convert and format them.
624
+ - `userId` is text without a relation to the user model, so deleting a user never deletes or blocks the financial
625
+ records, which outlive them.
626
+ - The records are written by the module only. Read them with `injectService('Payment')` like any resource, i.e. to
627
+ join them to the orders of the application, and extend their policies like any other.
628
+ - `metadata` is sent to the gateway with the record, so it holds no secret and no personal data beyond what the
629
+ gateway already has. The module adds `appweaverPaymentId` and `appweaverSubscriptionId`, linking the objects of the
630
+ gateway to their records.
631
+
632
+ ## Webhooks
633
+
634
+ A webhook request is verified against the `webhookSecret` of its gateway over the bytes it was received with (a
635
+ signature older than `payments.webhooks.tolerance` is refused, against a replay), stored once by the ID of its event,
636
+ and answered with `200` at once. A job of the `payments` queue then applies it:
637
+
638
+ - **Once**: an event the gateway sends again is recognized by its ID and not processed twice.
639
+ - **In order**: the object of an event is read from the gateway again before it is applied
640
+ (`payments.webhooks.refetch`), and a state only moves forward, so the events delivered late or out of order cannot
641
+ move a record back.
642
+ - **Atomically**: the records and the events of `onPaymentEvent` are written in one transaction with the webhook
643
+ marked as processed.
644
+ - **Retried**: a failing event is tried `payments.webhooks.maxAttempts` times, then kept as `failed` with its
645
+ `lastError`, to be processed again once its cause is fixed:
646
+
647
+ ```sh
648
+ weaver run payments-replay # every failed webhook event
649
+ weaver run payments-replay <id> # one stored event, by the ID of its PaymentWebhookEvent
650
+ ```
651
+
652
+ A request with a missing or wrong signature answers `400` (`PAYMENT_WEBHOOK_INVALID`), and one for a gateway that is
653
+ not configured answers `404`. Keep the endpoint reachable without authentication: the signature is its authentication.
654
+
655
+ ## Maintenance jobs
656
+
657
+ Registered as [maintenance jobs](./modules.md#maintenance-jobs), each run by one instance at a time:
658
+
659
+ | Job | Schedule | Does |
660
+ | ------------------------ | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
661
+ | `paymentsReconcile` | `5m` | Reads the payments and subscriptions in a state that is not final for longer than `payments.reconcileAfter` from their gateways again, catching the webhooks never received, and cancels the payments unpaid for `payments.pendingTtl` |
662
+ | `paymentsRedeliver` | `1m` | Queues the received webhook events and the pending events no job finished, i.e. after a crash |
663
+ | `paymentEventsRetention` | `1h` | Deletes the processed webhook events (`payments.webhooks.retention`) and the delivered events (`payments.eventRetention`); the failed ones are kept |
664
+
665
+ `weaver run maintenance paymentsReconcile` runs one by hand.
666
+
667
+ ## The fake gateway
668
+
669
+ The built-in `fake` gateway calls no provider and moves no money. It is the default gateway while none is configured,
670
+ never available in production, and a project scaffolded with the `payments` module keeps it in the `test`
671
+ environment (`payments.defaultGateway: 'fake'`).
672
+ It has every capability and emits the events a provider would send to the webhook endpoint, processed the same way.
673
+
674
+ - **In development**: a hosted checkout opens a page of the application (`/payments/fake/checkout/...`) with a Pay and
675
+ a Cancel link. Payments charged to a saved method are paid at once.
676
+ - **In tests**: drive it as the customer and the provider would:
677
+
678
+ ```ts
679
+ import { inject } from '@appweaver/core';
680
+ import { FakePaymentGateway, PaymentsService } from '@appweaver/payments';
681
+
682
+ const payments = inject(PaymentsService);
683
+ const gateway = (await payments.gateway('fake')) as FakePaymentGateway;
684
+
685
+ const { payment } = await payments.createPayment({ amount: 1999, userId: 1 });
686
+ await gateway.confirmPayment(payment.providerPaymentId!); // or 'failed', 'requiresAction'
687
+ expect((await payments.getPayment(payment.id)).status).toBe('succeeded');
688
+ ```
689
+
690
+ | Helper | Stands for |
691
+ | ------------------------------------------------------ | -------------------------------------------------------------------------------- |
692
+ | `confirmPayment(id, outcome?)` | The customer confirming a payment: `succeeded`, `failed`, `requiresAction` |
693
+ | `attachPaymentMethod(customerId, card?)` | A saved card, a Visa ending with 4242 by default |
694
+ | `confirmSetup(setupId)` | The customer completing a setup |
695
+ | `completeCheckout(checkoutId, outcome?)` | The customer paying on the hosted page, or the page expiring (`expired`) |
696
+ | `addPrice(price?)` | A recurring price, read by `syncPlans` |
697
+ | `renewSubscription(id, outcome?)` | The renewal of a subscription, paid or `failed` |
698
+ | `announceTrialEnd(id)`, `disputePayment(id, outcome?)` | The trial reminder, and a chargeback |
699
+ | `signWebhook(event)` | The body and the headers of a signed webhook request, for a test of the endpoint |
700
+ | `events`, `flush()` | The events emitted so far, and waiting for their delivery |
701
+
702
+ `FAKE_DECLINED_METHOD` is a saved payment method always refused, `FAKE_ACTION_METHOD` one whose payments wait for the
703
+ customer. The events of the payments are delivered by the queue, so a test awaits its jobs before asserting on a
704
+ handler or an email. `registerPaymentGateway(name, DriverClass)` registers a driver class of a test under a driver
705
+ name, without a module.
706
+
707
+ ## Errors
708
+
709
+ A `PaymentError` of `@appweaver/common`, mapped to the status below by the web module ([errors](./errors.md)):
710
+
711
+ | Code | Status | Thrown when | Details |
712
+ | -------------------------------- | ------ | -------------------------------------------------------------------------------------- | --------------------------------------------------------------- |
713
+ | `PAYMENT_DECLINED` | 402 | The bank refused the payment method | `gateway`, `operation`, `declineCode`, `status`, `providerCode` |
714
+ | `PAYMENT_REQUEST_INVALID` | 400 | The provider rejected the request | `gateway`, `operation`, `param`, `status`, `providerCode` |
715
+ | `PAYMENT_GATEWAY_UNAVAILABLE` | 503 | The provider is unreachable, rate limiting or failing; a retry may succeed | `gateway`, `operation`, `status`, `providerCode` |
716
+ | `PAYMENT_GATEWAY_FAILED` | 502 | Any other failure of the provider, i.e. wrong credentials | `gateway`, `operation`, `status`, `providerCode` |
717
+ | `PAYMENT_GATEWAY_UNKNOWN` | 500 | A gateway that is not configured | `gateway` |
718
+ | `PAYMENT_CAPABILITY_UNSUPPORTED` | 501 | The driver of the gateway cannot do what is asked | `gateway`, `capability` |
719
+ | `PAYMENT_AMOUNT_INVALID` | 400 | An amount that is not a positive integer of minor units, or above what can be captured | `amount`, `currency` |
720
+ | `PAYMENT_CURRENCY_UNSUPPORTED` | 400 | A currency that is no ISO 4217 code, or not in `payments.currencies` | `currency` |
721
+ | `PAYMENT_NOT_FOUND` | 404 | An unknown payment, or webhook event to replay | `id` |
722
+ | `PAYMENT_INVALID_STATE` | 409 | The payment or the subscription is in no state for the action | `id`, `status`, `action` |
723
+ | `PAYMENT_REFUND_EXCEEDED` | 409 | A refund above what is left of the payment | `id`, `amount`, `refundable` |
724
+ | `PAYMENT_METHOD_NOT_FOUND` | 404 | An unknown payment method, or one of another customer | `id` |
725
+ | `PAYMENT_PLAN_UNKNOWN` | 404 | No active plan of the key at the gateway | `plan` |
726
+ | `PAYMENT_SUBSCRIPTION_NOT_FOUND` | 404 | An unknown subscription | `id` |
727
+ | `PAYMENT_SUBSCRIPTIONS_DISABLED` | 501 | A call of the `SubscriptionsService` with `payments.subscriptions.enabled` off | |
728
+ | `PAYMENT_WEBHOOK_INVALID` | 400 | A webhook with a missing, wrong or expired signature | `gateway`, `reason` |
729
+
730
+ ```ts
731
+ import { ErrorCode, isAppweaverError } from '@appweaver/common';
732
+
733
+ try {
734
+ await payments.createPayment({
735
+ amount,
736
+ userId,
737
+ paymentMethodId,
738
+ offSession: true
739
+ });
740
+ } catch (e) {
741
+ if (isAppweaverError(e) && e.is(ErrorCode.PaymentDeclined)) {
742
+ // e.details.declineCode: 'insufficient_funds', 'expired_card', ...
743
+ }
744
+ throw e;
745
+ }
746
+ ```
747
+
748
+ The message of a decline is the one of the provider, written for the customer. The original error of the SDK is the
749
+ `cause`.
750
+
751
+ ## Operations
752
+
753
+ - **Health**: `payments.healthCheckGateways: ['stripe']` adds the gateways to the `payments` health check, each
754
+ checked with a request using its credentials.
755
+ - **Telemetry**: a span per gateway call and the counters of the webhooks and the events, see
756
+ [telemetry](./telemetry.md) (`telemetry.instrumentations.payments`).
757
+ - **Logs**: the `payments` logger. A webhook event that failed for good is logged as an error with the ID of its
758
+ event, and a payment that could not be reconciled as a warning.
759
+ - **Audit**: the webhook and return routes are not recorded in the audit log.
760
+ - **Going live**: set the live keys and the webhook secret of every gateway, install a persistent queue
761
+ (`@appweaver/bullmq`), keep `payments.webhooks.refetch` on, and watch `PaymentWebhookEvent` and `PaymentEvent` for
762
+ the `failed` status.
763
+
764
+ ## A driver of another provider
765
+
766
+ A driver extends `PaymentGateway` of `@appweaver/payments`, created once per gateway with its `GatewayConfig`. It
767
+ implements the customers, `createPayment`, `getPayment`, `cancelPayment`, `refundPayment`, `verifyWebhook` and
768
+ `checkHealth`, declares its `capabilities` (`checkout`, `manualCapture`, `savedMethods`, `subscriptions`, `portal`,
769
+ `prices`) and overrides the methods of the ones it has (`createCheckout`, `getCheckout` and `expireCheckout` for
770
+ `checkout`); the others throw `PAYMENT_CAPABILITY_UNSUPPORTED`. It speaks
771
+ minor units and the statuses of the module, sends the idempotency key of every write, normalizes its webhook events
772
+ into `GatewayEventData`, and throws a `PaymentError` (`PAYMENT_DECLINED`, `PAYMENT_REQUEST_INVALID`,
773
+ `PAYMENT_GATEWAY_UNAVAILABLE`, `PAYMENT_GATEWAY_FAILED`). Its module provides it by its driver name:
774
+
775
+ ```ts
776
+ // module.ts
777
+ import { defineModule } from '@appweaver/common';
778
+ import { PaymentGateway } from '@appweaver/payments';
779
+
780
+ export default defineModule({
781
+ name: '@acme/appweaver-adyen',
782
+ requires: ['@appweaver/payments'],
783
+ providers: [
784
+ {
785
+ contract: PaymentGateway,
786
+ name: 'adyen',
787
+ load: () => import('./adyen-gateway')
788
+ }
789
+ ]
790
+ });
791
+ ```
792
+
793
+ A gateway then selects it with `"driver": "adyen"`. There is no `payments.provider` key: the gateways name their
794
+ drivers, so the drivers of several providers work side by side. Test it with `testPaymentGatewayContract` of
795
+ `@appweaver/testing` ([modules](./modules.md#testing-a-driver)).