@owlmeans/server-payment 0.1.21 → 0.2.0-alpha.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.
Files changed (296) hide show
  1. package/README.md +52 -54
  2. package/agent-meta/manifest.json +2 -2
  3. package/agent-meta/skills/server-payment/SKILL.md +272 -330
  4. package/agent-meta/skills/server-payment/parts/reference.md +3 -3
  5. package/build/access/types.d.ts +7 -16
  6. package/build/access/types.d.ts.map +1 -1
  7. package/build/access.d.ts.map +1 -1
  8. package/build/access.js +6 -8
  9. package/build/access.js.map +1 -1
  10. package/build/actions/resync.d.ts +3 -3
  11. package/build/actions/resync.js +5 -5
  12. package/build/actions/resync.js.map +1 -1
  13. package/build/actions/webhook.d.ts +4 -1
  14. package/build/actions/webhook.d.ts.map +1 -1
  15. package/build/actions/webhook.js +8 -4
  16. package/build/actions/webhook.js.map +1 -1
  17. package/build/bootstrap/types.d.ts +13 -7
  18. package/build/bootstrap/types.d.ts.map +1 -1
  19. package/build/bootstrap.d.ts +4 -4
  20. package/build/bootstrap.d.ts.map +1 -1
  21. package/build/bootstrap.js +19 -10
  22. package/build/bootstrap.js.map +1 -1
  23. package/build/catalogue/types.d.ts +3 -3
  24. package/build/catalogue/types.d.ts.map +1 -1
  25. package/build/catalogue.d.ts.map +1 -1
  26. package/build/catalogue.js +4 -8
  27. package/build/catalogue.js.map +1 -1
  28. package/build/checkout/types.d.ts +21 -0
  29. package/build/checkout/types.d.ts.map +1 -0
  30. package/build/{plugins/stripe → checkout}/types.js.map +1 -1
  31. package/build/checkout.d.ts +6 -0
  32. package/build/checkout.d.ts.map +1 -0
  33. package/build/checkout.js +374 -0
  34. package/build/checkout.js.map +1 -0
  35. package/build/config.d.ts +10 -16
  36. package/build/config.d.ts.map +1 -1
  37. package/build/config.js +18 -59
  38. package/build/config.js.map +1 -1
  39. package/build/consts.d.ts +3 -49
  40. package/build/consts.d.ts.map +1 -1
  41. package/build/consts.js +3 -61
  42. package/build/consts.js.map +1 -1
  43. package/build/consumer/cancellation/types.d.ts +6 -4
  44. package/build/consumer/cancellation/types.d.ts.map +1 -1
  45. package/build/consumer/cancellation.d.ts.map +1 -1
  46. package/build/consumer/cancellation.js +11 -5
  47. package/build/consumer/cancellation.js.map +1 -1
  48. package/build/consumer/capture/types.d.ts +8 -12
  49. package/build/consumer/capture/types.d.ts.map +1 -1
  50. package/build/consumer/capture.d.ts.map +1 -1
  51. package/build/consumer/capture.js +48 -53
  52. package/build/consumer/capture.js.map +1 -1
  53. package/build/consumer/index.d.ts +4 -0
  54. package/build/consumer/index.d.ts.map +1 -1
  55. package/build/consumer/index.js +2 -0
  56. package/build/consumer/index.js.map +1 -1
  57. package/build/consumer/reconcile.d.ts.map +1 -1
  58. package/build/consumer/reconcile.js +82 -72
  59. package/build/consumer/reconcile.js.map +1 -1
  60. package/build/consumer/records/types.d.ts +4 -4
  61. package/build/consumer/records/types.d.ts.map +1 -1
  62. package/build/consumer/records.d.ts.map +1 -1
  63. package/build/consumer/records.js +16 -13
  64. package/build/consumer/records.js.map +1 -1
  65. package/build/consumer/service.d.ts +2 -2
  66. package/build/consumer/service.d.ts.map +1 -1
  67. package/build/consumer/service.js +28 -21
  68. package/build/consumer/service.js.map +1 -1
  69. package/build/consumer/types.d.ts +1 -4
  70. package/build/consumer/types.d.ts.map +1 -1
  71. package/build/consumer/types.local.d.ts +1 -9
  72. package/build/consumer/types.local.d.ts.map +1 -1
  73. package/build/consumer/withdrawal/types.d.ts +14 -12
  74. package/build/consumer/withdrawal/types.d.ts.map +1 -1
  75. package/build/consumer/withdrawal.d.ts.map +1 -1
  76. package/build/consumer/withdrawal.js +55 -71
  77. package/build/consumer/withdrawal.js.map +1 -1
  78. package/build/index.d.ts +12 -6
  79. package/build/index.d.ts.map +1 -1
  80. package/build/index.js +7 -4
  81. package/build/index.js.map +1 -1
  82. package/build/paygate/providers.d.ts +13 -0
  83. package/build/paygate/providers.d.ts.map +1 -0
  84. package/build/paygate/providers.js +38 -0
  85. package/build/paygate/providers.js.map +1 -0
  86. package/build/paygate/registry.d.ts +6 -0
  87. package/build/paygate/registry.d.ts.map +1 -0
  88. package/build/paygate/registry.js +37 -0
  89. package/build/paygate/registry.js.map +1 -0
  90. package/build/paygate/types.d.ts +577 -0
  91. package/build/paygate/types.d.ts.map +1 -0
  92. package/build/{plugins/session → paygate}/types.js.map +1 -1
  93. package/build/plan/types.d.ts +6 -1
  94. package/build/plan/types.d.ts.map +1 -1
  95. package/build/plan.d.ts.map +1 -1
  96. package/build/plan.js +16 -2
  97. package/build/plan.js.map +1 -1
  98. package/build/plugins/checkout-policy/types.d.ts +5 -3
  99. package/build/plugins/checkout-policy/types.d.ts.map +1 -1
  100. package/build/plugins/checkout-policy.d.ts.map +1 -1
  101. package/build/plugins/checkout-policy.js +5 -3
  102. package/build/plugins/checkout-policy.js.map +1 -1
  103. package/build/plugins/consts.local.d.ts +8 -10
  104. package/build/plugins/consts.local.d.ts.map +1 -1
  105. package/build/plugins/consts.local.js +2 -19
  106. package/build/plugins/consts.local.js.map +1 -1
  107. package/build/plugins/customer-lock/types.d.ts +2 -2
  108. package/build/plugins/customer-lock/types.d.ts.map +1 -1
  109. package/build/plugins/customer-lock.js +2 -2
  110. package/build/plugins/customer-lock.js.map +1 -1
  111. package/build/plugins/estimate/cache.js +1 -1
  112. package/build/plugins/estimate/cache.js.map +1 -1
  113. package/build/plugins/estimate/types.d.ts +10 -10
  114. package/build/plugins/estimate/types.d.ts.map +1 -1
  115. package/build/plugins/estimate.d.ts.map +1 -1
  116. package/build/plugins/estimate.js +48 -122
  117. package/build/plugins/estimate.js.map +1 -1
  118. package/build/plugins/events/types.d.ts +17 -10
  119. package/build/plugins/events/types.d.ts.map +1 -1
  120. package/build/plugins/events.d.ts +6 -5
  121. package/build/plugins/events.d.ts.map +1 -1
  122. package/build/plugins/events.js +162 -173
  123. package/build/plugins/events.js.map +1 -1
  124. package/build/plugins/fx/types.d.ts +10 -21
  125. package/build/plugins/fx/types.d.ts.map +1 -1
  126. package/build/plugins/fx.d.ts +1 -1
  127. package/build/plugins/fx.d.ts.map +1 -1
  128. package/build/plugins/fx.js +17 -54
  129. package/build/plugins/fx.js.map +1 -1
  130. package/build/plugins/portal/types.d.ts +8 -37
  131. package/build/plugins/portal/types.d.ts.map +1 -1
  132. package/build/plugins/portal.d.ts.map +1 -1
  133. package/build/plugins/portal.js +38 -208
  134. package/build/plugins/portal.js.map +1 -1
  135. package/build/plugins/refunds/types.d.ts +11 -11
  136. package/build/plugins/refunds/types.d.ts.map +1 -1
  137. package/build/plugins/refunds.d.ts.map +1 -1
  138. package/build/plugins/refunds.js +14 -39
  139. package/build/plugins/refunds.js.map +1 -1
  140. package/build/plugins/snapshot/types.d.ts +11 -0
  141. package/build/plugins/snapshot/types.d.ts.map +1 -0
  142. package/build/plugins/snapshot/types.js +2 -0
  143. package/build/plugins/snapshot/types.js.map +1 -0
  144. package/build/plugins/snapshot.d.ts +4 -0
  145. package/build/plugins/snapshot.d.ts.map +1 -0
  146. package/build/plugins/snapshot.js +19 -0
  147. package/build/plugins/snapshot.js.map +1 -0
  148. package/build/plugins/subscriptions/types.d.ts +17 -17
  149. package/build/plugins/subscriptions/types.d.ts.map +1 -1
  150. package/build/plugins/subscriptions.d.ts +4 -4
  151. package/build/plugins/subscriptions.d.ts.map +1 -1
  152. package/build/plugins/subscriptions.js +69 -77
  153. package/build/plugins/subscriptions.js.map +1 -1
  154. package/build/plugins/types.local.d.ts +9 -43
  155. package/build/plugins/types.local.d.ts.map +1 -1
  156. package/build/plugins/webhook-manager/types.d.ts +15 -43
  157. package/build/plugins/webhook-manager/types.d.ts.map +1 -1
  158. package/build/plugins/webhook-manager.d.ts +3 -3
  159. package/build/plugins/webhook-manager.d.ts.map +1 -1
  160. package/build/plugins/webhook-manager.js +21 -199
  161. package/build/plugins/webhook-manager.js.map +1 -1
  162. package/build/protocol.d.ts +1 -1
  163. package/build/protocol.d.ts.map +1 -1
  164. package/build/protocol.js +1 -1
  165. package/build/protocol.js.map +1 -1
  166. package/build/service.d.ts +11 -11
  167. package/build/service.d.ts.map +1 -1
  168. package/build/service.js +59 -23
  169. package/build/service.js.map +1 -1
  170. package/build/sync/types.d.ts +17 -13
  171. package/build/sync/types.d.ts.map +1 -1
  172. package/build/sync.d.ts.map +1 -1
  173. package/build/sync.js +22 -122
  174. package/build/sync.js.map +1 -1
  175. package/build/types.d.ts +46 -101
  176. package/build/types.d.ts.map +1 -1
  177. package/build/utils/types.d.ts +0 -8
  178. package/build/utils/types.d.ts.map +1 -1
  179. package/build/utils.d.ts +1 -4
  180. package/build/utils.d.ts.map +1 -1
  181. package/build/utils.js +1 -15
  182. package/build/utils.js.map +1 -1
  183. package/package.json +20 -22
  184. package/src/access/types.ts +7 -16
  185. package/src/access.ts +7 -15
  186. package/src/actions/resync.ts +5 -5
  187. package/src/actions/webhook.ts +8 -4
  188. package/src/bootstrap/types.ts +13 -7
  189. package/src/bootstrap.ts +23 -13
  190. package/src/catalogue/types.ts +3 -3
  191. package/src/catalogue.ts +4 -8
  192. package/src/checkout/types.ts +21 -0
  193. package/src/checkout.ts +414 -0
  194. package/src/config.ts +19 -66
  195. package/src/consts.ts +3 -69
  196. package/src/consumer/cancellation/types.ts +6 -4
  197. package/src/consumer/cancellation.ts +13 -7
  198. package/src/consumer/capture/types.ts +8 -12
  199. package/src/consumer/capture.ts +50 -59
  200. package/src/consumer/index.ts +4 -0
  201. package/src/consumer/reconcile.ts +69 -68
  202. package/src/consumer/records/types.ts +4 -4
  203. package/src/consumer/records.ts +19 -14
  204. package/src/consumer/service.ts +35 -22
  205. package/src/consumer/types.local.ts +1 -8
  206. package/src/consumer/types.ts +1 -4
  207. package/src/consumer/withdrawal/types.ts +14 -12
  208. package/src/consumer/withdrawal.ts +61 -77
  209. package/src/index.ts +12 -6
  210. package/src/paygate/providers.ts +48 -0
  211. package/src/paygate/registry.ts +53 -0
  212. package/src/paygate/types.ts +640 -0
  213. package/src/plan/types.ts +6 -1
  214. package/src/plan.ts +21 -3
  215. package/src/plugins/checkout-policy/types.ts +5 -3
  216. package/src/plugins/checkout-policy.ts +6 -5
  217. package/src/plugins/consts.local.ts +2 -26
  218. package/src/plugins/customer-lock/types.ts +2 -2
  219. package/src/plugins/customer-lock.ts +2 -2
  220. package/src/plugins/estimate/cache.ts +1 -1
  221. package/src/plugins/estimate/types.ts +10 -10
  222. package/src/plugins/estimate.ts +52 -128
  223. package/src/plugins/events/types.ts +17 -9
  224. package/src/plugins/events.ts +172 -190
  225. package/src/plugins/fx/types.ts +10 -23
  226. package/src/plugins/fx.ts +28 -64
  227. package/src/plugins/portal/types.ts +8 -38
  228. package/src/plugins/portal.ts +48 -229
  229. package/src/plugins/refunds/types.ts +11 -11
  230. package/src/plugins/refunds.ts +16 -40
  231. package/src/plugins/snapshot/types.ts +11 -0
  232. package/src/plugins/snapshot.ts +22 -0
  233. package/src/plugins/subscriptions/types.ts +17 -17
  234. package/src/plugins/subscriptions.ts +81 -81
  235. package/src/plugins/types.local.ts +9 -33
  236. package/src/plugins/webhook-manager/types.ts +15 -43
  237. package/src/plugins/webhook-manager.ts +24 -220
  238. package/src/protocol.ts +1 -1
  239. package/src/service.ts +66 -30
  240. package/src/sync/types.ts +17 -13
  241. package/src/sync.ts +25 -143
  242. package/src/types.ts +47 -97
  243. package/src/utils/types.ts +0 -9
  244. package/src/utils.ts +2 -20
  245. package/tests/capabilities.spec.ts +219 -0
  246. package/tests/entitlement.spec.ts +4 -4
  247. package/tests/gate-handlers.spec.ts +6 -6
  248. package/tests/gate.spec.ts +2 -2
  249. package/tests/grants.spec.ts +2 -2
  250. package/tests/internal-plan.spec.ts +2 -2
  251. package/tests/limit-gate.spec.ts +2 -2
  252. package/tests/paygates.spec.ts +132 -0
  253. package/tests/protocol.spec.ts +4 -5
  254. package/tests/usage.spec.ts +2 -2
  255. package/tests/webhook.spec.ts +137 -0
  256. package/build/plugins/session/types.d.ts +0 -34
  257. package/build/plugins/session/types.d.ts.map +0 -1
  258. package/build/plugins/session.d.ts +0 -4
  259. package/build/plugins/session.d.ts.map +0 -1
  260. package/build/plugins/session.js +0 -71
  261. package/build/plugins/session.js.map +0 -1
  262. package/build/plugins/status.d.ts +0 -8
  263. package/build/plugins/status.d.ts.map +0 -1
  264. package/build/plugins/status.js +0 -21
  265. package/build/plugins/status.js.map +0 -1
  266. package/build/plugins/stripe/types.d.ts +0 -20
  267. package/build/plugins/stripe/types.d.ts.map +0 -1
  268. package/build/plugins/stripe.d.ts +0 -6
  269. package/build/plugins/stripe.d.ts.map +0 -1
  270. package/build/plugins/stripe.js +0 -518
  271. package/build/plugins/stripe.js.map +0 -1
  272. package/src/plugins/session/types.ts +0 -30
  273. package/src/plugins/session.ts +0 -86
  274. package/src/plugins/status.ts +0 -22
  275. package/src/plugins/stripe/types.ts +0 -20
  276. package/src/plugins/stripe.ts +0 -571
  277. package/tests/checkout-consumer.spec.ts +0 -366
  278. package/tests/checkout-locks.spec.ts +0 -161
  279. package/tests/checkout-plugins.spec.ts +0 -164
  280. package/tests/checkout.spec.ts +0 -313
  281. package/tests/consumer-events.spec.ts +0 -215
  282. package/tests/consumer-fixtures.ts +0 -141
  283. package/tests/consumer-ops.spec.ts +0 -361
  284. package/tests/consumer-rights.integration.spec.ts +0 -147
  285. package/tests/consumer-rights.spec.ts +0 -606
  286. package/tests/context.ts +0 -110
  287. package/tests/estimate.spec.ts +0 -350
  288. package/tests/events.spec.ts +0 -367
  289. package/tests/fake-stripe.ts +0 -1004
  290. package/tests/gateway-options.spec.ts +0 -180
  291. package/tests/portal.spec.ts +0 -202
  292. package/tests/sync.spec.ts +0 -114
  293. package/tests/usage.integration.spec.ts +0 -165
  294. package/tests/webhook-manager.spec.ts +0 -149
  295. /package/build/{plugins/session → checkout}/types.js +0 -0
  296. /package/build/{plugins/stripe → paygate}/types.js +0 -0
