@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,58 +1,35 @@
1
- import type Stripe from 'stripe'
2
1
  import type { Context as ApiContext } from '@owlmeans/server-api'
3
2
  import { memoHelper } from '@owlmeans/context'
4
- import { STRIPE_PAYGATE_ALIAS } from '../consts.js'
5
3
  import type { PaymentSubscriptionRecord } from '../types.js'
4
+ import type { Paygate, PaygateCharge } from '../paygate/types.js'
6
5
  import type { PaymentReference, PaymentTarget, PaymentTargetHelper } from './refunds/types.js'
7
6
  import { paymentAccessOf } from '../access.js'
8
- import { paymentUtils } from '../utils.js'
9
7
 
10
8
  export const makePaymentTargetHelper = (ctx: ApiContext): PaymentTargetHelper => {
11
9
  const access = paymentAccessOf(ctx)
12
10
 
13
- const retrieveCharge = async (stripe: Stripe, chargeId: string): Promise<Stripe.Charge | null> => {
14
- try {
15
- return await stripe.charges.retrieve(chargeId)
16
- } catch (error) {
17
- if (paymentUtils.isMissingObject(error)) {
18
- return null
19
- }
20
- throw error
21
- }
22
- }
11
+ const retrieveCharge = async (paygate: Paygate, chargeId: string): Promise<PaygateCharge | null> =>
12
+ paygate.payments != null ? await paygate.payments.charge(chargeId) : null
23
13
 
24
- const subscriptionOfInvoice = async (
25
- stripe: Stripe, invoiceId: string,
26
- ): Promise<PaymentSubscriptionRecord | null> => {
27
- const latest = await access.subscriptions().load({ paygate: STRIPE_PAYGATE_ALIAS, latestInvoiceId: invoiceId })
14
+ const subscriptionOfInvoice = async (paygate: Paygate, invoiceId: string): Promise<PaymentSubscriptionRecord | null> => {
15
+ const latest = await access.subscriptions().load({ paygate: paygate.id, latestInvoiceId: invoiceId })
28
16
  if (latest != null) {
29
17
  return latest
30
18
  }
31
- let invoice: Stripe.Invoice
32
- try {
33
- invoice = await stripe.invoices.retrieve(invoiceId)
34
- } catch (error) {
35
- if (paymentUtils.isMissingObject(error)) {
36
- return null
37
- }
38
- throw error
39
- }
40
- // `invoice.subscription` is top-level on the API version the client is pinned to.
41
- const subscriptionId = paymentUtils.idOf((invoice as unknown as { subscription?: string | { id?: string } | null }).subscription)
19
+ const invoice = paygate.payments != null ? await paygate.payments.invoice(invoiceId) : null
20
+ const subscriptionId = invoice?.subscriptionId
42
21
 
43
- return subscriptionId != null
44
- ? await access.subscriptions().byExternalId(subscriptionId, STRIPE_PAYGATE_ALIAS)
45
- : null
22
+ return subscriptionId != null ? await access.subscriptions().byExternalId(subscriptionId, paygate.id) : null
46
23
  }
47
24
 
48
- const resolvePaymentTarget = async (stripe: Stripe, ref: PaymentReference): Promise<PaymentTarget | null> => {
25
+ const resolvePaymentTarget = async (paygate: Paygate, ref: PaymentReference): Promise<PaymentTarget | null> => {
49
26
  const ledger = access.fulfillments()
50
27
  let charge = ref.charge ?? null
51
28
  let paymentIntentId = ref.paymentIntentId
52
29
  const chargeId = ref.chargeId ?? charge?.id
53
30
 
54
31
  if (paymentIntentId != null) {
55
- const record = await ledger.load({ paygate: STRIPE_PAYGATE_ALIAS, paymentIntentId })
32
+ const record = await ledger.load({ paygate: paygate.id, paymentIntentId })
56
33
  if (record != null) {
57
34
  return { kind: 'fulfillment', record, charge, paymentIntentId }
58
35
  }
@@ -60,26 +37,25 @@ export const makePaymentTargetHelper = (ctx: ApiContext): PaymentTargetHelper =>
60
37
 
61
38
  let invoiceId = ref.invoiceId
62
39
  if (chargeId != null) {
63
- const record = await ledger.load({ paygate: STRIPE_PAYGATE_ALIAS, chargeId })
40
+ const record = await ledger.load({ paygate: paygate.id, chargeId })
64
41
  if (record != null) {
65
42
  return { kind: 'fulfillment', record, charge, paymentIntentId: paymentIntentId ?? record.paymentIntentId }
66
43
  }
67
- charge = charge ?? await retrieveCharge(stripe, chargeId)
68
- const chargeIntent = paymentUtils.idOf(charge?.payment_intent)
44
+ charge = charge ?? await retrieveCharge(paygate, chargeId)
45
+ const chargeIntent = charge?.paymentId
69
46
  if (chargeIntent != null && chargeIntent !== paymentIntentId) {
70
47
  paymentIntentId = chargeIntent
71
- const byIntent = await ledger.load({ paygate: STRIPE_PAYGATE_ALIAS, paymentIntentId: chargeIntent })
48
+ const byIntent = await ledger.load({ paygate: paygate.id, paymentIntentId: chargeIntent })
72
49
  if (byIntent != null) {
73
50
  const record = byIntent.chargeId == null ? await ledger.update({ ...byIntent, chargeId }) : byIntent
74
51
  return { kind: 'fulfillment', record, charge, paymentIntentId: chargeIntent }
75
52
  }
76
53
  }
77
- // `charge.invoice` is top-level on the API version the client is pinned to.
78
- invoiceId = invoiceId ?? paymentUtils.idOf((charge as unknown as { invoice?: string | { id?: string } | null } | null)?.invoice)
54
+ invoiceId = invoiceId ?? charge?.invoiceId
79
55
  }
80
56
 
81
57
  if (invoiceId != null) {
82
- const record = await subscriptionOfInvoice(stripe, invoiceId)
58
+ const record = await subscriptionOfInvoice(paygate, invoiceId)
83
59
  if (record != null) {
84
60
  return { kind: 'subscription', record, charge, paymentIntentId, invoiceId }
85
61
  }
@@ -0,0 +1,11 @@
1
+ import type { CheckoutSnapshot } from '../../paygate/types.js'
2
+
3
+ /** What a completed checkout session alone decides — pure. */
4
+ export interface CheckoutSnapshotHelper {
5
+ /**
6
+ * Whether a one-time checkout is fulfilled: a paid payment (a zero total only outside amount mode),
7
+ * or a completed amount checkout fully covered by promotion codes — a positive subtotal discounted
8
+ * to a zero total with no tax, the codes enabled on the session.
9
+ */
10
+ canFulfill: (session: CheckoutSnapshot) => boolean
11
+ }
@@ -0,0 +1,22 @@
1
+ import { CheckoutPricingMode } from '@owlmeans/payment'
2
+ import type { CheckoutSnapshot } from '../paygate/types.js'
3
+ import type { CheckoutSnapshotHelper } from './snapshot/types.js'
4
+
5
+ export const createCheckoutSnapshotHelper = (): CheckoutSnapshotHelper => {
6
+ const canFulfill = (session: CheckoutSnapshot): boolean => {
7
+ if (session.mode !== 'payment') return false
8
+ if (session.payment === 'paid'
9
+ && (session.amountTotalMinor !== 0 || session.metadata.pricingMode !== CheckoutPricingMode.Amount)) return true
10
+
11
+ return (session.payment === 'not-required' || session.payment === 'paid')
12
+ && session.status === 'complete' && session.metadata.pricingMode === CheckoutPricingMode.Amount
13
+ && session.promotionCodes && session.amountTotalMinor === 0
14
+ && Number.isSafeInteger(session.amountSubtotalMinor) && (session.amountSubtotalMinor ?? 0) > 0
15
+ && session.amountDiscountMinor === session.amountSubtotalMinor
16
+ && session.amountTaxMinor === 0
17
+ }
18
+
19
+ return { canFulfill }
20
+ }
21
+
22
+ export const checkoutSnapshotHelper = createCheckoutSnapshotHelper()
@@ -1,39 +1,39 @@
1
- import type Stripe from 'stripe'
2
1
  import type { SubscriptionStatus } from '@owlmeans/payment'
3
2
  import type { CommitResult, SubscriptionRef } from '../../types.js'
3
+ import type { Paygate, PaygateSubscription } from '../../paygate/types.js'
4
4
 
5
5
  export interface ApplyOptions {
6
6
  source: 'webhook' | 'resync'
7
7
  eventId?: string
8
- /** `event.created` (epoch seconds) of a webhook payload; an older payload than the stored state is skipped. */
9
- eventCreated?: number
8
+ /** When the paygate produced the event; an older payload than the stored state is skipped. */
9
+ eventCreated?: Date
10
10
  renewal?: boolean
11
11
  invoiceId?: string
12
12
  trialEnding?: boolean
13
13
  /** Store this status whatever the payload says (a deleted subscription is canceled). */
14
14
  forced?: SubscriptionStatus
15
- /** The paygate client — lets the first commit read the first invoice for its purchase row. */
16
- stripe?: Stripe
17
15
  }
18
16
 
19
- /** Stripe subscriptions applied to a context's subscription rows. */
20
- export interface StripeSubscriptionsHelper {
17
+ /** Paygate subscriptions applied to a context's subscription rows. */
18
+ export interface PaygateSubscriptionsHelper {
21
19
  /**
22
- * Apply one Stripe subscription — from a webhook payload or a fresh retrieval — to its row, and
23
- * tell observers what changed. Shared by every webhook and by resync.
20
+ * Apply one paygate subscription — from a webhook payload or a fresh retrieval — to its row, and
21
+ * tell observers what changed. Shared by every webhook and by resync. The first commit of a
22
+ * subscription writes its purchase before the `created` observers hear it.
24
23
  */
25
- applySubscription: (subscription: Stripe.Subscription, opts: ApplyOptions) => Promise<CommitResult>
26
- /** A subscription by id, or `null` when Stripe no longer has it. */
27
- retrieveSubscription: (stripe: Stripe, id: string) => Promise<Stripe.Subscription | null>
24
+ applySubscription: (paygate: Paygate, subscription: PaygateSubscription, opts: ApplyOptions) => Promise<CommitResult>
25
+ /** A subscription by id, or `null` when the paygate no longer has it (or keeps no subscriptions). */
26
+ retrieveSubscription: (paygate: Paygate, id: string) => Promise<PaygateSubscription | null>
28
27
  /** A row whose paygate subscription no longer exists is canceled (observers hear `canceled`). */
29
- cancelMissing: (externalId: string) => Promise<CommitResult>
28
+ cancelMissing: (paygate: Paygate, externalId: string) => Promise<CommitResult>
30
29
  /**
31
- * Re-read paygate subscriptions — one by id, or every row of one entity — and apply each as a
32
- * webhook would. A subscription the paygate no longer has is canceled.
30
+ * Re-read paygate subscriptions — one by id, or every paygate row of one entity — and apply each as
31
+ * a webhook would. A subscription the paygate no longer has is canceled; a row of a paygate that is
32
+ * not registered, or keeps no subscriptions, is skipped.
33
33
  *
34
34
  * @returns how many rows changed
35
35
  */
36
- resyncStripeSubscription: (stripe: Stripe, ref: SubscriptionRef) => Promise<number>
36
+ resyncSubscription: (ref: SubscriptionRef) => Promise<number>
37
37
  /** Resync every paygate subscription that is not already terminal. Errors per row are logged. */
38
- resyncStripeSubscriptions: (stripe: Stripe) => Promise<{ scanned: number, updated: number }>
38
+ resyncAll: () => Promise<{ scanned: number, updated: number }>
39
39
  }
@@ -1,10 +1,9 @@
1
- import type Stripe from 'stripe'
2
- import { SubscriptionStatus, TERMINAL_STATUSES } from '@owlmeans/payment'
1
+ import { INTERNAL_PAYGATE, SubscriptionStatus, TERMINAL_STATUSES } from '@owlmeans/payment'
3
2
  import type { Context as ApiContext } from '@owlmeans/server-api'
4
3
  import { memoHelper } from '@owlmeans/context'
5
- import { STRIPE_PAYGATE_ALIAS } from '../consts.js'
6
4
  import type { CommitResult, PaymentSubscriptionRecord, SubscriptionRef } from '../types.js'
7
- import type { ApplyOptions, StripeSubscriptionsHelper } from './subscriptions/types.js'
5
+ import type { Paygate, PaygateSubscription } from '../paygate/types.js'
6
+ import type { ApplyOptions, PaygateSubscriptionsHelper } from './subscriptions/types.js'
8
7
  import { log } from '../log.js'
9
8
  import { RESYNC_PAGE } from './consts.local.js'
10
9
  import { paymentAccessOf } from '../access.js'
@@ -12,36 +11,25 @@ import { paymentUtils } from '../utils.js'
12
11
  import { catalogueOf } from '../catalogue.js'
13
12
  import { planHelper } from '../plan.js'
14
13
  import { subscriptionCommitOf } from '../commit.js'
14
+ import { paygatesOf } from '../paygate/registry.js'
15
15
  import { customerLockHelper } from './customer-lock.js'
16
- import { mapStatus } from './status.js'
17
16
  import { captureOf } from '../consumer/capture.js'
18
17
 
19
- const isPaused = (subscription: Pick<Stripe.Subscription, 'status' | 'pause_collection'>): boolean =>
20
- subscription.status === 'paused'
21
- || (subscription.pause_collection != null && (subscription.status === 'active' || subscription.status === 'trialing'))
22
-
23
- /**
24
- * The current period. Top-level on the API version the client is pinned to; read through a narrow
25
- * accessor because later versions move it onto the subscription items.
26
- */
27
- const periodOf = (subscription: Stripe.Subscription): { start?: Date, end?: Date } => {
28
- const typed = subscription as unknown as { current_period_start?: number | null, current_period_end?: number | null }
29
- return { start: paymentUtils.dateOf(typed.current_period_start), end: paymentUtils.dateOf(typed.current_period_end) }
30
- }
31
-
32
18
  const secondsFloor = (at: Date): Date => new Date(Math.floor(at.getTime() / 1000) * 1000)
33
19
 
34
- export const makeStripeSubscriptionsHelper = (ctx: ApiContext): StripeSubscriptionsHelper => {
20
+ export const makePaygateSubscriptionsHelper = (ctx: ApiContext): PaygateSubscriptionsHelper => {
35
21
  const access = paymentAccessOf(ctx)
36
22
 
37
- const applySubscription = async (subscription: Stripe.Subscription, opts: ApplyOptions): Promise<CommitResult> => {
23
+ const applySubscription = async (
24
+ paygate: Paygate, subscription: PaygateSubscription, opts: ApplyOptions,
25
+ ): Promise<CommitResult> => {
38
26
  const metadata = subscription.metadata ?? {}
39
- const customerId = paymentUtils.idOf(subscription.customer)
40
- const previous = await access.subscriptions().byExternalId(subscription.id, STRIPE_PAYGATE_ALIAS)
27
+ const customerId = subscription.customerId
28
+ const previous = await access.subscriptions().byExternalId(subscription.id, paygate.id)
41
29
 
42
30
  let entityId: string | undefined = metadata.entityId ?? previous?.entityId
43
31
  if (entityId == null && customerId != null) {
44
- entityId = (await access.paygateCustomers().loadByPgId(customerId, STRIPE_PAYGATE_ALIAS))?.entityId ?? undefined
32
+ entityId = (await access.paygateCustomers().loadByPgId(customerId, paygate.id))?.entityId ?? undefined
45
33
  }
46
34
  if (entityId == null) {
47
35
  log.warn('Subscription belongs to no known entity; ignored', { subscriptionId: subscription.id })
@@ -52,24 +40,22 @@ export const makeStripeSubscriptionsHelper = (ctx: ApiContext): StripeSubscripti
52
40
  }
53
41
 
54
42
  const now = new Date()
55
- const syncedAt = opts.eventCreated != null ? new Date(opts.eventCreated * 1000) : secondsFloor(now)
43
+ const syncedAt = opts.eventCreated ?? secondsFloor(now)
56
44
  if (opts.eventCreated != null && previous?.syncedAt != null
57
45
  && syncedAt.getTime() < new Date(previous.syncedAt).getTime()) {
58
46
  return { record: previous, change: null, updated: false }
59
47
  }
60
48
 
61
- const item = subscription.items?.data?.[0]
62
- // A price recreated by `sync.ts` (an opposite `tax_behavior`) loses its lookup key; its sku
63
- // metadata survives, so a subscription switched to it in the portal still resolves its plan.
64
- const planSku = item?.price?.lookup_key ?? item?.price?.metadata?.sku ?? metadata.planSku ?? previous?.planSku
49
+ // A price recreated by the catalogue sync (an opposite tax behavior) may lose its lookup key; the
50
+ // paygate still names its plan, so a subscription switched to it in the portal resolves its plan.
51
+ const planSku = subscription.planSku ?? metadata.planSku ?? previous?.planSku
65
52
  if (planSku == null) {
66
53
  log.warn('Subscription names no plan; ignored', { subscriptionId: subscription.id })
67
54
  return { record: previous, change: null, updated: false }
68
55
  }
69
56
  const plan = await catalogueOf(ctx).findPlan(planSku)
70
57
  const productSku = plan?.productSku ?? previous?.productSku ?? metadata.productSku ?? planSku
71
- const paused = opts.forced == null && isPaused(subscription)
72
- const period = periodOf(subscription)
58
+ const paused = opts.forced == null && subscription.paused
73
59
  const terminal = opts.forced != null && TERMINAL_STATUSES.includes(opts.forced)
74
60
 
75
61
  const next = paymentUtils.compact({
@@ -78,24 +64,24 @@ export const makeStripeSubscriptionsHelper = (ctx: ApiContext): StripeSubscripti
78
64
  planSku,
79
65
  productSku,
80
66
  service: metadata.service ?? previous?.service ?? productSku,
81
- paygate: STRIPE_PAYGATE_ALIAS,
67
+ paygate: paygate.id,
82
68
  externalId: subscription.id,
83
- itemId: item?.id,
84
- priceId: item?.price?.id,
85
- status: opts.forced ?? mapStatus(subscription),
86
- externalStatus: subscription.status,
69
+ itemId: subscription.itemId,
70
+ priceId: subscription.priceId,
71
+ status: opts.forced ?? subscription.status,
72
+ externalStatus: subscription.externalStatus,
87
73
  rank: plan != null ? planHelper.planRank(plan) : previous?.rank ?? 0,
88
- periodStart: period.start,
89
- periodEnd: period.end,
90
- cancelAtPeriodEnd: subscription.cancel_at_period_end === true,
91
- canceledAt: paymentUtils.dateOf(subscription.canceled_at),
92
- endedAt: paymentUtils.dateOf(subscription.ended_at) ?? (terminal ? previous?.endedAt ?? now : undefined),
74
+ periodStart: subscription.periodStart,
75
+ periodEnd: subscription.periodEnd,
76
+ cancelAtPeriodEnd: subscription.cancelAtPeriodEnd === true,
77
+ canceledAt: subscription.canceledAt,
78
+ endedAt: subscription.endedAt ?? (terminal ? previous?.endedAt ?? now : undefined),
93
79
  pausedAt: paused ? previous?.pausedAt ?? now : undefined,
94
- trialEnd: paymentUtils.dateOf(subscription.trial_end),
95
- latestInvoiceId: opts.invoiceId ?? paymentUtils.idOf(subscription.latest_invoice) ?? previous?.latestInvoiceId,
80
+ trialEnd: subscription.trialEnd,
81
+ latestInvoiceId: opts.invoiceId ?? subscription.latestInvoiceId ?? previous?.latestInvoiceId,
96
82
  customerId,
97
83
  currency: subscription.currency?.toLowerCase() ?? previous?.currency,
98
- createdAt: previous?.createdAt ?? paymentUtils.dateOf(subscription.created) ?? now,
84
+ createdAt: previous?.createdAt ?? subscription.createdAt ?? now,
99
85
  updatedAt: now,
100
86
  syncedAt,
101
87
  }) as PaymentSubscriptionRecord
@@ -106,25 +92,17 @@ export const makeStripeSubscriptionsHelper = (ctx: ApiContext): StripeSubscripti
106
92
  // The first invoice is a purchase: its window exists before an observer grants the bundle.
107
93
  beforePropagate: async (record, change) => {
108
94
  if (change === 'created') {
109
- await captureOf(ctx).captureSubscriptionPurchase(opts.stripe ?? null, subscription, record)
95
+ await captureOf(ctx).captureSubscriptionPurchase(paygate, subscription, record)
110
96
  }
111
97
  },
112
98
  })
113
99
  }
114
100
 
115
- const retrieveSubscription = async (stripe: Stripe, id: string): Promise<Stripe.Subscription | null> => {
116
- try {
117
- return await stripe.subscriptions.retrieve(id)
118
- } catch (error) {
119
- if (paymentUtils.isMissingObject(error)) {
120
- return null
121
- }
122
- throw error
123
- }
124
- }
101
+ const retrieveSubscription = async (paygate: Paygate, id: string): Promise<PaygateSubscription | null> =>
102
+ paygate.subscriptions != null ? await paygate.subscriptions.retrieve(id) : null
125
103
 
126
- const cancelMissing = async (externalId: string): Promise<CommitResult> => {
127
- const previous = await access.subscriptions().byExternalId(externalId, STRIPE_PAYGATE_ALIAS)
104
+ const cancelMissing = async (paygate: Paygate, externalId: string): Promise<CommitResult> => {
105
+ const previous = await access.subscriptions().byExternalId(externalId, paygate.id)
128
106
  if (previous == null || TERMINAL_STATUSES.includes(previous.status)) {
129
107
  return { record: previous, change: null, updated: false }
130
108
  }
@@ -136,24 +114,47 @@ export const makeStripeSubscriptionsHelper = (ctx: ApiContext): StripeSubscripti
136
114
  })
137
115
  }
138
116
 
139
- const resyncStripeSubscription = async (stripe: Stripe, ref: SubscriptionRef): Promise<number> => {
140
- const ids = new Set<string>()
117
+ /** A registered paygate that keeps subscriptions, or `null`. */
118
+ const subscribingPaygate = (id: string | undefined): Paygate | null => {
119
+ const paygate = id != null ? paygatesOf(ctx).find(id) : null
120
+
121
+ return paygate?.subscriptions != null ? paygate : null
122
+ }
123
+
124
+ const resyncOne = async (paygate: Paygate, id: string): Promise<boolean> => {
125
+ const subscription = await retrieveSubscription(paygate, id)
126
+ const result = await customerLockHelper.withCustomerLock(paygate.id, subscription?.customerId, async () => subscription != null
127
+ ? await applySubscription(paygate, subscription, { source: 'resync' })
128
+ : await cancelMissing(paygate, id))
129
+
130
+ return result.updated
131
+ }
132
+
133
+ const resyncSubscription = async (ref: SubscriptionRef): Promise<number> => {
134
+ const targets = new Map<string, { paygate: Paygate, id: string }>()
135
+ const add = (paygate: Paygate | null, id: string): void => {
136
+ if (paygate != null && !targets.has(`${paygate.id}:${id}`)) {
137
+ targets.set(`${paygate.id}:${id}`, { paygate, id })
138
+ }
139
+ }
141
140
  if (ref.subscriptionId != null) {
142
- ids.add(ref.subscriptionId)
141
+ const row = ref.paygate == null
142
+ ? await access.subscriptions().load({ externalId: ref.subscriptionId, paygate: { $ne: INTERNAL_PAYGATE } })
143
+ : null
144
+ add(subscribingPaygate(ref.paygate ?? row?.paygate)
145
+ ?? (ref.paygate == null && row == null ? paygatesOf(ctx).all().find(paygate => paygate.subscriptions != null) ?? null : null),
146
+ ref.subscriptionId)
143
147
  }
144
148
  if (ref.entityId != null) {
145
- const { items } = await access.subscriptions().list({ entityId: ref.entityId, paygate: STRIPE_PAYGATE_ALIAS }, { size: 0 })
146
- items.forEach(row => ids.add(row.externalId))
149
+ const { items } = await access.subscriptions().list(
150
+ { entityId: ref.entityId, paygate: ref.paygate ?? { $ne: INTERNAL_PAYGATE } }, { size: 0 },
151
+ )
152
+ items.forEach(row => { add(subscribingPaygate(row.paygate), row.externalId) })
147
153
  }
148
154
 
149
155
  let updated = 0
150
- for (const id of ids) {
151
- const subscription = await retrieveSubscription(stripe, id)
152
- const customerId = subscription != null ? paymentUtils.idOf(subscription.customer) : undefined
153
- const result = await customerLockHelper.withCustomerLock(customerId, async () => subscription != null
154
- ? await applySubscription(subscription, { source: 'resync', stripe })
155
- : await cancelMissing(id))
156
- if (result.updated) {
156
+ for (const { paygate, id } of targets.values()) {
157
+ if (await resyncOne(paygate, id)) {
157
158
  updated++
158
159
  }
159
160
  }
@@ -161,35 +162,34 @@ export const makeStripeSubscriptionsHelper = (ctx: ApiContext): StripeSubscripti
161
162
  return updated
162
163
  }
163
164
 
164
- const resyncStripeSubscriptions = async (stripe: Stripe): Promise<{ scanned: number, updated: number }> => {
165
- const ids: string[] = []
165
+ const resyncAll = async (): Promise<{ scanned: number, updated: number }> => {
166
+ const rows: PaymentSubscriptionRecord[] = []
166
167
  for (let page = 0; ; page++) {
167
168
  const { items } = await access.subscriptions().list(
168
- { paygate: STRIPE_PAYGATE_ALIAS, status: { $nin: [...TERMINAL_STATUSES] } },
169
+ { paygate: { $ne: INTERNAL_PAYGATE }, status: { $nin: [...TERMINAL_STATUSES] } },
169
170
  { size: RESYNC_PAGE, page, sort: ['createdAt'] },
170
171
  )
171
- ids.push(...items.map(row => row.externalId))
172
+ rows.push(...items)
172
173
  if (items.length < RESYNC_PAGE) {
173
174
  break
174
175
  }
175
176
  }
177
+ const targets = rows.filter(row => subscribingPaygate(row.paygate) != null)
176
178
 
177
179
  let updated = 0
178
- for (const subscriptionId of ids) {
180
+ for (const row of targets) {
179
181
  try {
180
- updated += await resyncStripeSubscription(stripe, { subscriptionId })
182
+ updated += await resyncSubscription({ subscriptionId: row.externalId, paygate: row.paygate })
181
183
  } catch (error) {
182
- log.error('Subscription resync failed', { subscriptionId, error })
184
+ log.error('Subscription resync failed', { subscriptionId: row.externalId, paygate: row.paygate, error })
183
185
  }
184
186
  }
185
187
 
186
- return { scanned: ids.length, updated }
188
+ return { scanned: targets.length, updated }
187
189
  }
188
190
 
189
- return {
190
- applySubscription, retrieveSubscription, cancelMissing, resyncStripeSubscription, resyncStripeSubscriptions,
191
- }
191
+ return { applySubscription, retrieveSubscription, cancelMissing, resyncSubscription, resyncAll }
192
192
  }
193
193
 
194
- /** The Stripe subscriptions of a context — one per context. */
195
- export const stripeSubscriptionsOf = memoHelper.oncePer(makeStripeSubscriptionsHelper)
194
+ /** The paygate subscriptions of a context — one per context. */
195
+ export const paygateSubscriptionsOf = memoHelper.oncePer(makePaygateSubscriptionsHelper)
@@ -1,30 +1,15 @@
1
- import type Stripe from 'stripe'
2
- import type { BillingProfileView, ConsumerRegion, ConsumerRightsPolicy } from '@owlmeans/payment'
1
+ import type { BillingProfileView, ConsumerRegion, ConsumerRightsPolicy, TaxEstimate } from '@owlmeans/payment'
2
+ import type { FxQuote } from '../paygate/types.js'
3
3
 
4
4
  export interface CacheEntry<T> { value: T; expiresAt: number }
5
5
 
6
- export type TaxOutcome = { ok: true; calculation: Stripe.Tax.Calculation } | { ok: false; code?: string }
6
+ /** A cached tax answer: the estimate, or `null` when the paygate could not place the buyer. */
7
+ export type TaxOutcome = TaxEstimate | null
7
8
 
8
9
  export type FxOutcome = { currency: string; exchangeRate: number; fxFeeRate?: number } | null
9
10
 
10
-
11
- export interface FxQuoteResponse {
12
- rates?: Record<string, {
13
- exchange_rate?: number
14
- rate_details?: { base_rate?: number; fx_fee_rate?: number; reference_rate?: number }
15
- }>
16
- }
17
-
18
- export type ConfigurationParams = Stripe.BillingPortal.ConfigurationCreateParams
19
-
20
- export type Claim = 'ours' | 'foreign' | 'unclaimed'
21
-
22
- export interface CheckoutOptionsFlags {
23
- /** The billing country is locked and the saved customer address carries it: never overwrite it. */
24
- locked?: boolean
25
- /** Adaptive Pricing is allowed on this session (the charge currency is the settlement currency). */
26
- adaptive?: boolean
27
- }
11
+ /** The quotes one run (a catalogue sync) shares, by `<from>:<to>`. */
12
+ export type FxQuoteCache = Map<string, Promise<FxQuote | null>>
28
13
 
29
14
  /** What the consumer-rights policy makes of this checkout's buyer. */
30
15
  export interface BuyerContext {
@@ -37,23 +22,14 @@ export interface BuyerContext {
37
22
  /** `null`: the policy names no region currencies — the legacy settlement behaviour. */
38
23
  chargeCurrency: string | null
39
24
  /**
40
- * Checkout keeps the saved customer address (tax follows it, nothing typed at Stripe moves it): a
41
- * locked profile, or a `stripe.lockCustomerCountry` pin, whose country it carries — tax-locatable.
25
+ * Checkout keeps the saved customer address (tax follows it, nothing typed at the paygate moves
26
+ * it): a locked profile, or a pinned customer country, whose country it carries — tax-locatable.
42
27
  */
43
28
  addressLocked: boolean
44
- /** The address is held by `stripe.lockCustomerCountry`: the first completed purchase locks THIS country. */
29
+ /** The address is held by the paygate's customer country lock: the first completed purchase locks THIS country. */
45
30
  countryPinned: boolean
46
31
  }
47
32
 
48
- export interface StripeErrorShape {
49
- type?: string
50
- rawType?: string
51
- code?: string
52
- param?: string
53
- message?: string
54
- raw?: { type?: string, code?: string, param?: string, message?: string }
55
- }
56
-
57
33
  export interface WebhookRequest {
58
34
  original?: { rawBody?: string | Buffer }
59
35
  rawBody?: string | Buffer
@@ -1,63 +1,35 @@
1
- import type Stripe from 'stripe'
2
1
  import type { CommonServiceRoute } from '@owlmeans/route'
3
2
  import type { PaymentWebhookRecord } from '../../types.js'
3
+ import type { Paygate, PaygateDeployment } from '../../paygate/types.js'
4
4
 
5
5
  export interface EnsureWebhookOptions {
6
6
  /** Verify the stored endpoint still exists even when nothing changed locally. */
7
7
  force?: boolean
8
8
  }
9
9
 
10
- /** A deployment's Stripe webhook: where it is served, the managed endpoint, its secrets and its deliveries. */
10
+ /** A deployment's paygate webhooks: where they are served, the managed endpoints and their deliveries. */
11
11
  export interface WebhookHelper {
12
12
  /** The alias whose host and base form the webhook URL: the gateway's `webhookService`, else `cfg.service`. */
13
13
  webhookServiceOf: () => string
14
- /** The key this deployment's Stripe rows are stored under: the gateway's `owner`, else `cfg.service`. */
14
+ /** The key this deployment's paygate rows are stored under: the gateway's `owner`, else `cfg.service`. */
15
15
  gatewayOwnerOf: () => string
16
16
  /** @throws WebhookSetupError('service:<alias>') when the webhook service is not declared in `cfg.services`. */
17
17
  webhookRouteOf: (alias?: string) => CommonServiceRoute
18
- /** This deployment's public webhook URL for a paygate, on the webhook service's host and base. */
19
- webhookUrlOf: (paygate?: string) => string
18
+ /** This deployment's public webhook URL for a paygate (`/<base>/webhook/<paygate>`), on the webhook service's host and base. */
19
+ webhookUrlOf: (paygate: string) => string
20
+ /** The deployment a paygate keeps its endpoint and portal configuration for: the owner and the webhook URL. */
21
+ deploymentOf: (paygate: string) => PaygateDeployment
20
22
  /**
21
- * Keep exactly one Stripe webhook endpoint for this deployment at its own URL, subscribed to
22
- * `WEBHOOK_EVENTS` on the client's API version, and persist its signing secret — which Stripe
23
- * returns only when an endpoint is created.
24
- *
25
- * A deployment's identity is its webhook URL (`webhookUrlOf`: the `webhookService` alias's host and
26
- * base); its rows are keyed by the gateway's `owner` (`gatewayOwnerOf`). Several deployments of one
27
- * application may share a Stripe account — a test-mode account commonly serves every non-production
28
- * deployment — each with its own database and URL, so a deployment deletes only the endpoints its
29
- * own `payment-webhook` rows name.
30
- *
31
- * - A URL Stripe cannot deliver to (not https, a loopback or dotless host) is skipped.
32
- * - An unchanged `{ url, apiVersion, events }` fingerprint makes no paygate call at all.
33
- * - `force` first verifies the stored endpoint still exists; one deleted from outside loses its row
34
- * and is created again.
35
- * - Changed events on the same API version update the endpoint in place.
36
- * - A changed API version (create-only on an endpoint) deletes and recreates it.
37
- * - An endpoint already at this exact URL that no row names is replaced: its secret is unknown here.
38
- * - A row of this paygate and owner at another URL is a URL this deployment has left — a moved host,
39
- * or a new `webhookService`: once the endpoint at the current URL is in place, the endpoint that
40
- * row names is deleted (already gone is fine), then the row.
41
- * - An endpoint at another URL that no row of this deployment names belongs to another deployment
42
- * and is never deleted — whatever its metadata says.
43
- * - Replicas racing to persist one row: the endpoint created last is the live one.
44
- * - A created endpoint carries `{ owlmeans: 'payment', service: <owner> }` metadata and the
45
- * `owlmeans:<owner>` description for operators.
46
- */
47
- ensureWebhookEndpoint: (stripe: Stripe, opts?: EnsureWebhookOptions) => Promise<PaymentWebhookRecord | null>
48
- /**
49
- * The secrets a Stripe signature may be verified with, in order: the configured file secret (an
50
- * override), then the one stored for the managed endpoint — the newest row of the gateway's `owner`,
51
- * so a process receiving the webhook finds the secret whichever process of the owner stored it.
23
+ * Keep the paygate's webhook endpoint for this deployment at its own URL
24
+ * (`paygate.webhook.ensureEndpoint`). A deployment's identity is its webhook URL; its rows carry the
25
+ * gateway's `owner`. A URL a paygate cannot deliver to (not https, a loopback or dotless host) is
26
+ * skipped, and so is a paygate without `webhook`.
52
27
  */
53
- stripeWebhookSecrets: () => Promise<string[]>
54
- /** The secret a Stripe signature is verified with. @throws WebhookSetupError('secret') */
55
- stripeWebhookSecret: () => Promise<string>
28
+ ensureWebhookEndpoint: (paygate: Paygate, opts?: EnsureWebhookOptions) => Promise<PaymentWebhookRecord | null>
56
29
  /**
57
- * Verify a Stripe webhook against the configured override secret, then the managed endpoint's
58
- * stored one, and dispatch it.
30
+ * Verify a delivery with the paygate (against the owner's secrets) and apply its events in order.
59
31
  *
60
- * @throws PaygateSignatureError | WebhookSetupError('secret')
32
+ * @throws PaygateError('capability:webhook') | PaygateSignatureError | WebhookSetupError('secret')
61
33
  */
62
- handleStripeWebhook: (stripe: Stripe, request: unknown) => Promise<void>
34
+ handleDelivery: (paygate: Paygate, request: unknown) => Promise<void>
63
35
  }