@@ -1,37 +1,33 @@
1
1
  ---
2
2
  name: server-payment
3
- description: Public in-process Stripe gateway for OwlMeans backends — amount and quantity checkout, subscriptions, the checkout plugin seam (per-entity narrowing, admission, holds), protocol-bound webhook routes, product sync with per-currency prices, fulfillment observers, entitlement gates, internal plan grants and revokes, entitlement grants (payment-grant units and capabilities beside the plan), and the EU consumer-rights service (country lock, purchases and withdrawal windows, spend consent, subscription start requests, the withdrawal and cancellation functions with automatic refunds and credit notes, durable-medium mails, reconcile). Use when wiring @owlmeans/server-payment or changing Stripe payment behavior.
3
+ description: Public provider-agnostic paygate host for OwlMeans backends — payment providers registered per context (PaymentProvider / Paygate capabilities, ensurePaymentProviders, paygatesOf, forSale, the defined reaction to every absent capability, the boot feature checks), amount and quantity checkout, subscriptions, the checkout plugin seam (per-entity narrowing, admission, holds), protocol-bound webhook routes dispatching neutral paygate events, the catalogue sync with per-currency prices, fulfillment observers, entitlement gates, internal plan grants and revokes, entitlement grants (payment-grant units and capabilities beside the plan), and the EU consumer-rights service (country lock, purchases and withdrawal windows, spend consent, subscription start requests, the withdrawal and cancellation functions with automatic refunds and credit notes, durable-medium mails, reconcile). Use when wiring @owlmeans/server-payment, writing a payment provider, or changing payment behavior.
4
4
  user-invocable: false
5
5
  ---
6
6
  <!-- AUTO-GENERATED — do not edit. Regenerate via sync-agent-meta. -->
7
7
 
8
8
  # @owlmeans/server-payment
9
9
 
10
- **Install:** `bun add @owlmeans/server-payment@^0.1.21`
10
+ **Install:** `bun add @owlmeans/server-payment@^0.2.0-alpha.0`
11
11
 
12
- Public MIT package. It embeds Stripe into an application backend and owns everything between
13
- Stripe and an entity's entitlements: the subscription store, one-time fulfillments, the usage
14
- ledger of counted limits, plan resolution, the two gate services, Stripe's own configuration
15
- (products, prices, the portal, the webhook endpoint) and the EU consumer-rights records and
16
- functions. The application owns its catalogue, what a purchase is worth to it (credits,
17
- provisioning), its usage meter and its side effects. Contracts — plans, limits, promos, the
18
- entitlement view, the consumer-rights views, calculators, copy and refusals — are
19
- `@owlmeans/payment`; the model across packages is the `entitlements` skill. Field lists, the
20
- service contract and the step-by-step algorithms are in the `reference` part
21
- ([parts/reference.md](parts/reference.md)).
12
+ Public MIT package. It embeds payments into an application backend and owns everything between a
13
+ paygate and an entity's entitlements: the subscription store, one-time fulfillments, the usage
14
+ ledger of counted limits, plan resolution, the two gate services, the paygate bootstrap (products,
15
+ prices, the portal, the webhook endpoint — each delegated to the paygate) and the EU consumer-rights
16
+ records and functions. **It names no paygate and depends on none**: a paygate is a payment provider
17
+ package (OwlMeans connect) registered in the context. The application owns its catalogue, what a
18
+ purchase is worth to it (credits, provisioning), its usage meter and its side effects. Contracts —
19
+ plans, limits, promos, the entitlement view, the consumer-rights views, calculators, copy and
20
+ refusals — are `@owlmeans/payment`; the model across packages is the `entitlements` skill. Field
21
+ lists, the service contract and the step-by-step algorithms are in the `reference` part
22
+ ([parts/reference.md](parts/reference.md)); a provider's own SDK behaviour is its package's skill.
22
23
 
23
24
  ## Wiring
24
25
 
25
26
  ```typescript
26
- stripeSecrets(cfg, { api: '/secrets/stripe-key' }) // webhook secret: optional override
27
- portalBranding(cfg, { returnUrl: 'https://app.example.com/billing', headline: 'Example' })
28
27
  declarePaymentPricing(cfg, { // absent entirely: today's fixed behaviour, unchanged
29
28
  tax: { automatic: true, behavior: TaxBehavior.Exclusive, collectTaxId: true, estimate: true },
30
- currency: { adaptive: true, adaptiveFeeRate: 0.04, estimate: true }, // the fee is optional: see "Price sync and the tax estimate"
31
- stripe: { settlementCurrency: 'eur', subscriptionPaymentMethodTypes: ['card', 'link', 'klarna'],
32
- subscriptionPaymentMethodTypesByCurrency: { usd: ['card', 'link'] },
33
- lockCustomerEmail: true, lockCustomerCountry: true }, // optional: see "Customer locks"
34
- })
29
+ currency: { adaptive: true, adaptiveFeeRate: 0.04, estimate: true }, // the fee is optional: see "The estimate"
30
+ }) // `tax` and `currency` only — a provider declares its own settings
35
31
  declareConsumerRights(cfg, { // absent: no consumer-rights behaviour at all
36
32
  textVersion: 'terms-2026-09', links: { en: { billingTerms, withdrawalInformation, withdrawalFunction, cancellation } },
37
33
  currencies: { eu: 'eur', other: 'usd' },
@@ -48,7 +44,8 @@ declarePaymentPlan(cfg, { productSku: 'app-plans', sku: 'pro-monthly', rank: 10,
48
44
  withdrawal: { components: [{ key: 'services', basis: 'time', shareMinor: 1000 },
49
45
  { key: 'credits', basis: 'units', shareMinor: 1000 }] }, capabilities: […] })
50
46
 
51
- appendPaymentGatewayService(context) // the process that talks to Stripe
47
+ appendMyPaygate(context) // a provider package's `append…` — in EVERY process, before or after the gateway
48
+ appendPaymentGatewayService(context) // the process that talks to the paygates
52
49
  appendPaymentGatewayService(context, { manage: false }) // a worker that only reads entitlements and asserts consent
53
50
  // One deployment, several managed processes on one database: the same owner and webhookService everywhere
54
51
  appendPaymentGatewayService(context, { owner: 'app-api', webhookService: 'app-hooks' }) // receives the webhook, bootstraps at boot
@@ -72,61 +69,105 @@ paymentAccessOf(context).observer().onSubscription(async event => { /* keyed by
72
69
  ```
73
70
 
74
71
  - `appendPaymentGatewayService` registers twelve resources, the catalogue service
75
- (`PAYMENT_SERVICE`), the completion observer, the gateway (`GATEWAY_SERVICE`), the capability
76
- gate (`ENTITLEMENT_GATE`), the limit gate (`LIMIT_GATE`), the entitlement service
77
- (`ENTITLEMENT_SERVICE`) and the consumer-rights service (`CONSUMER_RIGHTS_SERVICE`), each only
78
- when not registered already. `appendConsumerRights` does the consumer-rights part alone.
79
- - **Registration order is free.** Whichever of `appendConsumerRights` and the gateway comes first,
80
- `usage` and `stripe` are installed on the one service, and `manage` resolves as the application's
81
- explicit value, else the gateway's, else managed. The consumer-rights resources keep the aliases
82
- of the first registration.
83
- - **The consumer-rights service is lazy** (like the completion observer): `paymentAccessOf(ctx).consumerRights()`,
84
- `useMeter` and `useMailRenderer` work while the application is wired; the gateway's initialization
85
- initializes it, so its boot checks still run at boot. The gateway is NOT lazy: `paymentAccessOf(ctx).gateway()` (and
72
+ (`PAYMENT_SERVICE`), the payment providers service (`PAYMENT_PROVIDERS`), the completion observer,
73
+ the gateway (`GATEWAY_SERVICE`), the capability gate (`ENTITLEMENT_GATE`), the limit gate
74
+ (`LIMIT_GATE`), the entitlement service (`ENTITLEMENT_SERVICE`) and the consumer-rights service
75
+ (`CONSUMER_RIGHTS_SERVICE`), each only when not registered already. `appendConsumerRights` does the
76
+ consumer-rights part alone.
77
+ - **Registration order is free.** Whichever of `appendConsumerRights`, the provider and the gateway
78
+ comes first, `usage` is installed on the one service and `manage` resolves as the application's
79
+ explicit value, else the gateway's, else managed. The consumer-rights resources keep the aliases of
80
+ the first registration.
81
+ - **The consumer-rights service and the providers service are lazy** (like the completion observer):
82
+ `paymentAccessOf(ctx).consumerRights()`, `useMeter`, `useMailRenderer` and a provider's registration
83
+ work while the application is wired; the gateway's initialization initializes the consumer rights, so
84
+ its boot checks still run at boot. The gateway is NOT lazy: `paymentAccessOf(ctx).gateway()` (and
86
85
  `.use(plugin)`) needs the initialized context.
87
- - **`manage: false`** registers the same surface with no Stripe client: no bootstrap at init, and
88
- `createLink`, `portalLink`, `resyncSubscription`, `resyncAll`, the webhook route, `withdraw` and
89
- `cancel` throw `PaygateError('unmanaged')`. `grantInternalPlan`, `revokeInternalPlan`, the
90
- entitlement grants, the entitlement service,
91
- `amountPolicy`, `planPrices` and the consumer-rights reads, `recordConsent`,
92
- `recordStartRequest` and `assertConsent` work, because they are Mongo only.
93
- - **Three keys of a deployment's Stripe state**, each a `PaymentGatewayOptions` field, each read
94
- back on the gateway (`paymentAccessOf(ctx).gateway().webhookService / owner / bootstrap`):
86
+ - **`manage: false`** registers the same surface without talking to a paygate: no bootstrap at init,
87
+ and `createLink`, `portalLink`, `estimatePrice`, `resyncSubscription`, `resyncAll`, the webhook
88
+ route, `withdraw` and `cancel` throw `PaygateError('unmanaged')`. `grantInternalPlan`,
89
+ `revokeInternalPlan`, the entitlement grants, the entitlement service, `amountPolicy`, `planPrices`
90
+ and the consumer-rights reads, `recordConsent`, `recordStartRequest` and `assertConsent` work,
91
+ because they are Mongo only. Register the provider there too: the webhook route resolves the paygate
92
+ first, and the boot checks its features.
93
+ - **Three keys of a deployment's paygate state**, each a `PaymentGatewayOptions` field, each read back
94
+ on the gateway (`paymentAccessOf(ctx).gateway().webhookService / owner / bootstrap`):
95
95
  - `webhookService` (default `cfg.service`) — the `cfg.services` alias whose host and base form
96
- `webhookOf(ctx).webhookUrlOf`, the portal's deployment key too. Name the process that RECEIVES the webhook
97
- (the one serving `paymentGate`) in every process, so every bootstrap computes one URL.
96
+ `webhookOf(ctx).webhookUrlOf(paygate)` (`/<base>/payment-gate/webhook/<paygate>`), the portal's
97
+ deployment key too (`webhookOf(ctx).deploymentOf(paygate)` = `{ owner, webhookUrl }`). Name the
98
+ process that RECEIVES the webhook (the one serving `paymentGate`) in every process, so every
99
+ bootstrap computes one URL.
98
100
  - `owner` (default `cfg.service`) — the `payment-webhook` rows' `service`, the signing-secret
99
- lookup, the endpoint's `owlmeans:<owner>` description and `service` metadata, the
100
- `portal:<owner>` fingerprint and the portal's `service` metadata. One value in every process of
101
- the database, so each finds and replaces the others' rows.
102
- - `bootstrap` (default: `manage`) — run `stripeBootstrapOf(ctx).bootstrapStripe` at boot. Exactly one kind of process
103
- keeps it (the receiver). A managed process with `bootstrap: false` still serves checkout, the
104
- portal, estimates, the resyncs and the webhook route, and a FORCED bootstrap (`resync`, an
105
- application's maintenance `stripeBootstrapOf(ctx).bootstrapStripe(stripe, { force: true })`) still runs there —
106
- same URL, same rows, fingerprinted, so idempotent from any process.
101
+ lookup and the labels a paygate puts on its own objects. One value in every process of the
102
+ database, so each finds and replaces the others' rows.
103
+ - `bootstrap` (default: `manage`) — run `paygateBootstrapOf(ctx).bootstrap()` at boot. Exactly one
104
+ kind of process keeps it (the receiver). A managed process with `bootstrap: false` still serves
105
+ checkout, the portal, estimates, the resyncs and the webhook route, and a FORCED bootstrap
106
+ (`resync`, an application's maintenance `paygateBootstrapOf(ctx).bootstrap({ force: true })`)
107
+ still runs there — same URL, same rows, fingerprinted, so idempotent from any process.
107
108
  - Refused at construction: `bootstrap: true` with `manage: false`, an empty `owner` or
108
109
  `webhookService` (`PaygateError`). A managed, bootstrapping gateway fails its initialization when
109
110
  `webhookService` is not declared in `cfg.services` (`WebhookSetupError('service:<alias>')`).
110
- - `stripe` (a `StripeFactory`, default `paymentAccessOf(ctx).stripeClient`) is the gateway's own Stripe client —
111
- `paymentAccessOf(ctx).gateway().stripe(ctx)`, used by its methods, its boot bootstrap and the `paymentGate` handlers.
112
- The consumer-rights service takes its own (`appendConsumerRights({ stripe })`).
111
+ - **Boot checks** (gateway initialization): a declared policy feature a registered paygate lacks
112
+ fails the boot — `tax.automatic` → `automaticTax`, `tax.collectTaxId` → `taxIdCollection`,
113
+ `currency.adaptive` → `adaptiveCurrency`, the consumer-rights `checkoutTerms` → `termsConsent`
114
+ (`PaygateError('feature:<flag>:<paygate>')`); a managed, bootstrapping gateway with no provider
115
+ registered fails (`PaygateError('provider:none')`), a managed one without bootstrap only warns.
113
116
  - Every process that registers the gateway runs the collection validators (`collMod`) of all
114
117
  twelve records at init: a process of an older version narrows the validators again, so roll
115
118
  the processes of one deployment out together.
116
119
  - Gateway methods take the stable `entityId`. A public handler resolves it from its request
117
120
  entity first; protocol bodies carry `entitySlug`.
118
- - A value in `stripeSecrets` / `portalBranding` that starts with `/` is read from that file at
119
- boot, and a missing file fails the boot — so leave `webhook` out unless the file exists.
121
+
122
+ ## The paygate contract
123
+
124
+ A provider implements `PaymentProvider { id, features, bind(ctx): Paygate }` (`paygate/types.ts`) and
125
+ is registered with `ensurePaymentProviders(ctx).register(provider)` — one registered under a taken id
126
+ replaces it. `paygatesOf(ctx)` binds each provider once per context: `find(id)` (or `null`), `get(id)`
127
+ (`UnknownPaygate`), `all()` in registration order, and `forSale(product, plan, requested?)` — the
128
+ paygates the plan is sold through (`planHelper.isSoldThrough`) that can sell it (a recurring plan needs
129
+ `subscriptions`), narrowed to `requested`. `paymentAccessOf(ctx).paygates()` is the same registry.
130
+
131
+ `features` (`PaygateFeatures`): `automaticTax`, `taxIdCollection`, `adaptiveCurrency`, `termsConsent`,
132
+ `customTextMax?` (the host refuses a longer text, `ConsumerRightsError('copy:length:<field>')`),
133
+ `sessionTtl?` (the plugins' lifetime is clamped into it; absent, a session takes none). The paygate
134
+ always has `settlementCurrency()`, `customers` (`ensure`, `retrieve`, `setCountry`, `locks`) and
135
+ `checkout` (`createSession`, `expireSession`, `units`, `listCompleted?`); every other capability has a
136
+ defined host reaction to its absence:
137
+
138
+ | Absent | Host reaction |
139
+ |---|---|
140
+ | `subscriptions` | a recurring plan is not for sale through it; resync skips its rows; a subscription withdrawal is `review`; a cancellation is only received |
141
+ | `payments` | every withdrawal of its purchases is `review` (no paygate call); refunds and disputes resolve without charge or invoice reads |
142
+ | `payments.creditNotes` | a withdrawal refunds proportionally, without a corrective document |
143
+ | `webhook` | its route throws `PaygateError('capability:webhook')`; the bootstrap skips the endpoint |
144
+ | `catalogue` | the product sync skips it; a quantity or subscription checkout throws `ProductError('price:<lookup key>')` |
145
+ | `portal` | `portalLink` throws `PortalUnavailable('paygate')`; the bootstrap skips the configuration |
146
+ | `tax` | an estimate answers `at-checkout` |
147
+ | `fx` | a conversion between two currencies throws `PaygateError('fx-rate:<from>:<to>')`; an estimate has no local line |
148
+ | `checkout.listCompleted` | the consumer-rights reconcile backfills no purchase |
149
+
150
+ Every call that moves money or ends a contract carries a `PaygateCall { idempotencyKey, comment? }`:
151
+ the host computes the keys (`withdrawal:<id>:<step>[:<attempt>]`, `cancellation:<id>:schedule[:<attempt>]`)
152
+ and the notes (`withdrawal:<id>`, `cancellation:<id>`). What the host reads back is neutral data —
153
+ `CheckoutSnapshot`, `PaygateSubscription` (the status already mapped to `SubscriptionStatus`),
154
+ `PaygateInvoice`, `PaygateCharge`, `PaygateRefund`, `PaygateDispute` — and a webhook delivery is
155
+ verified by the paygate into ordered `PaygateEvent`s (`customer`, `checkout`, `subscription`, `invoice`,
156
+ `refund`, `dispute`). A provider reaches the host's stores through `paymentAccessOf(ctx)`
157
+ (`paygateCustomers`, `paymentWebhooks`, `fingerprints`, `pluginConfig`), `consumerRecordsOf(ctx)` and
158
+ `webhookOf(ctx)`; its own settings are its own plugin records.
120
159
 
121
160
  ## Declaring plans
122
161
 
123
162
  - **`rank`** orders a product's plans; a higher rank is an upgrade. A safe integer `>= 0`; absent
124
163
  reads as `0`.
125
164
  - **The free plan is a plan**: `free: true`, `price: 0`, no `gateways`. It is never synchronized to
126
- Stripe and never checked out; an entity without an entitling subscription resolves to it.
127
- - `gateways` names the paygates a plan is sold through; absent inherits the product's.
165
+ a paygate and never checked out; an entity without an entitling subscription resolves to it.
166
+ - `gateways` names the paygates a plan is sold through; absent inherits the product's, and neither
167
+ declared means EVERY registered paygate (`declarePaymentProduct` no longer defaults it). An empty
168
+ list sells it through none.
128
169
  - **`currencyPrices`** (`{ usd: 20 }`, major units, lowercase codes) are exact prices in further
129
- currencies, synced as the reusable Price's `currency_options`; a declared price in the Price's
170
+ currencies, synced as further currencies of the reusable price; a declared price in the price's
130
171
  default currency replaces its converted amount. Only for recurring and quantity plans.
131
172
  - **`withdrawal.components`** state the separately priced parts of a subscription for a withdrawal
132
173
  (CJEU C-641/19): `{ key, basis: 'time' | 'units', shareMinor }`, the shares summing to
@@ -144,18 +185,18 @@ paymentAccessOf(context).observer().onSubscription(async event => { /* keyed by
144
185
 
145
186
  ## Records
146
187
 
147
- None declares an ObjectId reference: `entityId` is an organization key and every other id is Stripe's.
188
+ None declares an ObjectId reference: `entityId` is an organization key and every other id is the paygate's; every row of a paygate carries its id in `paygate`.
148
189
 
149
190
  | Collection | One row per | Indexes |
150
191
  |---|---|---|
151
- | `payment-paygate-customer` | Stripe customer (`country`, `currency` from its webhooks; `deletedAt`) | `{paygate, externalId}` unique · `{paygate, entityId}` · `{paygate, profileId}` |
152
- | `payment-subscription` | subscription: `sub_…`, `free:<entityId>`, `internal:<planSku>:<entityId>` (+ `currency` and the checkout evidence) | `{paygate, externalId}` unique · `{entityId, status, rank:-1}` · `{entityId, planSku}` · `{paygate, customerId}` · `{paygate, itemId}` sparse · `{paygate, status, updatedAt}` |
192
+ | `payment-paygate-customer` | paygate customer (`country`, `currency` from its events; `deletedAt`) | `{paygate, externalId}` unique · `{paygate, entityId}` · `{paygate, profileId}` |
193
+ | `payment-subscription` | subscription: a paygate's id, `free:<entityId>`, `internal:<planSku>:<entityId>` (+ `currency` and the checkout evidence) | `{paygate, externalId}` unique · `{entityId, status, rank:-1}` · `{entityId, planSku}` · `{paygate, customerId}` · `{paygate, itemId}` sparse · `{paygate, status, updatedAt}` |
153
194
  | `payment-fulfillment` | one-time checkout session (+ evidence: country, e-mail, totals, terms, `purchaseId`) | `{paygate, externalId}` unique · `{paygate, paymentIntentId}` sparse · `{paygate, chargeId}` sparse · `{entityId, createdAt:-1}` |
154
195
  | `payment-webhook` | managed webhook endpoint of an owner (`service` = the gateway's `owner`; `secret` is `secure: true`) | `{paygate, service, url}` unique |
155
196
  | `payment-usage` | usage event — the ledger | `{entityId, limitKey, eventKey}` unique · `{entityId, limitKey, window}` · `{entityId, limitKey, ref}` sparse · `{entityId, createdAt:-1}` |
156
197
  | `payment-usage-counter` | (entity, limit, window) projection | `{entityId, limitKey, window}` unique |
157
198
  | `payment-grant` | entitlement grant beside the plan: `kind` (`units` / `capability`), `limitKey`, `capability`, `amount`, `used`, `startsAt`, `endsAt?`, `status` (`active` / `revoked`), `ref`, `note`, `revokedAt` | (§ Entitlement grants) |
158
- | `payment-fingerprint` | synchronized product (`<productSku>`, with `prices[]`) or portal (`portal:<owner>`) | `{sku}` unique |
199
+ | `payment-fingerprint` | synchronized product (`<productSku>`, with `prices[]` — one paygate syncs a product) or a paygate's own fingerprint (its portal configuration) | `{sku}` unique |
159
200
  | `payment-billing-profile` | organization: the billing country fixed at the first purchase | `{entityId}` unique · `{paygate, customerId}` sparse |
160
201
  | `payment-purchase` | purchase = contract + withdrawal window (a paid one-time checkout, a subscription's first invoice) | `{purchaseId}` unique · `{contractRef}` unique · `{entityId, deadline:-1}` · `{entityId, purchasedAt:-1}` · `{sessionId}` unique sparse · `{paygate, subscriptionId}` · `{invoiceId}` · `{invoiceNumber}` · `{paygate, paymentIntentId}` |
161
202
  | `payment-consumer-consent` | append-only: a performance consent or a subscription start request | `{entityId, decidedAt:-1}` · `{kind, entityId, planSku, decidedAt:-1}` |
@@ -175,118 +216,78 @@ None declares an ObjectId reference: `entityId` is an organization key and every
175
216
 
176
217
  ## Checkout
177
218
 
178
- - `Amount`: one inline `price_data` item for the synchronized product, quantity 1, its
179
- `tax_behavior` the declared `PricingPolicy.tax.behavior`. Promotion-code entry defaults off;
180
- `declarePaymentPricing({ stripe: { amountPromotionCodes: true }, … })` enables it for amount
181
- sessions in that deployment. Discounts reduce payment, never the selected `amountMinor` or its
182
- original charge metadata. `Quantity`: the
183
- reusable price under the plan lookup key, adjustable quantity. Subscription: `planSku` (else the
184
- product's first recurring plan), quantity 1. One-time Sessions enable `invoice_creation`.
185
- - `CreateLinkParams.locale` is a caller-validated Stripe locale (Session `locale`, the Customer's
186
- `preferred_locales`). `submitText` is trusted application copy — a string, or a function of
187
- `CheckoutTextContext {language, currency, unitAmountMinor, interval, region, country}` — on
188
- every mode; never caller-provided text.
189
- - A plan the paygate does not sell is refused (`ProductError`). `checkoutOptions` puts automatic
190
- tax, billing address collection, tax-id collection and Adaptive Pricing on the session exactly
191
- as `PricingPolicy` declares them.
192
- - Subscription methods come from `stripe.subscriptionPaymentMethodTypesByCurrency[chargeCurrency]`,
193
- falling back to `subscriptionPaymentMethodTypes`; with neither, Stripe selects dynamically.
194
- Currency keys and method names normalize to lowercase. Currency keys must have three letters;
195
- method lists must be nonempty and unique. Choose account-supported methods for each currency:
196
- a method the account cannot accept in that currency rejects the whole session.
197
- - **Without a consumer-rights policy every session is what it always was**: the charge currency
198
- is the settlement currency (FX from the catalogue), Adaptive Pricing as declared.
219
+ `gateway.createLink(ctx, params)` (`checkoutOf(ctx).createCheckoutLink`): the plans of the product
220
+ for sale through some paygate (`params.paygate` narrows), the named plan (else the product's first
221
+ recurring plan, a consumable's first plan), the paygate `forSale` answers first — a plan no paygate
222
+ sells is `ProductError('plan:<sku>')`, none at all `ProductError('plan')`. The host decides the whole
223
+ session and hands the paygate a `SessionInput`; the paygate only translates it.
224
+
225
+ - `Amount`: one inline line at the charge amount (`checkoutPricingHelper.chargeAmountMinor`, the
226
+ declared `tax.behavior`), the policy narrowed by the plugins first. `Quantity`: the reusable price
227
+ under the plan lookup key (`catalogue.price`), adjustable quantity. Subscription: the plan's reusable
228
+ price, quantity 1, and the subscription's own metadata.
229
+ - `CreateLinkParams.locale` is a caller-validated locale the paygate supports. `submitText` is
230
+ trusted application copy — a string, or a function of `CheckoutTextContext {language, currency,
231
+ unitAmountMinor, interval, region, country}` — on every mode; never caller-provided text.
232
+ - `automaticTax` / `collectTaxId` / `adaptiveCurrency` exactly as `PricingPolicy` declares them
233
+ (`adaptiveCurrency` only when the charge currency is the settlement currency), `keepAddress` when the
234
+ saved address carries the locked or pinned country and is tax-locatable.
235
+ - **Metadata** (session; a subscription's own too): `pricingMode`, `currency`, `entityId`,
236
+ `profileId?`, `service`, `productSku`, `planSku`; an amount checkout's `amountCurrency`,
237
+ `amountMinor`, `sourceChargeAmountMinor`, `chargeAmountMinor`; under a consumer-rights policy below.
238
+ The checkout events read them back — they are the host's, never a paygate's.
239
+ - **Without a consumer-rights policy every session is what it always was**: the charge currency is the
240
+ settlement currency (FX through the paygate's `fx`), local-currency pricing as declared.
199
241
 
200
242
  ### Under a consumer-rights policy
201
243
 
202
244
  - **The country.** A locked billing profile overrides `params.country`; another declared country is
203
245
  `BillingCountryLocked` (409), and so is a saved customer address that left the locked country
204
246
  (an operator relocks). An organization that already paid before its country was locked is
205
- locked lazily from its Stripe customer's address (`source: 'customer'`). Before any lock, the
206
- declared country is prefilled on a customer without an address.
247
+ locked lazily from its paygate customer's address (`source: 'customer'`). Before any lock, the
248
+ declared country is preselected on a customer without an address (`customers.setCountry(…, { replace: false })`).
207
249
  - **The currency.** Charge currency = the profile's currency, else `consumerRegionHelper.chargeCurrencyOf(region)`
208
250
  (`policy.currencies`). An amount checkout whose policy currency IS the charge currency is
209
- charged exactly — no FX call; any other goes through the FX reference rate (rounded up). A
210
- subscription or quantity session is forced to the charge currency (`currency`) only when its
211
- synced Price carries it (default or option) — otherwise it is left to Stripe and warned.
212
- `adaptive_pricing.enabled` is explicitly true only when the policy enables it and the charge
213
- currency is the settlement currency; every other session sends false. Omitting the flag lets
214
- Stripe inherit the Dashboard setting and can enable localization for an exact USD checkout.
215
- - **The lock at Stripe.** A locked profile whose customer carries the address:
216
- `customer_update.address: 'never'` and `billing_address_collection: 'auto'` (tax follows the
217
- saved address, Checkout cannot move it); `name: 'auto'` stays. A locked customer without a
218
- tax-locatable address (`stripeSessionHelper.isTaxLocatable`) keeps `'auto'`/`'required'`, or Stripe refuses the
219
- session ("Automatic tax calculation in Checkout requires a valid address on the Customer").
220
- - **Terms.** `mechanisms.checkoutTerms` puts `consent_collection.terms_of_service: 'required'` and
221
- `custom_text.terms_of_service_acceptance` (the `checkout.terms-acceptance.in-scope | other` copy
222
- with the billing language's links, ≤ 1200 characters) on every session.
223
- - **A missing Dashboard terms URL never breaks a payment.** Stripe refuses the checkbox then
224
- (`invalid_request_error`, param `consent_collection[terms_of_service]`, "You cannot collect consent
225
- to your terms of service unless a URL is set in the Stripe Dashboard", matched by
226
- `stripeSessionHelper.isMissingTermsUrl`): the session is created ONCE more without `consent_collection` and without the
227
- terms text, under the same plugin admissions, metadata `termsCollected: 'false'`; a
228
- `checkout-terms-fallback` event (`recordKind: 'checkout'`, `recordId` = the entity, `externalId`
229
- = the session, `ok: false`, the Stripe message in `detail`) is appended per fallback and one
230
- `warn` log per context tells the operator what to set. Any other refusal is not retried; a
231
- failing retry releases the admissions and propagates its own error.
251
+ charged exactly — no FX call; any other goes through the paygate's FX reference rate (rounded up). A
252
+ subscription or quantity session is forced to the charge currency only when its synced price
253
+ carries it (default or further currency) — otherwise it is left to the paygate and warned.
254
+ - **Terms.** `mechanisms.checkoutTerms` puts the terms checkbox (`collectTerms`) with the
255
+ `checkout.terms-acceptance.in-scope | other` copy and the billing language's links on every session.
256
+ A paygate may create the session without it when its own account cannot collect it — then the
257
+ metadata says `termsCollected: 'false'` and it audits a `checkout-terms-fallback` event.
232
258
  - **Texts.** An in-scope top-up without `submitText` says what it buys (`checkout.top-up`, with the
233
259
  country's name); a subscription without `submitText` shows the renewal price in the charge
234
- currency (`checkout.renewal.<interval>`), and `after_submit` links the cancellation page while
235
- that mechanism is on. Every text is asserted ≤ 1200 characters.
260
+ currency (`checkout.renewal.<interval>`), and the after-submit text links the cancellation page while
261
+ that mechanism is on. Every text is asserted within the paygate's `customTextMax`.
236
262
  - **Start requests.** A subscription needs a fresh start request bound to the organization, the
237
263
  plan and the current text version (`assertStartRequest` → `SubscriptionStartRequired`, 428),
238
264
  unless the organization is already locked outside the territories — a country picked before
239
- checkout may differ from the address typed at Stripe.
240
- - **Metadata** (session and `subscription_data`): `region`, `country`, `language`, `termsVersion`,
241
- `copyVersion`, `termsCollected` (`'true'` when the checkbox is on the session, `'false'` when the
242
- policy has it off or after the fallback), `ipCountry` (the `cf-ipcountry` the app passes),
243
- `startRequestId`, `profileId`, `countryPinned` (`'true'` only under `lockCustomerCountry` when the
265
+ checkout may differ from the address typed at the paygate.
266
+ - **Metadata**: `region`, `country`, `language`, `termsVersion`, `copyVersion`, `termsCollected`
267
+ (`'true'` when the checkbox is on the session), `ipCountry` (the `cf-ipcountry` the app passes),
268
+ `startRequestId`, `countryPinned` (`'true'` only under the paygate's customer country lock when the
244
269
  session kept the pinned address). The purchase's `termsAccepted` comes only from the completed
245
- session's `consent.terms_of_service` — absent when nothing was collected.
246
-
247
- ### Amount promotion codes and free completions
248
-
249
- - Coupons apply to the existing single grossed-up line, processing adjustment included; Stripe
250
- computes tax after the discount. `amount_subtotal` remains the original pre-discount base;
251
- `amount_total` records the discounted, tax-inclusive payment, including an explicit zero.
252
- - A completed amount session with promotion codes enabled, a positive base subtotal fully covered
253
- by `total_details.amount_discount`, zero tax and zero total fulfills for `no_payment_required`
254
- as well as `paid`. Currency, subtotal and credit-value metadata checks still apply. Fulfillment
255
- keeps the full selected credits and the existing session idempotency key; no PaymentIntent or
256
- invoice is required for a free redemption. Purchase backfill uses the same completion predicate.
257
- - A zero-total top-up keeps its purchase receipt and country lock but has no monetary withdrawal
258
- deadline, spending-consent window or refundable amount. Discounted paid purchases use the actual
259
- payment for proportional refunds. Keep the original invoice-line basis in credit notes: Stripe
260
- applies the invoice discount itself, once. `DisputeEvent.paidMinor` is the actual charge total in
261
- dispute currency, including tax; an absent value retains the consumer's legacy fallback.
262
-
263
- ### Customer locks (`declarePaymentPricing` → `stripe`)
264
-
265
- Both are opt-in, backend-only, read per call from the Stripe pricing plugin config, and work with
266
- or without a consumer-rights policy.
267
-
268
- - **`lockCustomerEmail`** — every `createLink` must pass `CreateLinkParams.email` (the application's
269
- verified e-mail of the buyer), else `PaygateError('customer-email')` before any Stripe call. It is
270
- written to the Stripe customer (created with it, or updated — case-insensitively different — in
271
- the same call as `preferred_locales`), never as `customer_email`: Checkout shows a customer's
272
- valid e-mail read-only, and only while the customer has none asks for one and saves it. The
273
- customer carries the LAST payer's e-mail (invoices and renewals go there). Without the lock
274
- `email` is ignored.
275
- - **`lockCustomerCountry`** — the known country (the locked profile's, else `params.country`) is
276
- written to the customer as a country-only address (lines and postal code cleared) when the saved
277
- one carries no or another country — over another country only before any lock (a locked
278
- customer's other country is still `BillingCountryLocked`). When the saved address is
279
- tax-locatable the session keeps it (`customer_update.address: 'never'`, collection `'auto'`):
280
- no address form, tax on the pinned country; Stripe still shows the card form's "Country or
281
- region" picker (a payment-method detail no parameter hides), which then moves neither tax nor the
282
- saved address. Metadata `countryPinned: 'true'` makes the first completed purchase lock THAT
283
- country (`lockFromSession`: `metadata.country` before `customer_details.address.country`).
284
- - **Tax-locatable** (`stripeSessionHelper.isTaxLocatable`, from Stripe's customer-locations table): a country alone
285
- everywhere except US (needs `postal_code`) and CA / IN (`postal_code` or `state`). A pinned US,
286
- CA or IN customer without one is not kept: Checkout collects the address — country editable —
287
- and the purchase locks what was typed, as without the option.
288
- - **The portal** never offers `email` under `lockCustomerEmail`, nor `address` under
289
- `lockCustomerCountry` (or `countryLock`); both flags are in its fingerprint.
270
+ session's own terms acceptance — absent when nothing was collected.
271
+
272
+ ### Free completions
273
+
274
+ A completed amount checkout with promotion codes enabled, a positive subtotal fully discounted, zero
275
+ tax and a zero total fulfills (`checkoutSnapshotHelper.canFulfill`) as a paid one does; currency,
276
+ subtotal and credit-value metadata checks still apply, fulfillment keeps the full selected credits.
277
+ A zero-total top-up keeps its purchase receipt and country lock but has no monetary withdrawal
278
+ deadline, spending-consent window or refundable amount; a discounted paid purchase refunds
279
+ proportionally to the actual payment. `DisputeEvent.paidMinor` is the actual charge total.
280
+
281
+ ### Customer locks (`customers.locks()`, provider configuration)
282
+
283
+ - **E-mail** — every `createLink` must pass `CreateLinkParams.email` (the application's verified
284
+ e-mail of the buyer), else `PaygateError('customer-email')` before any paygate call; it is passed to
285
+ `customers.ensure`, which pins it on the paygate customer. Without the lock `email` is ignored.
286
+ - **Country** — the known country (the locked profile's, else `params.country`) is written to the
287
+ customer as a country-only address (`setCountry(…, { replace: true })`) when the saved one carries no
288
+ or another country — over another country only before any lock. When the saved address is
289
+ tax-locatable the session keeps it (`keepAddress`): tax on the pinned country, and metadata
290
+ `countryPinned: 'true'` makes the first completed purchase lock THAT country.
290
291
 
291
292
  ## Checkout plugins
292
293
 
@@ -299,59 +300,47 @@ registry: a plugin whose `alias` is registered already replaces it). All hooks a
299
300
  | `admit(ctx, CheckoutAttempt)` | before the session, every mode | throw (`CheckoutLimitExceeded`) to veto; may return `{ reservationId }` |
300
301
  | `created(ctx, CheckoutCreated)` | after the session | gets `sessionId`, `url`, `expiresAt`, amounts, its own `reservationId`; a throw expires the session, releases every hold and propagates |
301
302
  | `settled(ctx, CheckoutSettled)` | webhook: `paid`, `expired`, `failed`; and `failed` for a checkout that never became usable | errors are logged, never raised |
302
- | `sessionTtlSeconds` | — | the smallest declared, clamped to 30 min – 24 h, becomes `expires_at`; none declared: Stripe's default |
303
+ | `sessionTtlSeconds` | — | the smallest declared, clamped into the paygate's `features.sessionTtl`, becomes the session's `expiresAt`; none declared, or a paygate without bounds: its own default |
303
304
 
304
305
  - **One narrowing path.** `createLink` and `gateway.amountPolicy(ctx, entityId, productSku,
305
306
  planSku?)` both call `checkoutPluginsOf(ctx).narrowAmountFor` → `amountNarrowingHelper.narrowAmountPolicy` (`@owlmeans/payment`); an amount
306
307
  above the narrowed maximum, or any amount while `blocked`, is `CheckoutLimitExceeded` (409). A
307
308
  control and a refusal cannot disagree. An amount above the plan's own maximum stays the base
308
309
  policy's error.
309
- - A veto, a Stripe refusal or a throwing `created` releases what the earlier plugins admitted
310
+ - A veto, a paygate refusal, a session without a URL or a throwing `created` (the fresh session is
311
+ expired first) releases what the earlier plugins admitted
310
312
  (`settled` with `outcome: 'failed'` and their `reservationId`).
311
313
  - `gateway.planPrices(ctx, productSku)` answers `PlanPriceView[]` (a default entry per Price plus
312
- one per currency option) from the synced fingerprint rows — no Stripe call.
313
-
314
- ## Price sync and the tax estimate
315
-
316
- - `productSyncOf(ctx).syncStripeProducts` gives a matching, still-`unspecified` price the declared `tax.behavior` IN
317
- PLACE and a fresh one on creation; a price carrying the OPPOSITE behavior is replaced. Before an
318
- in-place update it checks the account's tax-settings default and skips — logging why — when that
319
- would change existing renewals, unless `stripe.migrateUnspecifiedPrices` opts in.
320
- - A recurring or quantity plan whose catalogue currency differs from `stripe.settlementCurrency` is
321
- converted with an unlocked FX Quote (`reference_rate`, rounded up). Its **currency options**:
322
- the declared `currencyPrices`, plus the catalogue currency (exact `round(price × 100)`) when it is
323
- one of the policy's region currencies; each option carries the declared `tax_behavior`. Active
324
- prices are listed with `expand: ['data.currency_options']`; a changed option replaces the Price
325
- (deactivate + create with `transfer_lookup_key`) — options are never edited in place, so a
326
- subscriber keeps the Price they accepted.
327
- - The resolved amounts, currencies and options are fingerprinted; an unchanged fingerprint makes no
328
- product/price call. Each sync stores the product's `prices[]` (`SyncedPrice`: price id, lookup
329
- key, default currency and amount, options, tax behavior, interval, source amount) on the
330
- fingerprint row — what `planPrices`, checkout currency forcing and the estimate read. A row from
331
- before `prices[]` existed syncs once more.
332
- - `estimatePrice` (`plugins/estimate.ts`) is a Stripe Tax calculation for one product/plan's
333
- reference amount at a country — **$0.05 per distinct** (currency, country, amount, tax code,
334
- behavior, matching tax ids) combination, cached per gateway-service instance for 24h; failures
335
- are never cached. **A locked profile overrides the requested country** (`source: 'profile'`,
336
- `locked: true`); the estimate carries `region`. Under a policy with region currencies a
337
- recurring plan is estimated in the charge currency at its synced unit amount (default or
338
- option); the `local` line (FX Quotes, a PREVIEW endpoint) only when the session's CHARGE currency
339
- (the region's, or the locked profile's) is the settlement currency — the same test the session's
340
- `adaptive_pricing` takes. An amount plan stays estimated in its policy currency but is charged in
341
- the region's currency, so an EU top-up gets its local line through the policy → settlement →
342
- local chain, and an exact-USD one none.
343
- - **The local line prices the conversion the way Checkout does.** Adaptive Pricing shows a buyer's
344
- currency at the quote's `base_rate` plus its own conversion fee (`price × (1 + fee)`, Stripe's 2–4%,
345
- decided per currency — test mode showed 4% for PLN: `1 EUR = 4.5626 PLN = 1 / 0.227941 × 1.04`),
346
- while the FX Quotes `exchange_rate` is `base_rate × (1 − fx_fee_rate)` with the quote's 2% — so it
347
- understates Checkout (99.11 against 101.02 PLN for a €22.14 total). `currency.adaptiveFeeRate`
348
- declares that fee: `local.exchangeRate` = `base_rate / (1 + fee)` (and `fxFeeRate` = the fee),
349
- divided by the source's reference rate for an amount plan, so a subscription and a top-up share the
350
- one rule. Absent, `local.exchangeRate` is the quote's own `exchange_rate`. A buyer whose local
351
- currency IS the settlement currency pays no conversion fee and gets none. `StripeFxRate.baseRate`
352
- is `rate_details.base_rate` (derived from `exchange_rate` and `fx_fee_rate` when absent); the fee
353
- is part of the FX cache key. The fee Stripe really applies is not exposed by any API — probe it by
354
- reading a test-mode Checkout page ("includes N% conversion fee") and set the declared value.
314
+ one per further currency) from the synced fingerprint rows — no paygate call.
315
+
316
+ ## Catalogue sync and the estimate
317
+
318
+ - `productSyncOf(ctx).syncProducts(paygate)` — for every product with a plan sold through the paygate:
319
+ a recurring or quantity plan whose catalogue currency differs from the paygate's settlement currency
320
+ is converted at its FX reference rate (rounded up); its **further currencies** are the declared
321
+ `currencyPrices`, plus the catalogue currency (exact `round(price × 100)`) when it is one of the
322
+ policy's region currencies. The resolved amounts, currencies, options and the declared tax behavior
323
+ are fingerprinted; an unchanged fingerprint makes no paygate call. Otherwise `catalogue.syncProduct`
324
+ brings the product and its prices to the declaration (the paygate keeps a subscriber's accepted
325
+ price) and the host stores the product's `prices[]` (`SyncedPrice`: price id, lookup key, default
326
+ currency and amount, options, tax behavior, interval, source amount) on the fingerprint row — what
327
+ `planPrices`, checkout currency forcing and the estimate read. A row from before `prices[]` existed
328
+ syncs once more. `syncPaymentProducts()` syncs every paygate.
329
+ - `estimatePrice` (`estimateOf(ctx).estimatePrice`): the paygate's `tax.calculate` for one
330
+ product/plan's reference amount at a country — cached per gateway-service instance for 24 h per
331
+ distinct (paygate, currency, country, amount, tax code, behavior, matching tax ids, exemption);
332
+ failures are never cached. **A locked profile overrides the requested country** (`source: 'profile'`,
333
+ `locked: true`); without one the paygate customer's country serves (`source: 'customer'`), its tax
334
+ ids of that country and its exemption included. The estimate carries `region`. Under a policy with
335
+ region currencies a recurring plan is estimated in the charge currency at its synced unit amount;
336
+ the `local` line only when the session's CHARGE currency is the settlement currency — the same test
337
+ the session takes. An amount plan stays estimated in its policy currency but is charged in the
338
+ region's currency, so an EU top-up gets its local line through the policy → settlement → local chain.
339
+ - **The local line prices the conversion the way checkout does.** `currency.adaptiveFeeRate`
340
+ declares the paygate's local-currency conversion fee: `local.exchangeRate` = the quote's base rate
341
+ `/ (1 + fee)` (and `fxFeeRate` = the fee), divided by the source's reference rate for an amount plan.
342
+ Absent, `local.exchangeRate` is the quote's own fee-inclusive rate. A paygate without `fx` gives no
343
+ local line; a paygate without `tax` answers `at-checkout`.
355
344
 
356
345
  ## The subscription store
357
346
 
@@ -367,19 +356,21 @@ registry: a plugin whose `alias` is registered already replaces it). All hooks a
367
356
  belongs to the row — it follows the subscription through a plan change, ends with it, and the
368
357
  free-plan fallback (no row) has none. A new overridable parameter is a new optional key of
369
358
  `SubscriptionOverrides`, declared in `PaymentSubscriptionSchema` and merged in `planHelper.overriddenPlan`.
370
- - `mapStatus`: `active`→Active, `trialing`→Trial, `past_due`→PastDue, `unpaid`/`paused`→Suspended,
371
- `incomplete`→Created, `incomplete_expired`→Ended, `canceled`→Canceled; paused collection is
372
- Suspended with `pausedAt`.
359
+ - The paygate maps its own status to `SubscriptionStatus` (`PaygateSubscription.status`, the raw word
360
+ in `externalStatus`); a paused subscription is stored with `pausedAt`. The plan is the price's plan
361
+ (`PaygateSubscription.planSku`), else `metadata.planSku`, else the row's.
373
362
  - **State is written before observers, and classified against what observers were last told**
374
363
  (`propagated`, stamped with `lastEventId` only after every observer succeeded).
375
- `CommitOptions.beforePropagate(record, change)` runs between the write and the observers — the
376
- Stripe path writes a subscription's purchase there on `created`, so the window exists before an
364
+ `CommitOptions.beforePropagate(record, change)` runs between the write and the observers — a
365
+ paygate subscription's purchase is written there on `created`, so the window exists before an
377
366
  observer grants the bundle.
378
367
  - Classification, first match: `created` · `canceled` · `paused` · `resumed` · `upgraded` /
379
368
  `downgraded` · `cancel-scheduled` · `cancel-undone` · `renewed` (once per invoice) · `past-due` ·
380
369
  `suspended` · `trial-ending`.
381
370
  - A repeated delivery (`lastEventId`) is ignored; an older payload than the stored state is not
382
- applied. `resyncSubscription` / `resyncAll` re-read and apply as a webhook would.
371
+ applied. `resyncSubscription` / `resyncAll` (`paygateSubscriptionsOf(ctx)`) re-read through each
372
+ row's paygate and apply as a webhook would; a subscription the paygate no longer has is canceled,
373
+ a row of an unregistered paygate or one without `subscriptions` is skipped.
383
374
  - **Internal plans** (`paygate: INTERNAL_PAYGATE`, row `internal:<planSku>:<entityId>`; Mongo only,
384
375
  so they work unmanaged): `gateway.grantInternalPlan(ctx, entityId, planSku, { force?, periodEnd? })`
385
376
  upserts the row — the free plan, or any plan with `force: true` (else `ProductError`); `periodEnd`
@@ -433,7 +424,7 @@ units or a capability beside its plan:
433
424
  ## Entitlements and gates
434
425
 
435
426
  - `paymentAccessOf(ctx).entitlements()` → `effectivePlan`, `entitlements` (the `EntitlementView`), `hasCapability`,
436
- `limitState`, the ledger operations. Never calls Stripe.
427
+ `limitState`, the ledger operations. Never calls a paygate.
437
428
  - **Capability gate** (`ENTITLEMENT_GATE`) passes when the view grants ANY parameter; **limit gate**
438
429
  (`LIMIT_GATE`) when any `limit:<key>[>=n]` has room — it never consumes. Both refuse with
439
430
  `AuthForbidden` refusals (403) and fail closed on an unreadable store.
@@ -447,8 +438,9 @@ first purchase. The service is `paymentAccessOf(ctx).consumerRights()` (`.consum
447
438
  full contract is in the `reference` part ([parts/reference.md](parts/reference.md)).
448
439
 
449
440
  - **A purchase** is a paid one-time checkout, or a subscription's FIRST invoice — renewals,
450
- internal grants and manual credits never are. Its row (`purchaseId` `stripe:<cs_…>` /
451
- `stripe:<sub_…>`, `contractRef` `CR-YYMMDD-XXXXXX` over an unambiguous alphabet, retried on a
441
+ internal grants and manual credits never are. Its row (`purchaseId` `<paygate>:<checkout session id>` /
442
+ `<paygate>:<subscription id>` — `consumerRecordsOf(ctx).purchaseIdOf(paygate, id)`, `contractRef`
443
+ `CR-YYMMDD-XXXXXX` over an unambiguous alphabet, retried on a
452
444
  collision) is written **before anything is granted**: in `checkout.session.completed` before
453
445
  `onTopUp`, in the first subscription commit before the `created` observers. A completed
454
446
  subscription checkout then refines it with the buyer's own country, e-mail, totals and terms
@@ -459,9 +451,10 @@ full contract is in the `reference` part ([parts/reference.md](parts/reference.m
459
451
  - **The lock**: the first completed purchase's `customer_details.address.country` (else the
460
452
  declared one) locks the profile — first write wins through the unique index; a later different
461
453
  country is a `lock-mismatch` event, never a relock. The request's `cf-ipcountry` is stored as
462
- `ipCountry` beside it, and the `lock` event flags `ipMismatch`. The profile's currency is an
463
- entitling Stripe subscription's currency when one exists (two subscriptions of one customer can
464
- not differ), else the region's. Only `lock(entityId, country, 'manual', { force: true, by,
454
+ `ipCountry` beside it, and the `lock` event flags `ipMismatch`. The profile records the paygate it
455
+ came from (`LockOptions.paygate`, default the first registered). Its currency is an entitling paygate
456
+ subscription's currency when one exists (two subscriptions of one customer can not differ), else the
457
+ region's. Only `lock(entityId, country, 'manual', { force: true, by,
465
458
  reason })` replaces a lock, audited as `relock`.
466
459
  - **Unlock** (an operator, Mongo only — unmanaged works): `unlock(entityId, { by, reason })` deletes
467
460
  the profile (only while it still holds the country read) and appends an `unlock` event carrying the
@@ -488,20 +481,21 @@ full contract is in the `reference` part ([parts/reference.md](parts/reference.m
488
481
  - **Withdrawal** (`withdraw(subject | null, body, origin)`, managed only): in-app by `purchaseId`,
489
482
  public by contract reference or invoice number plus an e-mail of the purchase, its profile or
490
483
  its paygate customer. The declaration and the conditional `withdrawnAt` are written BEFORE
491
- Stripe; the receipt is mailed at once; then the paygate steps under
484
+ the paygate; the receipt is mailed at once; then the paygate steps under
492
485
  `withdrawal:<id>:<step>` keys; then `onWithdrawal`. The refund comes from the application's
493
486
  `UsageMeter` through the `@owlmeans/payment` calculators (deduction `usedAfter + settled +
494
- clawed`); no meter, or `automaticRefunds` off, is `review` (no paygate call). A late
487
+ clawed`); no meter, `automaticRefunds` off, or a paygate that cannot execute it (no `payments`; no
488
+ `subscriptions` for a subscription purchase) is `review` (no paygate call). A late
495
489
  declaration is `expired` — recorded and acknowledged, nothing executed. A repeated one answers
496
490
  the original receipt. The public answer is always the bare `DeclarationReceipt`.
497
491
  - **Cancellation** (`cancel(subject | null, body, origin)`): in-app the organization's entitling
498
- Stripe subscription; public a contract reference plus e-mail, else the one organization whose
499
- paygate customer has that e-mail. Ordinary → `cancel_at_period_end`, or `cancel_at` a later
500
- boundary (`cancellationEffectiveAt`, no proration); already scheduled → `already-scheduled`;
492
+ paygate subscription; public a contract reference plus e-mail, else the one organization whose
493
+ paygate customer has that e-mail. Ordinary → `subscriptions.scheduleCancel` at the period end, or at
494
+ a later boundary (`cancellationEffectiveAt`, no proration); already scheduled → `already-scheduled`;
501
495
  **extraordinary → `review`, the paygate untouched** (an operator decides, the receipt says so).
502
496
  - **Observers `onConsent` / `onWithdrawal` / `onCancellation` run AFTER the records and the paygate
503
497
  steps; a throw is recorded (`observers` event) and retried by `reconcile()` — unlike the paygate
504
- callbacks, whose throw makes Stripe redeliver.** A `WithdrawalEvent` with `status: 'refunded'`
498
+ callbacks, whose throw makes the paygate redeliver.** A `WithdrawalEvent` with `status: 'refunded'`
505
499
  carries `units.returned` — take exactly those back; `review` means an operator refunds later,
506
500
  and that refund arrives as an ordinary `RefundEvent`.
507
501
  - **`RefundEvent.withdrawalId`**: a refund this package made for a withdrawal carries
@@ -534,23 +528,28 @@ mailer is registered.
534
528
  paygate steps of withdrawals (refund, credit note, subscription cancel) and scheduled
535
529
  cancellations, failed mails and failed observers; backfills purchases (records only, no mail) from
536
530
  completed sessions of the last 16 days without a row; locks organizations that paid before the
537
- lock from their paygate customer (never one an operator unlocked). A retry uses a fresh idempotency key (`…:<attempt>`; Stripe
538
- replays a stored failure for a day) and first adopts a refund or credit note an earlier attempt
539
- made (found by `metadata.withdrawalId`). Five failures of a step leave it to an operator. At most
531
+ lock from their paygate customer (never one an operator unlocked). A retry uses a fresh idempotency key (`…:<attempt>`; a paygate
532
+ may replay a stored failure) and first adopts a refund or credit note an earlier attempt
533
+ made (`payments.findRefund` / `creditNotes.find` by `metadata.withdrawalId`). The backfill reads each
534
+ paygate's `checkout.listCompleted`. Five failures of a step leave it to an operator. At most
540
535
  `limit` (50) items per step.
541
536
 
542
537
  ## Protocols, handlers and security
543
538
 
544
- - `paymentGate` (bound by `paymentGateEntrypoints`): `webhook` is public because Stripe signs the
545
- untouched raw body — never put an application guard on it; `resync` and `resyncSubscriptions`
546
- carry `GUARD_ED25519`.
539
+ - `paymentGate` (bound by `paymentGateEntrypoints`): `webhook` (`/payment-gate/webhook/:paygate`) is
540
+ public because the paygate signs the untouched raw body — never put an application guard on it. It
541
+ resolves the paygate FIRST (`UnknownPaygate` for an unregistered id), then refuses an unmanaged
542
+ gateway (`PaygateError('unmanaged')`) and a paygate without `webhook`
543
+ (`PaygateError('capability:webhook')`), lets the paygate verify the delivery
544
+ (`PaygateSignatureError`, 400) and applies its events in order (`paymentEventsOf(ctx).apply`).
545
+ `resync` and `resyncSubscriptions` carry `GUARD_ED25519`.
547
546
  - **An application that declares the gate itself** — its own aliases, every route pinned to the
548
547
  service that receives the webhook — binds its declarations to `paymentGateHandlers` (`webhook`,
549
548
  `resync`, `resyncSubscriptions`) with `bind(own.webhook, paymentGateHandlers.webhook)` from
550
549
  `@owlmeans/server-entrypoint` / `@owlmeans/server-app`, and never registers `paymentGate` or
551
550
  `paymentGateEntrypoints`. A handler reads its context from the entrypoint it is bound to, so the
552
551
  application's declaration is the one mounted and run. Its declarations keep the library's paths
553
- (`webhookOf(ctx).webhookUrlOf` forms the Stripe URL from `paymentGate`'s), contracts (`PaygateParams`,
552
+ (`webhookOf(ctx).webhookUrlOf(paygate)` forms the paygate's URL from `paymentGate`'s), contracts (`PaygateParams`,
554
553
  `ResyncResult`, `ResyncSubscriptionsResult` — `bind` refuses another shape at compile time) and
555
554
  guards. Two ways to get it wrong: `bindAll(declarations, [paymentGateHandlers.webhook])` pairs by
556
555
  object identity and leaves the application's declaration without a handler, and
@@ -573,73 +572,50 @@ made (found by `metadata.withdrawalId`). Five failures of a step leave it to an
573
572
  `cf-connecting-ip` → the LAST `x-forwarded-for` entry → `x-real-ip` → the socket; the raw
574
573
  `x-forwarded-for`, `user-agent` (≤ 512), `cf-ipcountry`, `accept-language`.
575
574
 
576
- ## Stripe self-management
577
-
578
- Runs in `initialize()` of a managed gateway with `bootstrap` (default), after the context is
579
- ready, and on a forced `stripeBootstrapOf(ctx).bootstrapStripe` from any managed process; each step independent: products
580
- and prices (above), the portal configuration, the webhook endpoint. A deployment's identity is its
581
- webhook URL (`webhookOf(ctx).webhookUrlOf()`: the `webhookService` alias's host and base); its rows carry the
582
- `owner`.
583
-
584
- - **The portal configuration**: customer update (tax id; email unless `stripe.lockCustomerEmail`;
585
- address unless `mechanisms.countryLock` or `stripe.lockCustomerCountry`), invoice history,
586
- payment method update, cancellation at period end without proration, price switching between the
587
- active recurring prices. Its fingerprint covers the catalogue (incl. `currencyPrices`), the lock
588
- flags, the region currencies, the branding and the deployment key. Each deployment owns its own configuration, tagged `{ owlmeans: 'payment',
589
- service: <owner>, deployment: webhookOf(ctx).webhookUrlOf() }`; one tagged for another deployment (a former
590
- webhook URL included) is never touched — a moved URL creates a new configuration.
591
- - `portalLink(ctx, entityId, { flow, planSku?, returnUrl })`: a customer is required
592
- (`PortalUnavailable`, 409); `Cancel`/`Update`/`Change` need an entitling Stripe subscription.
593
- - **The webhook endpoint** at `webhookOf(ctx).webhookUrlOf()`, subscribed to `WEBHOOK_EVENTS`, on the API version
594
- read back from the client; only an https public host. A deployment deletes only the endpoints its
595
- own rows name. A new URL (a moved host, a new `webhookService`) creates the endpoint there, then
596
- deletes the endpoints of the owner's rows at other URLs and those rows — no migration step. The
597
- secret (create-only) is stored field-encrypted where the database has a key; the receiver reads
598
- the newest row of its `owner`.
599
- - **Do not bump the Stripe SDK** (17.x, API `2025-02-24.acacia`): `current_period_*`,
600
- `invoice.subscription`, `invoice.payment_intent`, `charge.invoice` are top-level there and move
601
- later; credit notes link a refund by `refund`; `presentment_details` is untyped. Read them through
602
- narrow accessors.
603
- - **Dashboard prerequisites** (test and live): a terms-of-service URL in Settings → Public details
604
- before `checkoutTerms` is on (without it every checkout falls back to no checkbox — payments go on,
605
- but the acceptance is not collected: watch for `checkout-terms-fallback` events); Checkout's return/refund
606
- policy off or pointing at the Billing Terms, never "no refunds"; business name, address and
607
- support e-mail in Public details; the "successful payments" and "refunds" customer e-mails.
575
+ ## The paygate bootstrap
576
+
577
+ `paygateBootstrapOf(ctx).bootstrap({ force? })` runs in `initialize()` of a managed gateway with
578
+ `bootstrap` (default), after the context is ready, and on a forced run from any managed process. For
579
+ every registered paygate, each step on its own (one failing is logged and does not block the others),
580
+ each capability the paygate lacks skipped: the products and prices (`productSyncOf(ctx).syncProducts`),
581
+ the portal configuration (`portal.ensureConfiguration(deploymentOf(paygate))`), the webhook endpoint
582
+ (`webhook.ensureEndpoint(deploymentOf(paygate))` — only for an https public host; a local one is
583
+ logged `payment.webhook.unmanaged` and skipped). A deployment's identity is its webhook URL; its rows
584
+ carry the `owner`. `resync` forgets every fingerprint first. What a paygate does in each step
585
+ (endpoints, signing secrets, configurations shared by deployments of one account) is its provider's.
608
586
 
609
587
  ## Event dispatch
610
588
 
611
- | Event | Persisted | Observer · event key |
589
+ | Paygate event | Persisted | Observer · event key |
612
590
  |---|---|---|
613
- | `customer.created` / `.updated` | customer upsert (`country`, `currency`) | — |
614
- | `customer.deleted` | customer `deletedAt` | — |
615
- | `checkout.session.completed` / `.async_payment_succeeded`, `payment` mode, paid | lock + purchase + confirmation mail, fulfillment (+ evidence), `fulfilledAt` after observers | `onTopUp` · session id; plugins `settled('paid')` |
616
- | same, `subscription` mode | subscription applied if no webhook did (purchase in its first commit), purchase refined, lock, subscription evidence, confirmation mail | plugins `settled('paid')` |
617
- | `checkout.session.async_payment_failed` | fulfillment `failedAt` | `onPaymentFailed {kind:'checkout'}` · `payment-failed:<session>:0`; `settled('failed')` |
618
- | `checkout.session.expired` | unfulfilled fulfillment purged | plugins `settled('expired')` |
619
- | `customer.subscription.created` / `.updated` / `.pending_update_*` / `.paused` / `.resumed` | subscription applied (+ `currency`) | `onSubscription` · classified |
620
- | `customer.subscription.deleted` | applied as Canceled + `endedAt` | `canceled` |
621
- | `customer.subscription.trial_will_end` | applied | `trial-ending` |
622
- | `invoice.paid` | cycle invoice ⇒ re-read, applied as a renewal; otherwise `latestInvoiceId` | `renewed` |
623
- | `invoice.payment_failed` / `.payment_action_required` | re-read and applied | classified, then `onPaymentFailed {kind:'invoice'}` · `payment-failed:<invoice>:<attempt>` |
624
- | `invoice.upcoming` | nothing | — |
625
- | `invoice.marked_uncollectible` / `invoice.voided` | re-read and applied / `latestInvoiceId` | classified / — |
626
- | `charge.refunded`, `refund.created` / `.updated` (succeeded) | fulfillment `refundedMinor`/`refundedAt`; purchase `refundedMinor`, `refundedAt` on a whole refund | `onRefund` · `refund:<refund>` (`metadata`, `withdrawalId`) |
627
- | `refund.failed` | — | — |
628
- | `charge.dispute.*` | target `disputedAt`, `disputeStatus` | `onDispute {phase}` · `dispute:<dispute>:<phase>` |
629
-
630
- A refund or dispute resolves to its target by payment intent (fulfillment), by charge, by invoice
631
- (the subscription whose latest invoice it is, else the invoice's subscription); a subscription
632
- refund touches the purchase only when it is of the purchase's own (first) invoice.
591
+ | `customer` `upserted` / `deleted` | customer upsert (`country` upper, `currency` lower) / `deletedAt` | — |
592
+ | `checkout` `completed`, a one-time payment the session fulfils | lock + purchase + confirmation mail, fulfillment (+ evidence; quantity units from `checkout.units`), `fulfilledAt` after observers | `onTopUp` · session id; plugins `settled('paid')` |
593
+ | same, `subscription` mode, paid or not required | subscription applied if no event did (purchase in its first commit), purchase refined, lock, subscription evidence, confirmation mail | plugins `settled('paid')` |
594
+ | `checkout` `failed` | fulfillment `failedAt` | `onPaymentFailed {kind:'checkout'}` · `payment-failed:<session>:0`; `settled('failed')` |
595
+ | `checkout` `expired` | unfulfilled fulfillment purged | plugins `settled('expired')` |
596
+ | `subscription` | applied (+ `currency`); `deleted` as Canceled + `endedAt`; `trialEnding` | `onSubscription` · classified (`canceled`, `trial-ending`) |
597
+ | `invoice` `paid`, a renewal | re-read and applied as a renewal | `renewed` |
598
+ | `invoice` `paid`, otherwise / `voided` | `latestInvoiceId` (a voided one re-reads the subscription's) | — |
599
+ | `invoice` `payment-failed` / `action-required` | re-read and applied | classified, then `onPaymentFailed {kind:'invoice'}` · `payment-failed:<invoice>:<attempt>` |
600
+ | `invoice` `uncollectible` | re-read and applied | classified |
601
+ | `refund`, succeeded | fulfillment `refundedMinor`/`refundedAt`; purchase `refundedMinor`, `refundedAt` on a whole refund | `onRefund` · `refund:<refund>` (`metadata`, `withdrawalId`) |
602
+ | `dispute` | target `disputedAt`, `disputeStatus` | `onDispute {phase}` · `dispute:<dispute>:<phase>` |
603
+
604
+ A refund or dispute resolves to its target by payment (fulfillment), by charge, by invoice (the
605
+ subscription whose latest invoice it is, else the invoice's subscription — `payments.charge`,
606
+ `payments.invoice`); a subscription refund touches the purchase only when it is of the purchase's own
607
+ (first) invoice. Work on one paygate customer is serialized in-process (`customerLockHelper`, key
608
+ `<paygate>:<customer>`).
633
609
 
634
610
  ## Observer API and idempotency keys
635
611
 
636
612
  | Callback | Payload | Key | A throw |
637
613
  |---|---|---|---|
638
- | `onTopUp` | `TopUpCompletion` | session id | Stripe redelivers |
639
- | `onSubscription` | `SubscriptionEvent` | `subscription:<id>:<change>:…` | Stripe redelivers |
640
- | `onRefund` | `RefundEvent` (+ `metadata`, `withdrawalId`) | `refund:<refund>` | Stripe redelivers |
641
- | `onDispute` | `DisputeEvent` | `dispute:<dispute>:<phase>` | Stripe redelivers |
642
- | `onPaymentFailed` | `PaymentFailedEvent` | `payment-failed:<session\|invoice>:<attempt>` | Stripe redelivers |
614
+ | `onTopUp` | `TopUpCompletion` | session id | the paygate redelivers |
615
+ | `onSubscription` | `SubscriptionEvent` | `subscription:<id>:<change>:…` | the paygate redelivers |
616
+ | `onRefund` | `RefundEvent` (+ `metadata`, `withdrawalId`) | `refund:<refund>` | the paygate redelivers |
617
+ | `onDispute` | `DisputeEvent` | `dispute:<dispute>:<phase>` | the paygate redelivers |
618
+ | `onPaymentFailed` | `PaymentFailedEvent` | `payment-failed:<session\|invoice>:<attempt>` | the paygate redelivers |
643
619
  | `onConsent` | `ConsentEvent` (`kind`, `consentId`, `purchaseIds`, `planSku`) | `consent:<id>` | recorded; `reconcile` retries |
644
620
  | `onWithdrawal` | `WithdrawalEvent` (`status`, `purchase: PurchaseRef`, `refund`, `units`, `subscriptionCanceled`) | `withdrawal:<id>` | recorded; `reconcile` retries |
645
621
  | `onCancellation` | `CancellationEvent` (`matched`, `kind`, `status`, `effectiveAt`) | `cancellation:<id>` | recorded; `reconcile` retries |
@@ -651,55 +627,21 @@ refund uses `netAmountMinor * refundedTotalMinor / paidMinor`.
651
627
  ## Testing
652
628
 
653
629
  Unit specs run a real server context — real catalogue, services and gates — over in-memory
654
- resources (unique and sparse-unique indexes, raw conditional updates) and a fake Stripe that records
655
- every SDK call and its request options (idempotency keys) and can fail a method's next calls
656
- (`state.failures`: a message, a real SDK error such as `new Stripe.errors.StripeInvalidRequestError(…)`,
657
- or a list of them, one per call), so "no Stripe call" is an assertion. `makeFakeContext` wires the
658
- consumer-rights call before the gateway by default (`gatewayFirst`, `rights` and a pre-init `wire`
659
- hook test the other orders); `gateway` passes the gateway's options (default `{ manage: false }`,
660
- the fake always its Stripe client, so a managed one boot-bootstraps against it), `service` /
661
- `host` / `base` / `services` shape `cfg.service` and `cfg.services`, and `seed` pre-fills stores
662
- (a database shared between two processes). `gate-handlers.spec.ts` binds `paymentGateHandlers`
663
- onto a re-declared, pinned gate and runs it in that process's context. The consumer-rights service there is
664
- managed through the fake (`appendConsumerRights({ manage: true, stripe })`) with a console mailer
665
- (`fake.mails`). The Mongo-gated specs prove admission under concurrency, the collection validators
666
- of every record, the unique indexes, the concurrent first lock and the single winner of
667
- concurrent withdrawals.
668
-
669
- ## External docs
670
-
671
- - https://docs.stripe.com/api/checkout/sessions/object — `amount_subtotal` precedes discounts and
672
- tax; `amount_total` follows them; a free payment can omit a PaymentIntent.
673
- - https://docs.stripe.com/payments/checkout/no-cost-orders — fulfill zero-cost orders on Checkout
674
- completion, including orders discounted by 100%.
675
- - https://docs.stripe.com/invoicing/dashboard/credit-notes#credit-balances-and-discounts — invoice
676
- discounts apply proportionally to credit-note lines; retain the original line basis.
677
-
678
- - https://docs.stripe.com/api/checkout/sessions/create — `customer`: "If the Customer already has a valid email set, the email will be prefilled and not editable in Checkout" (else Checkout saves the typed one); `customer_email` only prefills a NEW customer and cannot be combined with `customer`. Inline `price_data`; `consent_collection.terms_of_service` needs a terms URL in the Dashboard (else `invalid_request_error` on param `consent_collection[terms_of_service]`); `custom_text.{submit, after_submit, terms_of_service_acceptance}` ≤ 1200 characters each; `currency` forces a Price's currency option; `expires_at` 30 min – 24 h.
679
- - https://docs.stripe.com/tax/customer-locations — minimal tax location: country alone except US (postal code), CA and IN (postal code or province); https://docs.stripe.com/tax/checkout/page — an existing customer with `customer_update.address: 'never'` is taxed on its saved address. Verified against test mode (2026-10): a pinned DE customer keeps its VAT when the card country is switched to US; a country-only US/CA customer is refused at session creation.
680
- - https://docs.stripe.com/payments/checkout/localize-prices/manual-currency-prices — `currency_options` on a Price, one reusable Price for several currencies; manual options override Adaptive Pricing for that currency.
681
- - https://docs.stripe.com/payments/currencies/localize-prices/adaptive-pricing — Adaptive Pricing requires the price currency to be a settlement currency; webhook amounts stay in the integration currency.
682
- - https://docs.stripe.com/api/checkout/sessions/create?query=adaptive_pricing — `adaptive_pricing.enabled` defaults to the Dashboard setting when omitted; send an explicit boolean for every session.
683
- - https://docs.stripe.com/payments/klarna — Klarna eligibility depends on currency, customer location and purchase use case; verify the account's supported currencies before explicitly requesting it.
684
- - https://docs.stripe.com/invoicing/multi-currency-customers — a customer's subscriptions share one currency; one-time payments may differ.
685
- - https://docs.stripe.com/invoicing/integration/programmatic-credit-notes — preview a credit note on an invoice line; link an existing refund with `refund`; custom lines are not allowed with automatic tax.
686
- - https://docs.stripe.com/tax/reports — a refund or a credit note lowers reported tax; only the credit note is the corrective document of an issued invoice.
687
- - https://docs.stripe.com/api/refunds/create — `payment_intent`, `amount`, `reason: requested_by_customer`, `metadata`; an idempotency key replays the stored answer (failures too) for 24 h.
688
- - https://docs.stripe.com/api/subscriptions/cancel and /update — `cancel(prorate, invoice_now, cancellation_details)`; `update(cancel_at_period_end | cancel_at, proration_behavior)`.
689
- - https://docs.stripe.com/payments/checkout/receipts — one-time Checkout needs `invoice_creation.enabled` for a post-payment invoice; a Customer's `preferred_locales` localizes Stripe mails.
690
- - https://docs.stripe.com/checkout/fulfillment — fulfillment must be idempotent and support delayed-payment success events.
691
- - https://docs.stripe.com/api/webhook_endpoints/create — the signing `secret` is returned only by create; `api_version` is create-only.
692
- - https://docs.stripe.com/api/customer_portal/configurations/create — `features.customer_update.allowed_updates`, subscription cancel/update features; configurations are never deletable.
693
- - https://docs.stripe.com/api/tax/calculations/create — `percentage_decimal` is a STRING; parse it exactly.
694
- - https://docs.stripe.com/api/fx_quotes/create — a PREVIEW endpoint (`stripe.rawRequest`); `reference_rate` for settlement conversion.
695
- - https://docs.stripe.com/currencies/localize-prices/fx-quotes-api — `exchange_rate` is fee-inclusive (`base_rate × (1 − fx_fee_rate)`, 2%); dividing a price by `base_rate` is the fee-free local price.
696
- - https://docs.stripe.com/payments/currencies/localize-prices/adaptive-pricing — the buyer pays a 2–4% conversion fee that Stripe decides ("includes 4% conversion fee" on a PLN Checkout, 2026-10): the mid-market rate × (1 + fee), a different fee from the FX Quotes' `fx_fee_rate`.
630
+ resources with a fake paygate (`@owlmeans/test-payment`: `makeFakeContext`, `makeFakePaygate`; the
631
+ `test-payment` skill), so "no paygate call" and "the host asked the paygate for exactly this session"
632
+ are assertions. `paygates.spec.ts` covers the registry, `forSale` and the boot checks;
633
+ `webhook.spec.ts` the route and the dispatch; `capabilities.spec.ts` the checkout input and every
634
+ absent capability; `gate-handlers.spec.ts` binds `paymentGateHandlers` onto a re-declared, pinned
635
+ gate. A provider's SDK behaviour, its golden records and the Mongo-gated integration specs (admission
636
+ under concurrency, the collection validators, the concurrent first lock) live in the provider's
637
+ package.
697
638
 
698
639
  ## Related
699
640
 
700
641
  - [[entitlements]] — the model across packages
701
642
  - [[payment]] — the contracts: grammars, views, consumer-rights calculators, copy, refusals, factories
702
643
  - [[web-payment]] — hooks and pieces, the consumer-rights dialogs and functions
644
+ - [[test-payment]] — the harness: in-memory context, fake paygate
703
645
  - [[mailer]] — the mail transport the consumer-rights mails go through
704
646
  - [[mongo-resource]] — raw collection access, duplicate-key detection, field locking
705
647