@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.
- package/README.md +52 -54
- package/agent-meta/manifest.json +2 -2
- package/agent-meta/skills/server-payment/SKILL.md +272 -330
- package/agent-meta/skills/server-payment/parts/reference.md +3 -3
- package/build/access/types.d.ts +7 -16
- package/build/access/types.d.ts.map +1 -1
- package/build/access.d.ts.map +1 -1
- package/build/access.js +6 -8
- package/build/access.js.map +1 -1
- package/build/actions/resync.d.ts +3 -3
- package/build/actions/resync.js +5 -5
- package/build/actions/resync.js.map +1 -1
- package/build/actions/webhook.d.ts +4 -1
- package/build/actions/webhook.d.ts.map +1 -1
- package/build/actions/webhook.js +8 -4
- package/build/actions/webhook.js.map +1 -1
- package/build/bootstrap/types.d.ts +13 -7
- package/build/bootstrap/types.d.ts.map +1 -1
- package/build/bootstrap.d.ts +4 -4
- package/build/bootstrap.d.ts.map +1 -1
- package/build/bootstrap.js +19 -10
- package/build/bootstrap.js.map +1 -1
- package/build/catalogue/types.d.ts +3 -3
- package/build/catalogue/types.d.ts.map +1 -1
- package/build/catalogue.d.ts.map +1 -1
- package/build/catalogue.js +4 -8
- package/build/catalogue.js.map +1 -1
- package/build/checkout/types.d.ts +21 -0
- package/build/checkout/types.d.ts.map +1 -0
- package/build/{plugins/stripe → checkout}/types.js.map +1 -1
- package/build/checkout.d.ts +6 -0
- package/build/checkout.d.ts.map +1 -0
- package/build/checkout.js +374 -0
- package/build/checkout.js.map +1 -0
- package/build/config.d.ts +10 -16
- package/build/config.d.ts.map +1 -1
- package/build/config.js +18 -59
- package/build/config.js.map +1 -1
- package/build/consts.d.ts +3 -49
- package/build/consts.d.ts.map +1 -1
- package/build/consts.js +3 -61
- package/build/consts.js.map +1 -1
- package/build/consumer/cancellation/types.d.ts +6 -4
- package/build/consumer/cancellation/types.d.ts.map +1 -1
- package/build/consumer/cancellation.d.ts.map +1 -1
- package/build/consumer/cancellation.js +11 -5
- package/build/consumer/cancellation.js.map +1 -1
- package/build/consumer/capture/types.d.ts +8 -12
- package/build/consumer/capture/types.d.ts.map +1 -1
- package/build/consumer/capture.d.ts.map +1 -1
- package/build/consumer/capture.js +48 -53
- package/build/consumer/capture.js.map +1 -1
- package/build/consumer/index.d.ts +4 -0
- package/build/consumer/index.d.ts.map +1 -1
- package/build/consumer/index.js +2 -0
- package/build/consumer/index.js.map +1 -1
- package/build/consumer/reconcile.d.ts.map +1 -1
- package/build/consumer/reconcile.js +82 -72
- package/build/consumer/reconcile.js.map +1 -1
- package/build/consumer/records/types.d.ts +4 -4
- package/build/consumer/records/types.d.ts.map +1 -1
- package/build/consumer/records.d.ts.map +1 -1
- package/build/consumer/records.js +16 -13
- package/build/consumer/records.js.map +1 -1
- package/build/consumer/service.d.ts +2 -2
- package/build/consumer/service.d.ts.map +1 -1
- package/build/consumer/service.js +28 -21
- package/build/consumer/service.js.map +1 -1
- package/build/consumer/types.d.ts +1 -4
- package/build/consumer/types.d.ts.map +1 -1
- package/build/consumer/types.local.d.ts +1 -9
- package/build/consumer/types.local.d.ts.map +1 -1
- package/build/consumer/withdrawal/types.d.ts +14 -12
- package/build/consumer/withdrawal/types.d.ts.map +1 -1
- package/build/consumer/withdrawal.d.ts.map +1 -1
- package/build/consumer/withdrawal.js +55 -71
- package/build/consumer/withdrawal.js.map +1 -1
- package/build/index.d.ts +12 -6
- package/build/index.d.ts.map +1 -1
- package/build/index.js +7 -4
- package/build/index.js.map +1 -1
- package/build/paygate/providers.d.ts +13 -0
- package/build/paygate/providers.d.ts.map +1 -0
- package/build/paygate/providers.js +38 -0
- package/build/paygate/providers.js.map +1 -0
- package/build/paygate/registry.d.ts +6 -0
- package/build/paygate/registry.d.ts.map +1 -0
- package/build/paygate/registry.js +37 -0
- package/build/paygate/registry.js.map +1 -0
- package/build/paygate/types.d.ts +577 -0
- package/build/paygate/types.d.ts.map +1 -0
- package/build/{plugins/session → paygate}/types.js.map +1 -1
- package/build/plan/types.d.ts +6 -1
- package/build/plan/types.d.ts.map +1 -1
- package/build/plan.d.ts.map +1 -1
- package/build/plan.js +16 -2
- package/build/plan.js.map +1 -1
- package/build/plugins/checkout-policy/types.d.ts +5 -3
- package/build/plugins/checkout-policy/types.d.ts.map +1 -1
- package/build/plugins/checkout-policy.d.ts.map +1 -1
- package/build/plugins/checkout-policy.js +5 -3
- package/build/plugins/checkout-policy.js.map +1 -1
- package/build/plugins/consts.local.d.ts +8 -10
- package/build/plugins/consts.local.d.ts.map +1 -1
- package/build/plugins/consts.local.js +2 -19
- package/build/plugins/consts.local.js.map +1 -1
- package/build/plugins/customer-lock/types.d.ts +2 -2
- package/build/plugins/customer-lock/types.d.ts.map +1 -1
- package/build/plugins/customer-lock.js +2 -2
- package/build/plugins/customer-lock.js.map +1 -1
- package/build/plugins/estimate/cache.js +1 -1
- package/build/plugins/estimate/cache.js.map +1 -1
- package/build/plugins/estimate/types.d.ts +10 -10
- package/build/plugins/estimate/types.d.ts.map +1 -1
- package/build/plugins/estimate.d.ts.map +1 -1
- package/build/plugins/estimate.js +48 -122
- package/build/plugins/estimate.js.map +1 -1
- package/build/plugins/events/types.d.ts +17 -10
- package/build/plugins/events/types.d.ts.map +1 -1
- package/build/plugins/events.d.ts +6 -5
- package/build/plugins/events.d.ts.map +1 -1
- package/build/plugins/events.js +162 -173
- package/build/plugins/events.js.map +1 -1
- package/build/plugins/fx/types.d.ts +10 -21
- package/build/plugins/fx/types.d.ts.map +1 -1
- package/build/plugins/fx.d.ts +1 -1
- package/build/plugins/fx.d.ts.map +1 -1
- package/build/plugins/fx.js +17 -54
- package/build/plugins/fx.js.map +1 -1
- package/build/plugins/portal/types.d.ts +8 -37
- package/build/plugins/portal/types.d.ts.map +1 -1
- package/build/plugins/portal.d.ts.map +1 -1
- package/build/plugins/portal.js +38 -208
- package/build/plugins/portal.js.map +1 -1
- package/build/plugins/refunds/types.d.ts +11 -11
- package/build/plugins/refunds/types.d.ts.map +1 -1
- package/build/plugins/refunds.d.ts.map +1 -1
- package/build/plugins/refunds.js +14 -39
- package/build/plugins/refunds.js.map +1 -1
- package/build/plugins/snapshot/types.d.ts +11 -0
- package/build/plugins/snapshot/types.d.ts.map +1 -0
- package/build/plugins/snapshot/types.js +2 -0
- package/build/plugins/snapshot/types.js.map +1 -0
- package/build/plugins/snapshot.d.ts +4 -0
- package/build/plugins/snapshot.d.ts.map +1 -0
- package/build/plugins/snapshot.js +19 -0
- package/build/plugins/snapshot.js.map +1 -0
- package/build/plugins/subscriptions/types.d.ts +17 -17
- package/build/plugins/subscriptions/types.d.ts.map +1 -1
- package/build/plugins/subscriptions.d.ts +4 -4
- package/build/plugins/subscriptions.d.ts.map +1 -1
- package/build/plugins/subscriptions.js +69 -77
- package/build/plugins/subscriptions.js.map +1 -1
- package/build/plugins/types.local.d.ts +9 -43
- package/build/plugins/types.local.d.ts.map +1 -1
- package/build/plugins/webhook-manager/types.d.ts +15 -43
- package/build/plugins/webhook-manager/types.d.ts.map +1 -1
- package/build/plugins/webhook-manager.d.ts +3 -3
- package/build/plugins/webhook-manager.d.ts.map +1 -1
- package/build/plugins/webhook-manager.js +21 -199
- package/build/plugins/webhook-manager.js.map +1 -1
- package/build/protocol.d.ts +1 -1
- package/build/protocol.d.ts.map +1 -1
- package/build/protocol.js +1 -1
- package/build/protocol.js.map +1 -1
- package/build/service.d.ts +11 -11
- package/build/service.d.ts.map +1 -1
- package/build/service.js +59 -23
- package/build/service.js.map +1 -1
- package/build/sync/types.d.ts +17 -13
- package/build/sync/types.d.ts.map +1 -1
- package/build/sync.d.ts.map +1 -1
- package/build/sync.js +22 -122
- package/build/sync.js.map +1 -1
- package/build/types.d.ts +46 -101
- package/build/types.d.ts.map +1 -1
- package/build/utils/types.d.ts +0 -8
- package/build/utils/types.d.ts.map +1 -1
- package/build/utils.d.ts +1 -4
- package/build/utils.d.ts.map +1 -1
- package/build/utils.js +1 -15
- package/build/utils.js.map +1 -1
- package/package.json +20 -22
- package/src/access/types.ts +7 -16
- package/src/access.ts +7 -15
- package/src/actions/resync.ts +5 -5
- package/src/actions/webhook.ts +8 -4
- package/src/bootstrap/types.ts +13 -7
- package/src/bootstrap.ts +23 -13
- package/src/catalogue/types.ts +3 -3
- package/src/catalogue.ts +4 -8
- package/src/checkout/types.ts +21 -0
- package/src/checkout.ts +414 -0
- package/src/config.ts +19 -66
- package/src/consts.ts +3 -69
- package/src/consumer/cancellation/types.ts +6 -4
- package/src/consumer/cancellation.ts +13 -7
- package/src/consumer/capture/types.ts +8 -12
- package/src/consumer/capture.ts +50 -59
- package/src/consumer/index.ts +4 -0
- package/src/consumer/reconcile.ts +69 -68
- package/src/consumer/records/types.ts +4 -4
- package/src/consumer/records.ts +19 -14
- package/src/consumer/service.ts +35 -22
- package/src/consumer/types.local.ts +1 -8
- package/src/consumer/types.ts +1 -4
- package/src/consumer/withdrawal/types.ts +14 -12
- package/src/consumer/withdrawal.ts +61 -77
- package/src/index.ts +12 -6
- package/src/paygate/providers.ts +48 -0
- package/src/paygate/registry.ts +53 -0
- package/src/paygate/types.ts +640 -0
- package/src/plan/types.ts +6 -1
- package/src/plan.ts +21 -3
- package/src/plugins/checkout-policy/types.ts +5 -3
- package/src/plugins/checkout-policy.ts +6 -5
- package/src/plugins/consts.local.ts +2 -26
- package/src/plugins/customer-lock/types.ts +2 -2
- package/src/plugins/customer-lock.ts +2 -2
- package/src/plugins/estimate/cache.ts +1 -1
- package/src/plugins/estimate/types.ts +10 -10
- package/src/plugins/estimate.ts +52 -128
- package/src/plugins/events/types.ts +17 -9
- package/src/plugins/events.ts +172 -190
- package/src/plugins/fx/types.ts +10 -23
- package/src/plugins/fx.ts +28 -64
- package/src/plugins/portal/types.ts +8 -38
- package/src/plugins/portal.ts +48 -229
- package/src/plugins/refunds/types.ts +11 -11
- package/src/plugins/refunds.ts +16 -40
- package/src/plugins/snapshot/types.ts +11 -0
- package/src/plugins/snapshot.ts +22 -0
- package/src/plugins/subscriptions/types.ts +17 -17
- package/src/plugins/subscriptions.ts +81 -81
- package/src/plugins/types.local.ts +9 -33
- package/src/plugins/webhook-manager/types.ts +15 -43
- package/src/plugins/webhook-manager.ts +24 -220
- package/src/protocol.ts +1 -1
- package/src/service.ts +66 -30
- package/src/sync/types.ts +17 -13
- package/src/sync.ts +25 -143
- package/src/types.ts +47 -97
- package/src/utils/types.ts +0 -9
- package/src/utils.ts +2 -20
- package/tests/capabilities.spec.ts +219 -0
- package/tests/entitlement.spec.ts +4 -4
- package/tests/gate-handlers.spec.ts +6 -6
- package/tests/gate.spec.ts +2 -2
- package/tests/grants.spec.ts +2 -2
- package/tests/internal-plan.spec.ts +2 -2
- package/tests/limit-gate.spec.ts +2 -2
- package/tests/paygates.spec.ts +132 -0
- package/tests/protocol.spec.ts +4 -5
- package/tests/usage.spec.ts +2 -2
- package/tests/webhook.spec.ts +137 -0
- package/build/plugins/session/types.d.ts +0 -34
- package/build/plugins/session/types.d.ts.map +0 -1
- package/build/plugins/session.d.ts +0 -4
- package/build/plugins/session.d.ts.map +0 -1
- package/build/plugins/session.js +0 -71
- package/build/plugins/session.js.map +0 -1
- package/build/plugins/status.d.ts +0 -8
- package/build/plugins/status.d.ts.map +0 -1
- package/build/plugins/status.js +0 -21
- package/build/plugins/status.js.map +0 -1
- package/build/plugins/stripe/types.d.ts +0 -20
- package/build/plugins/stripe/types.d.ts.map +0 -1
- package/build/plugins/stripe.d.ts +0 -6
- package/build/plugins/stripe.d.ts.map +0 -1
- package/build/plugins/stripe.js +0 -518
- package/build/plugins/stripe.js.map +0 -1
- package/src/plugins/session/types.ts +0 -30
- package/src/plugins/session.ts +0 -86
- package/src/plugins/status.ts +0 -22
- package/src/plugins/stripe/types.ts +0 -20
- package/src/plugins/stripe.ts +0 -571
- package/tests/checkout-consumer.spec.ts +0 -366
- package/tests/checkout-locks.spec.ts +0 -161
- package/tests/checkout-plugins.spec.ts +0 -164
- package/tests/checkout.spec.ts +0 -313
- package/tests/consumer-events.spec.ts +0 -215
- package/tests/consumer-fixtures.ts +0 -141
- package/tests/consumer-ops.spec.ts +0 -361
- package/tests/consumer-rights.integration.spec.ts +0 -147
- package/tests/consumer-rights.spec.ts +0 -606
- package/tests/context.ts +0 -110
- package/tests/estimate.spec.ts +0 -350
- package/tests/events.spec.ts +0 -367
- package/tests/fake-stripe.ts +0 -1004
- package/tests/gateway-options.spec.ts +0 -180
- package/tests/portal.spec.ts +0 -202
- package/tests/sync.spec.ts +0 -114
- package/tests/usage.integration.spec.ts +0 -165
- package/tests/webhook-manager.spec.ts +0 -149
- /package/build/{plugins/session → checkout}/types.js +0 -0
- /package/build/{plugins/stripe → paygate}/types.js +0 -0
package/src/plugins/events.ts
CHANGED
|
@@ -1,31 +1,30 @@
|
|
|
1
|
-
import type Stripe from 'stripe'
|
|
2
1
|
import { CheckoutPricingMode, ENTITLING_STATUSES, PaygateError, SubscriptionStatus } from '@owlmeans/payment'
|
|
3
2
|
import type { Context as ApiContext } from '@owlmeans/server-api'
|
|
4
|
-
import {
|
|
3
|
+
import { memoHelper } from '@owlmeans/context'
|
|
4
|
+
import { GATEWAY_SERVICE } from '../consts.js'
|
|
5
5
|
import type {
|
|
6
6
|
CommitResult, CheckoutOutcome, CheckoutPlugin, DisputeEvent, PaymentFulfillmentRecord, PaymentSubscriptionRecord,
|
|
7
7
|
RefundEvent, TopUpCompletion,
|
|
8
8
|
} from '../types.js'
|
|
9
|
+
import type {
|
|
10
|
+
CheckoutSnapshot, DisputeChangedEvent, EventCustomer, EventInvoice, InvoiceEvent, Paygate, PaygateCharge,
|
|
11
|
+
PaygateEvent, PaygateRefund, PaygateSubscription, SubscriptionChangedEvent,
|
|
12
|
+
} from '../paygate/types.js'
|
|
9
13
|
import type { PaymentTarget } from './refunds/types.js'
|
|
10
14
|
import type { ApplyOptions } from './subscriptions/types.js'
|
|
11
15
|
import { log } from '../log.js'
|
|
12
|
-
import {
|
|
13
|
-
import type { EventHandler, StripeEventHandler } from './events/types.js'
|
|
16
|
+
import type { PaymentEventsHelper } from './events/types.js'
|
|
14
17
|
import { paymentAccessOf } from '../access.js'
|
|
15
18
|
import { paymentUtils } from '../utils.js'
|
|
16
19
|
import { checkoutPluginsOf } from './checkout-plugins.js'
|
|
17
20
|
import { paymentTargetOf } from './refunds.js'
|
|
18
21
|
import { customerLockHelper } from './customer-lock.js'
|
|
19
|
-
import {
|
|
22
|
+
import { paygateSubscriptionsOf } from './subscriptions.js'
|
|
23
|
+
import { checkoutSnapshotHelper } from './snapshot.js'
|
|
20
24
|
import { consumerRecordsOf } from '../consumer/records.js'
|
|
21
25
|
import { captureOf } from '../consumer/capture.js'
|
|
22
|
-
import { stripeSessionHelper } from './session.js'
|
|
23
|
-
|
|
24
|
-
/** `invoice.subscription`, top-level on the pinned API version. */
|
|
25
|
-
const subscriptionIdOfInvoice = (invoice: Stripe.Invoice): string | undefined =>
|
|
26
|
-
paymentUtils.idOf((invoice as unknown as { subscription?: string | { id?: string } | null }).subscription)
|
|
27
26
|
|
|
28
|
-
const integerMetadata = (metadata:
|
|
27
|
+
const integerMetadata = (metadata: Record<string, string>, key: string): number => {
|
|
29
28
|
const raw = metadata[key]
|
|
30
29
|
const value = raw == null || raw.trim() === '' ? Number.NaN : Number(raw)
|
|
31
30
|
if (!Number.isSafeInteger(value)) throw new PaygateError(`metadata:${key}`)
|
|
@@ -33,33 +32,34 @@ const integerMetadata = (metadata: Stripe.Metadata, key: string): number => {
|
|
|
33
32
|
}
|
|
34
33
|
|
|
35
34
|
/**
|
|
36
|
-
* The
|
|
37
|
-
*
|
|
35
|
+
* The event dispatch of a context: one paygate event applied to the stores and told to the
|
|
36
|
+
* observers. A throw escapes so the paygate delivers the event again.
|
|
38
37
|
*/
|
|
39
|
-
export const
|
|
38
|
+
export const makePaymentEventsHelper = (ctx: ApiContext): PaymentEventsHelper => {
|
|
40
39
|
const access = paymentAccessOf(ctx)
|
|
41
|
-
const
|
|
40
|
+
const subscriptions = paygateSubscriptionsOf(ctx)
|
|
41
|
+
const lock = customerLockHelper.withCustomerLock
|
|
42
42
|
|
|
43
43
|
/** The registered checkout plugins — none in a context without a gateway service. */
|
|
44
44
|
const registeredPlugins = (): readonly CheckoutPlugin[] =>
|
|
45
45
|
(ctx as unknown as { hasService?: (alias: string) => boolean }).hasService?.(GATEWAY_SERVICE) === true
|
|
46
46
|
? access.gateway().checkoutPlugins?.() ?? [] : []
|
|
47
47
|
|
|
48
|
-
const upsertCustomer = async (customer:
|
|
49
|
-
await
|
|
48
|
+
const upsertCustomer = async (paygate: Paygate, customer: EventCustomer): Promise<void> => {
|
|
49
|
+
await lock(paygate.id, customer.id, async () => {
|
|
50
50
|
const resource = access.paygateCustomers()
|
|
51
|
-
const existing = await resource.loadByPgId(customer.id,
|
|
51
|
+
const existing = await resource.loadByPgId(customer.id, paygate.id)
|
|
52
52
|
const data = paymentUtils.compact({
|
|
53
53
|
email: customer.email ?? undefined, name: customer.name ?? undefined,
|
|
54
|
-
taxId: customer.
|
|
55
|
-
country: customer.
|
|
54
|
+
taxId: customer.taxId ?? undefined,
|
|
55
|
+
country: customer.country?.toUpperCase() ?? undefined,
|
|
56
56
|
currency: customer.currency?.toLowerCase() ?? undefined,
|
|
57
57
|
entityId: customer.metadata?.entityId ?? existing?.entityId ?? undefined,
|
|
58
58
|
profileId: customer.metadata?.profileId ?? existing?.profileId ?? undefined,
|
|
59
59
|
})
|
|
60
60
|
if (existing == null) {
|
|
61
61
|
try {
|
|
62
|
-
await resource.create({ paygate:
|
|
62
|
+
await resource.create({ paygate: paygate.id, externalId: customer.id, ...data })
|
|
63
63
|
} catch (error) {
|
|
64
64
|
if (!paymentUtils.isDuplicateKey(error)) throw error
|
|
65
65
|
}
|
|
@@ -70,15 +70,15 @@ export const createEventHandler = (ctx: ApiContext, stripe: Stripe): StripeEvent
|
|
|
70
70
|
})
|
|
71
71
|
}
|
|
72
72
|
|
|
73
|
-
const markCustomerDeleted = async (
|
|
73
|
+
const markCustomerDeleted = async (paygate: Paygate, customerId: string): Promise<void> => {
|
|
74
74
|
const resource = access.paygateCustomers()
|
|
75
|
-
const existing = await resource.loadByPgId(
|
|
75
|
+
const existing = await resource.loadByPgId(customerId, paygate.id)
|
|
76
76
|
if (existing != null && existing.deletedAt == null) {
|
|
77
77
|
await resource.update({ ...existing, deletedAt: new Date() })
|
|
78
78
|
}
|
|
79
79
|
}
|
|
80
80
|
|
|
81
|
-
const settle = async (session:
|
|
81
|
+
const settle = async (session: CheckoutSnapshot, outcome: CheckoutOutcome, entityId?: string): Promise<void> => {
|
|
82
82
|
const metadata = session.metadata ?? {}
|
|
83
83
|
const owner = entityId ?? metadata.entityId
|
|
84
84
|
if (owner == null) return
|
|
@@ -89,25 +89,25 @@ export const createEventHandler = (ctx: ApiContext, stripe: Stripe): StripeEvent
|
|
|
89
89
|
}))
|
|
90
90
|
}
|
|
91
91
|
|
|
92
|
-
const fulfillPayment = async (session:
|
|
92
|
+
const fulfillPayment = async (paygate: Paygate, session: CheckoutSnapshot): Promise<void> => {
|
|
93
93
|
if (session.mode === 'subscription') {
|
|
94
|
-
await completeSubscriptionCheckout(session)
|
|
94
|
+
await completeSubscriptionCheckout(paygate, session)
|
|
95
95
|
return
|
|
96
96
|
}
|
|
97
|
-
if (!
|
|
97
|
+
if (!checkoutSnapshotHelper.canFulfill(session)) return
|
|
98
98
|
const metadata = session.metadata ?? {}
|
|
99
99
|
if (metadata.entityId == null || metadata.service == null || metadata.productSku == null) {
|
|
100
100
|
throw new PaygateError('metadata:owner')
|
|
101
101
|
}
|
|
102
|
-
await
|
|
102
|
+
await lock(paygate.id, session.customerId, async () => {
|
|
103
103
|
const ledger = access.fulfillments()
|
|
104
|
-
let stored = await ledger.byExternalId(session.id,
|
|
104
|
+
let stored = await ledger.byExternalId(session.id, paygate.id)
|
|
105
105
|
if (stored?.fulfilledAt != null) return
|
|
106
106
|
|
|
107
107
|
const amountMode = metadata.pricingMode === CheckoutPricingMode.Amount
|
|
108
108
|
const base = {
|
|
109
109
|
entityId: metadata.entityId, productSku: metadata.productSku, planSku: metadata.planSku,
|
|
110
|
-
service: metadata.service, paygate:
|
|
110
|
+
service: metadata.service, paygate: paygate.id, externalId: session.id,
|
|
111
111
|
}
|
|
112
112
|
let completion: TopUpCompletion
|
|
113
113
|
let record: Partial<PaymentFulfillmentRecord>
|
|
@@ -119,7 +119,7 @@ export const createEventHandler = (ctx: ApiContext, stripe: Stripe): StripeEvent
|
|
|
119
119
|
? chargedMinor : integerMetadata(metadata, 'sourceChargeAmountMinor')
|
|
120
120
|
const amountCurrency = (metadata.amountCurrency ?? currency)?.toLowerCase()
|
|
121
121
|
if (currency == null || session.currency?.toLowerCase() !== currency
|
|
122
|
-
|| amountCurrency == null || session.
|
|
122
|
+
|| amountCurrency == null || session.amountSubtotalMinor !== chargedMinor
|
|
123
123
|
|| amountMinor <= 0 || chargedMinor <= 0 || sourceChargedMinor < amountMinor
|
|
124
124
|
|| (amountCurrency === currency && sourceChargedMinor !== chargedMinor)) {
|
|
125
125
|
throw new PaygateError('amount-mismatch')
|
|
@@ -136,8 +136,7 @@ export const createEventHandler = (ctx: ApiContext, stripe: Stripe): StripeEvent
|
|
|
136
136
|
if (metadata.currency != null && session.currency?.toLowerCase() !== metadata.currency.toLowerCase()) {
|
|
137
137
|
throw new PaygateError('currency-mismatch')
|
|
138
138
|
}
|
|
139
|
-
const
|
|
140
|
-
const units = lineItems.data.reduce((sum, line) => sum + (line.quantity ?? 0), 0)
|
|
139
|
+
const units = await paygate.checkout.units(session.id)
|
|
141
140
|
if (units <= 0) throw new PaygateError('units')
|
|
142
141
|
record = { mode: CheckoutPricingMode.Quantity, units, ...(session.currency != null ? { currency: session.currency } : {}) }
|
|
143
142
|
completion = { ...base, mode: 'quantity', units }
|
|
@@ -145,18 +144,16 @@ export const createEventHandler = (ctx: ApiContext, stripe: Stripe): StripeEvent
|
|
|
145
144
|
|
|
146
145
|
// The purchase — the withdrawal window and the contract — exists BEFORE the credits do; the
|
|
147
146
|
// billing country is locked with it.
|
|
148
|
-
const captured = await captureOf(ctx).capturePaymentPurchase(
|
|
147
|
+
const captured = await captureOf(ctx).capturePaymentPurchase(paygate, session, paymentUtils.compact({
|
|
149
148
|
netAmountMinor: completion.mode === 'amount' ? completion.amountMinor : undefined,
|
|
150
149
|
amountCurrency: completion.mode === 'amount' ? completion.amountCurrency : undefined,
|
|
151
150
|
units: completion.mode === 'quantity' ? completion.units : undefined,
|
|
152
151
|
}))
|
|
153
152
|
const evidence = captureOf(ctx).sessionEvidenceOf(session)
|
|
154
|
-
const identifiers = paymentUtils.compact({
|
|
155
|
-
paymentIntentId: paymentUtils.idOf(session.payment_intent), invoiceId: paymentUtils.idOf(session.invoice),
|
|
156
|
-
})
|
|
153
|
+
const identifiers = paymentUtils.compact({ paymentIntentId: session.paymentId, invoiceId: session.invoiceId })
|
|
157
154
|
const evidenceFields = paymentUtils.compact({
|
|
158
155
|
country: evidence.country, email: evidence.email, profileId: metadata.profileId,
|
|
159
|
-
amountTotalMinor: session.
|
|
156
|
+
amountTotalMinor: session.amountTotalMinor ?? undefined, amountTaxMinor: session.amountTaxMinor ?? undefined,
|
|
160
157
|
termsAccepted: evidence.termsAccepted, purchaseId: captured?.purchase.purchaseId,
|
|
161
158
|
})
|
|
162
159
|
if (stored == null) {
|
|
@@ -164,7 +161,7 @@ export const createEventHandler = (ctx: ApiContext, stripe: Stripe): StripeEvent
|
|
|
164
161
|
stored = await ledger.create(paymentUtils.compact({ ...base, ...record, ...identifiers, ...evidenceFields, createdAt: new Date() }) as PaymentFulfillmentRecord)
|
|
165
162
|
} catch (error) {
|
|
166
163
|
if (!paymentUtils.isDuplicateKey(error)) throw error
|
|
167
|
-
stored = await ledger.byExternalId(session.id,
|
|
164
|
+
stored = await ledger.byExternalId(session.id, paygate.id)
|
|
168
165
|
if (stored == null || stored.fulfilledAt != null) return
|
|
169
166
|
}
|
|
170
167
|
} else if ((stored.paymentIntentId == null && identifiers.paymentIntentId != null)
|
|
@@ -187,40 +184,40 @@ export const createEventHandler = (ctx: ApiContext, stripe: Stripe): StripeEvent
|
|
|
187
184
|
* refined with the buyer's own country and totals, the billing country is locked, the evidence is
|
|
188
185
|
* stored on the subscription row and the confirmation mailed.
|
|
189
186
|
*/
|
|
190
|
-
const completeSubscriptionCheckout = async (session:
|
|
191
|
-
if (session.
|
|
192
|
-
const subscriptionId =
|
|
187
|
+
const completeSubscriptionCheckout = async (paygate: Paygate, session: CheckoutSnapshot): Promise<void> => {
|
|
188
|
+
if (session.payment !== 'paid' && session.payment !== 'not-required') return
|
|
189
|
+
const subscriptionId = session.subscriptionId
|
|
193
190
|
if (subscriptionId == null) return
|
|
194
|
-
await
|
|
195
|
-
let row = await access.subscriptions().byExternalId(subscriptionId,
|
|
196
|
-
let subscription:
|
|
191
|
+
await lock(paygate.id, session.customerId, async () => {
|
|
192
|
+
let row = await access.subscriptions().byExternalId(subscriptionId, paygate.id)
|
|
193
|
+
let subscription: PaygateSubscription | null = null
|
|
197
194
|
if (row?.propagated == null) {
|
|
198
|
-
subscription = await
|
|
195
|
+
subscription = await subscriptions.retrieveSubscription(paygate, subscriptionId)
|
|
199
196
|
if (subscription != null) {
|
|
200
|
-
row = (await
|
|
197
|
+
row = (await subscriptions.applySubscription(paygate, subscription, { source: 'webhook' })).record ?? row
|
|
201
198
|
}
|
|
202
199
|
}
|
|
203
200
|
if (row == null) {
|
|
204
201
|
log.warn('Completed checkout names an unknown subscription', { sessionId: session.id, subscriptionId })
|
|
205
202
|
return
|
|
206
203
|
}
|
|
207
|
-
let purchase = await access.purchases().byPurchaseId(consumerRecordsOf(ctx).purchaseIdOf(subscriptionId))
|
|
204
|
+
let purchase = await access.purchases().byPurchaseId(consumerRecordsOf(ctx).purchaseIdOf(paygate.id, subscriptionId))
|
|
208
205
|
if (purchase == null && ENTITLING_STATUSES.includes(row.status)) {
|
|
209
|
-
subscription = subscription ?? await
|
|
206
|
+
subscription = subscription ?? await subscriptions.retrieveSubscription(paygate, subscriptionId)
|
|
210
207
|
purchase = subscription != null
|
|
211
|
-
? (await captureOf(ctx).captureSubscriptionPurchase(
|
|
208
|
+
? (await captureOf(ctx).captureSubscriptionPurchase(paygate, subscription, row))?.purchase ?? null : null
|
|
212
209
|
}
|
|
213
210
|
if (purchase != null) {
|
|
214
|
-
purchase = await captureOf(ctx).completeSubscriptionPurchase(
|
|
211
|
+
purchase = await captureOf(ctx).completeSubscriptionPurchase(paygate, session, purchase)
|
|
215
212
|
}
|
|
216
213
|
const evidence = captureOf(ctx).sessionEvidenceOf(session)
|
|
217
214
|
const metadata = session.metadata ?? {}
|
|
218
|
-
const current = await access.subscriptions().byExternalId(subscriptionId,
|
|
215
|
+
const current = await access.subscriptions().byExternalId(subscriptionId, paygate.id) ?? row
|
|
219
216
|
await access.subscriptions().update(paymentUtils.compact({
|
|
220
217
|
...current,
|
|
221
218
|
checkoutSessionId: session.id,
|
|
222
219
|
purchaseId: purchase?.purchaseId ?? current.purchaseId,
|
|
223
|
-
firstInvoiceId: current.firstInvoiceId ??
|
|
220
|
+
firstInvoiceId: current.firstInvoiceId ?? session.invoiceId,
|
|
224
221
|
currency: current.currency ?? (evidence.currency !== '' ? evidence.currency : undefined),
|
|
225
222
|
country: evidence.country ?? current.country,
|
|
226
223
|
email: evidence.email ?? current.email,
|
|
@@ -238,25 +235,25 @@ export const createEventHandler = (ctx: ApiContext, stripe: Stripe): StripeEvent
|
|
|
238
235
|
await settle(session, 'paid')
|
|
239
236
|
}
|
|
240
237
|
|
|
241
|
-
const checkoutFailed = async (session:
|
|
238
|
+
const checkoutFailed = async (paygate: Paygate, session: CheckoutSnapshot): Promise<void> => {
|
|
242
239
|
const metadata = session.metadata ?? {}
|
|
243
|
-
const customerId =
|
|
240
|
+
const customerId = session.customerId
|
|
244
241
|
const entityId = metadata.entityId
|
|
245
|
-
?? (customerId != null ? (await access.paygateCustomers().loadByPgId(customerId,
|
|
242
|
+
?? (customerId != null ? (await access.paygateCustomers().loadByPgId(customerId, paygate.id))?.entityId : undefined)
|
|
246
243
|
if (entityId == null) {
|
|
247
244
|
log.warn('Failed checkout belongs to no known entity', { sessionId: session.id })
|
|
248
245
|
return
|
|
249
246
|
}
|
|
250
247
|
if (session.mode === 'payment' && metadata.productSku != null && metadata.service != null) {
|
|
251
248
|
const ledger = access.fulfillments()
|
|
252
|
-
const stored = await ledger.byExternalId(session.id,
|
|
249
|
+
const stored = await ledger.byExternalId(session.id, paygate.id)
|
|
253
250
|
if (stored == null) {
|
|
254
251
|
try {
|
|
255
252
|
await ledger.create(paymentUtils.compact({
|
|
256
253
|
entityId, productSku: metadata.productSku, planSku: metadata.planSku, service: metadata.service,
|
|
257
|
-
paygate:
|
|
254
|
+
paygate: paygate.id, externalId: session.id,
|
|
258
255
|
mode: metadata.pricingMode === CheckoutPricingMode.Amount ? CheckoutPricingMode.Amount : CheckoutPricingMode.Quantity,
|
|
259
|
-
paymentIntentId:
|
|
256
|
+
paymentIntentId: session.paymentId, createdAt: new Date(), failedAt: new Date(),
|
|
260
257
|
}) as PaymentFulfillmentRecord)
|
|
261
258
|
} catch (error) {
|
|
262
259
|
if (!paymentUtils.isDuplicateKey(error)) throw error
|
|
@@ -267,62 +264,54 @@ export const createEventHandler = (ctx: ApiContext, stripe: Stripe): StripeEvent
|
|
|
267
264
|
}
|
|
268
265
|
await access.observer().propagatePaymentFailed(paymentUtils.compact({
|
|
269
266
|
entityId, kind: 'checkout' as const, externalId: session.id,
|
|
270
|
-
subscriptionId:
|
|
267
|
+
subscriptionId: session.subscriptionId, eventKey: `payment-failed:${session.id}:0`,
|
|
271
268
|
}), ctx)
|
|
272
269
|
log.info('Payment failed', paymentUtils.compact({
|
|
273
|
-
entityId, kind: 'checkout', sessionId: session.id, subscriptionId:
|
|
270
|
+
entityId, kind: 'checkout', sessionId: session.id, subscriptionId: session.subscriptionId,
|
|
274
271
|
}), { event: 'payment.failed' })
|
|
275
272
|
await settle(session, 'failed', entityId)
|
|
276
273
|
}
|
|
277
274
|
|
|
278
|
-
const purgeExpiredCheckout = async (session:
|
|
279
|
-
await access.fulfillments().purge({ paygate:
|
|
275
|
+
const purgeExpiredCheckout = async (paygate: Paygate, session: CheckoutSnapshot): Promise<void> => {
|
|
276
|
+
await access.fulfillments().purge({ paygate: paygate.id, externalId: session.id, fulfilledAt: null })
|
|
280
277
|
await settle(session, 'expired')
|
|
281
278
|
}
|
|
282
279
|
|
|
283
|
-
const
|
|
284
|
-
const subscription = event.
|
|
285
|
-
await
|
|
286
|
-
await
|
|
287
|
-
source: 'webhook', eventId: event.
|
|
280
|
+
const subscriptionChanged = async (paygate: Paygate, event: SubscriptionChangedEvent): Promise<void> => {
|
|
281
|
+
const subscription = event.subscription
|
|
282
|
+
await lock(paygate.id, subscription.customerId, async () => {
|
|
283
|
+
await subscriptions.applySubscription(paygate, subscription, {
|
|
284
|
+
source: 'webhook', eventId: event.eventId, eventCreated: event.createdAt,
|
|
285
|
+
...(event.deleted ? { forced: SubscriptionStatus.Canceled } : {}),
|
|
286
|
+
...(event.trialEnding ? { trialEnding: true } : {}),
|
|
288
287
|
})
|
|
289
288
|
})
|
|
290
289
|
}
|
|
291
290
|
|
|
292
291
|
const reapplyInvoiceSubscription = async (
|
|
293
|
-
|
|
292
|
+
paygate: Paygate, eventId: string, invoice: EventInvoice, opts: Partial<ApplyOptions> = {},
|
|
294
293
|
): Promise<CommitResult | null> => {
|
|
295
|
-
const subscriptionId =
|
|
296
|
-
if (subscriptionId == null) return null
|
|
297
|
-
const subscription = await
|
|
294
|
+
const subscriptionId = invoice.subscriptionId
|
|
295
|
+
if (subscriptionId == null || paygate.subscriptions == null) return null
|
|
296
|
+
const subscription = await subscriptions.retrieveSubscription(paygate, subscriptionId)
|
|
298
297
|
if (subscription == null) {
|
|
299
|
-
return await
|
|
300
|
-
async () => await stripeSubscriptions.cancelMissing(subscriptionId))
|
|
298
|
+
return await lock(paygate.id, invoice.customerId, async () => await subscriptions.cancelMissing(paygate, subscriptionId))
|
|
301
299
|
}
|
|
302
300
|
|
|
303
|
-
return await
|
|
304
|
-
await
|
|
301
|
+
return await lock(paygate.id, subscription.customerId, async () =>
|
|
302
|
+
await subscriptions.applySubscription(paygate, subscription, { source: 'webhook', eventId, ...opts }))
|
|
305
303
|
}
|
|
306
304
|
|
|
307
|
-
const
|
|
308
|
-
const
|
|
309
|
-
if (invoice.billing_reason === 'subscription_cycle') {
|
|
310
|
-
await reapplyInvoiceSubscription(event, invoice, { renewal: true, invoiceId: invoice.id })
|
|
311
|
-
return
|
|
312
|
-
}
|
|
313
|
-
await refreshLatestInvoice(invoice, invoice.id)
|
|
314
|
-
}
|
|
315
|
-
|
|
316
|
-
const refreshLatestInvoice = async (invoice: Stripe.Invoice, latestInvoiceId?: string): Promise<void> => {
|
|
317
|
-
const subscriptionId = subscriptionIdOfInvoice(invoice)
|
|
305
|
+
const refreshLatestInvoice = async (paygate: Paygate, invoice: EventInvoice, latestInvoiceId?: string): Promise<void> => {
|
|
306
|
+
const subscriptionId = invoice.subscriptionId
|
|
318
307
|
if (subscriptionId == null) return
|
|
319
|
-
await
|
|
320
|
-
const row = await access.subscriptions().byExternalId(subscriptionId,
|
|
308
|
+
await lock(paygate.id, invoice.customerId, async () => {
|
|
309
|
+
const row = await access.subscriptions().byExternalId(subscriptionId, paygate.id)
|
|
321
310
|
if (row == null) return
|
|
322
311
|
let latest = latestInvoiceId
|
|
323
312
|
if (latest == null) {
|
|
324
|
-
const subscription = await
|
|
325
|
-
latest =
|
|
313
|
+
const subscription = await subscriptions.retrieveSubscription(paygate, subscriptionId)
|
|
314
|
+
latest = subscription?.latestInvoiceId
|
|
326
315
|
}
|
|
327
316
|
if (latest != null && row.latestInvoiceId !== latest) {
|
|
328
317
|
await access.subscriptions().update({ ...row, latestInvoiceId: latest, updatedAt: new Date() })
|
|
@@ -330,28 +319,50 @@ export const createEventHandler = (ctx: ApiContext, stripe: Stripe): StripeEvent
|
|
|
330
319
|
})
|
|
331
320
|
}
|
|
332
321
|
|
|
333
|
-
const invoiceFailed
|
|
334
|
-
const invoice = event.
|
|
335
|
-
const result = await reapplyInvoiceSubscription(event, invoice)
|
|
336
|
-
const customerId =
|
|
322
|
+
const invoiceFailed = async (paygate: Paygate, event: InvoiceEvent): Promise<void> => {
|
|
323
|
+
const invoice = event.invoice
|
|
324
|
+
const result = await reapplyInvoiceSubscription(paygate, event.eventId, invoice)
|
|
325
|
+
const customerId = invoice.customerId
|
|
337
326
|
const entityId = result?.record?.entityId
|
|
338
|
-
?? (customerId != null ? (await access.paygateCustomers().loadByPgId(customerId,
|
|
327
|
+
?? (customerId != null ? (await access.paygateCustomers().loadByPgId(customerId, paygate.id))?.entityId : undefined)
|
|
339
328
|
if (entityId == null) {
|
|
340
329
|
log.warn('Failed invoice belongs to no known entity', { invoiceId: invoice.id })
|
|
341
330
|
return
|
|
342
331
|
}
|
|
343
|
-
const attempt = invoice.
|
|
332
|
+
const attempt = invoice.attempt ?? 0
|
|
333
|
+
const actionRequired = event.change === 'action-required'
|
|
344
334
|
await access.observer().propagatePaymentFailed(paymentUtils.compact({
|
|
345
|
-
entityId, kind: 'invoice' as const, externalId: invoice.id, subscriptionId:
|
|
346
|
-
invoiceId: invoice.id, attempt, actionRequired
|
|
347
|
-
nextAttemptAt:
|
|
335
|
+
entityId, kind: 'invoice' as const, externalId: invoice.id, subscriptionId: invoice.subscriptionId,
|
|
336
|
+
invoiceId: invoice.id, attempt, actionRequired,
|
|
337
|
+
nextAttemptAt: invoice.nextAttemptAt, eventKey: `payment-failed:${invoice.id}:${attempt}`,
|
|
348
338
|
}), ctx)
|
|
349
339
|
log.info('Payment failed', paymentUtils.compact({
|
|
350
|
-
entityId, kind: 'invoice', invoiceId: invoice.id, subscriptionId:
|
|
351
|
-
actionRequired: event.type === 'invoice.payment_action_required',
|
|
340
|
+
entityId, kind: 'invoice', invoiceId: invoice.id, subscriptionId: invoice.subscriptionId, attempt, actionRequired,
|
|
352
341
|
}), { event: 'payment.failed' })
|
|
353
342
|
}
|
|
354
343
|
|
|
344
|
+
const invoiceChanged = async (paygate: Paygate, event: InvoiceEvent): Promise<void> => {
|
|
345
|
+
const invoice = event.invoice
|
|
346
|
+
switch (event.change) {
|
|
347
|
+
case 'paid':
|
|
348
|
+
if (invoice.renewal) {
|
|
349
|
+
await reapplyInvoiceSubscription(paygate, event.eventId, invoice, { renewal: true, invoiceId: invoice.id })
|
|
350
|
+
return
|
|
351
|
+
}
|
|
352
|
+
await refreshLatestInvoice(paygate, invoice, invoice.id)
|
|
353
|
+
return
|
|
354
|
+
case 'payment-failed':
|
|
355
|
+
case 'action-required':
|
|
356
|
+
await invoiceFailed(paygate, event)
|
|
357
|
+
return
|
|
358
|
+
case 'uncollectible':
|
|
359
|
+
await reapplyInvoiceSubscription(paygate, event.eventId, invoice)
|
|
360
|
+
return
|
|
361
|
+
case 'voided':
|
|
362
|
+
await refreshLatestInvoice(paygate, invoice)
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
|
|
355
366
|
const targetFields = (target: PaymentTarget) => target.kind === 'fulfillment'
|
|
356
367
|
? paymentUtils.compact({
|
|
357
368
|
entityId: target.record.entityId, target: target.kind, productSku: target.record.productSku,
|
|
@@ -365,8 +376,10 @@ export const createEventHandler = (ctx: ApiContext, stripe: Stripe): StripeEvent
|
|
|
365
376
|
})
|
|
366
377
|
|
|
367
378
|
/** A refund of a purchase's payment moves its refunded total; a whole refund closes its window. */
|
|
368
|
-
const refundPurchase = async (
|
|
369
|
-
|
|
379
|
+
const refundPurchase = async (
|
|
380
|
+
paygate: Paygate, target: PaymentTarget, refundedTotal: number, paid: number | undefined,
|
|
381
|
+
): Promise<void> => {
|
|
382
|
+
const purchaseId = consumerRecordsOf(ctx).purchaseIdOf(paygate.id, target.record.externalId)
|
|
370
383
|
const purchase = await access.purchases().byPurchaseId(purchaseId)
|
|
371
384
|
if (purchase == null || (target.kind === 'subscription' && purchase.invoiceId != null && purchase.invoiceId !== target.invoiceId)) {
|
|
372
385
|
return
|
|
@@ -377,33 +390,33 @@ export const createEventHandler = (ctx: ApiContext, stripe: Stripe): StripeEvent
|
|
|
377
390
|
}))
|
|
378
391
|
}
|
|
379
392
|
|
|
380
|
-
const processRefund = async (refund:
|
|
381
|
-
if (refund.
|
|
382
|
-
const target = await paymentTargetOf(ctx).resolvePaymentTarget(
|
|
383
|
-
paymentIntentId:
|
|
393
|
+
const processRefund = async (paygate: Paygate, refund: PaygateRefund, charge?: PaygateCharge | null): Promise<void> => {
|
|
394
|
+
if (!refund.succeeded) return
|
|
395
|
+
const target = await paymentTargetOf(ctx).resolvePaymentTarget(paygate, {
|
|
396
|
+
paymentIntentId: refund.paymentId, chargeId: refund.chargeId, charge,
|
|
384
397
|
})
|
|
385
398
|
if (target == null) {
|
|
386
399
|
log.warn('Refund matches no fulfillment or subscription', { refundId: refund.id })
|
|
387
400
|
return
|
|
388
401
|
}
|
|
389
|
-
const chargeId =
|
|
390
|
-
const refunded = target.charge ?? (chargeId != null ? await paymentTargetOf(ctx).retrieveCharge(
|
|
391
|
-
const refundedTotal = Math.max(refunded?.
|
|
392
|
-
const paid = refunded?.
|
|
402
|
+
const chargeId = refund.chargeId
|
|
403
|
+
const refunded = target.charge ?? (chargeId != null ? await paymentTargetOf(ctx).retrieveCharge(paygate, chargeId) : null)
|
|
404
|
+
const refundedTotal = Math.max(refunded?.refundedMinor ?? 0, refund.amountMinor)
|
|
405
|
+
const paid = refunded?.amountMinor
|
|
393
406
|
if (target.kind === 'fulfillment') {
|
|
394
407
|
await access.fulfillments().update(paymentUtils.compact({
|
|
395
408
|
...target.record, refundedMinor: Math.max(target.record.refundedMinor ?? 0, refundedTotal),
|
|
396
409
|
refundedAt: new Date(), chargeId: target.record.chargeId ?? refunded?.id,
|
|
397
410
|
}))
|
|
398
411
|
}
|
|
399
|
-
await refundPurchase(target, refundedTotal, paid)
|
|
412
|
+
await refundPurchase(paygate, target, refundedTotal, paid)
|
|
400
413
|
const metadata = { ...(refund.metadata ?? {}) } as Record<string, string>
|
|
401
414
|
await access.observer().propagateRefund(paymentUtils.compact({
|
|
402
415
|
...targetFields(target),
|
|
403
416
|
refundId: refund.id,
|
|
404
|
-
paymentIntentId: target.paymentIntentId ??
|
|
417
|
+
paymentIntentId: target.paymentIntentId ?? refund.paymentId,
|
|
405
418
|
invoiceId: target.kind === 'subscription' ? target.invoiceId : target.record.invoiceId ?? undefined,
|
|
406
|
-
amountMinor: refund.
|
|
419
|
+
amountMinor: refund.amountMinor,
|
|
407
420
|
refundedTotalMinor: refundedTotal,
|
|
408
421
|
paidMinor: paid,
|
|
409
422
|
currency: refund.currency,
|
|
@@ -415,35 +428,22 @@ export const createEventHandler = (ctx: ApiContext, stripe: Stripe): StripeEvent
|
|
|
415
428
|
}) as RefundEvent, ctx)
|
|
416
429
|
log.info('Payment refunded', paymentUtils.compact({
|
|
417
430
|
entityId: target.record.entityId, target: target.kind, externalId: target.record.externalId, refundId: refund.id,
|
|
418
|
-
amountMinor: refund.
|
|
431
|
+
amountMinor: refund.amountMinor, refundedTotalMinor: refundedTotal, paidMinor: paid, currency: refund.currency,
|
|
419
432
|
withdrawalId: metadata.withdrawalId != null && metadata.withdrawalId !== '' ? metadata.withdrawalId : undefined,
|
|
420
433
|
}), { event: 'payment.refunded' })
|
|
421
434
|
}
|
|
422
435
|
|
|
423
|
-
const
|
|
424
|
-
const
|
|
425
|
-
const
|
|
426
|
-
|
|
427
|
-
await processRefund(refund, charge)
|
|
428
|
-
}
|
|
429
|
-
}
|
|
430
|
-
|
|
431
|
-
const refundChanged: EventHandler = async event => {
|
|
432
|
-
await processRefund(event.data.object as Stripe.Refund)
|
|
433
|
-
}
|
|
434
|
-
|
|
435
|
-
const disputeChanged: EventHandler = async event => {
|
|
436
|
-
const dispute = event.data.object as Stripe.Dispute
|
|
437
|
-
const phase = DISPUTE_PHASES[event.type]
|
|
438
|
-
const target = await paymentTargetOf(ctx).resolvePaymentTarget(stripe, {
|
|
439
|
-
paymentIntentId: paymentUtils.idOf(dispute.payment_intent), chargeId: paymentUtils.idOf(dispute.charge),
|
|
436
|
+
const disputeChanged = async (paygate: Paygate, event: DisputeChangedEvent): Promise<void> => {
|
|
437
|
+
const { dispute, phase } = event
|
|
438
|
+
const target = await paymentTargetOf(ctx).resolvePaymentTarget(paygate, {
|
|
439
|
+
paymentIntentId: dispute.paymentId, chargeId: dispute.chargeId,
|
|
440
440
|
})
|
|
441
441
|
if (target == null) {
|
|
442
442
|
log.warn('Dispute matches no fulfillment or subscription', { disputeId: dispute.id })
|
|
443
443
|
return
|
|
444
444
|
}
|
|
445
|
-
const chargeId =
|
|
446
|
-
const charge = target.charge ?? (chargeId != null ? await paymentTargetOf(ctx).retrieveCharge(
|
|
445
|
+
const chargeId = dispute.chargeId
|
|
446
|
+
const charge = target.charge ?? (chargeId != null ? await paymentTargetOf(ctx).retrieveCharge(paygate, chargeId) : null)
|
|
447
447
|
const marks = { disputedAt: target.record.disputedAt ?? new Date(), disputeStatus: dispute.status }
|
|
448
448
|
if (target.kind === 'fulfillment') {
|
|
449
449
|
await access.fulfillments().update({ ...target.record, ...marks })
|
|
@@ -452,67 +452,49 @@ export const createEventHandler = (ctx: ApiContext, stripe: Stripe): StripeEvent
|
|
|
452
452
|
}
|
|
453
453
|
await access.observer().propagateDispute(paymentUtils.compact({
|
|
454
454
|
...targetFields(target), disputeId: dispute.id, phase, status: dispute.status,
|
|
455
|
-
amountMinor: dispute.
|
|
455
|
+
amountMinor: dispute.amountMinor, paidMinor: charge?.amountMinor, currency: dispute.currency,
|
|
456
|
+
eventKey: `dispute:${dispute.id}:${phase}`,
|
|
456
457
|
}) as DisputeEvent, ctx)
|
|
457
458
|
log.info('Dispute changed', paymentUtils.compact({
|
|
458
459
|
entityId: target.record.entityId, target: target.kind, externalId: target.record.externalId,
|
|
459
|
-
disputeId: dispute.id, phase, status: dispute.status, amountMinor: dispute.
|
|
460
|
+
disputeId: dispute.id, phase, status: dispute.status, amountMinor: dispute.amountMinor, currency: dispute.currency,
|
|
460
461
|
}), { event: phase === 'opened' ? 'dispute.opened' : phase === 'closed' ? 'dispute.closed' : 'dispute.updated' })
|
|
461
462
|
}
|
|
462
463
|
|
|
463
|
-
const
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
'invoice.marked_uncollectible': async event => {
|
|
494
|
-
await reapplyInvoiceSubscription(event, event.data.object as Stripe.Invoice)
|
|
495
|
-
},
|
|
496
|
-
'invoice.voided': async event => { await refreshLatestInvoice(event.data.object as Stripe.Invoice) },
|
|
497
|
-
|
|
498
|
-
'charge.refunded': chargeRefunded,
|
|
499
|
-
'refund.created': refundChanged,
|
|
500
|
-
'refund.updated': refundChanged,
|
|
501
|
-
'refund.failed': async () => undefined,
|
|
502
|
-
|
|
503
|
-
'charge.dispute.created': disputeChanged,
|
|
504
|
-
'charge.dispute.funds_withdrawn': disputeChanged,
|
|
505
|
-
'charge.dispute.funds_reinstated': disputeChanged,
|
|
506
|
-
'charge.dispute.closed': disputeChanged,
|
|
464
|
+
const apply = async (paygate: Paygate, event: PaygateEvent): Promise<void> => {
|
|
465
|
+
switch (event.type) {
|
|
466
|
+
case 'customer':
|
|
467
|
+
if (event.change === 'deleted') {
|
|
468
|
+
await markCustomerDeleted(paygate, event.customer.id)
|
|
469
|
+
} else {
|
|
470
|
+
await upsertCustomer(paygate, event.customer)
|
|
471
|
+
}
|
|
472
|
+
return
|
|
473
|
+
case 'checkout':
|
|
474
|
+
if (event.outcome === 'completed') {
|
|
475
|
+
await fulfillPayment(paygate, event.session)
|
|
476
|
+
} else if (event.outcome === 'failed') {
|
|
477
|
+
await checkoutFailed(paygate, event.session)
|
|
478
|
+
} else {
|
|
479
|
+
await purgeExpiredCheckout(paygate, event.session)
|
|
480
|
+
}
|
|
481
|
+
return
|
|
482
|
+
case 'subscription':
|
|
483
|
+
await subscriptionChanged(paygate, event)
|
|
484
|
+
return
|
|
485
|
+
case 'invoice':
|
|
486
|
+
await invoiceChanged(paygate, event)
|
|
487
|
+
return
|
|
488
|
+
case 'refund':
|
|
489
|
+
await processRefund(paygate, event.refund, event.charge)
|
|
490
|
+
return
|
|
491
|
+
case 'dispute':
|
|
492
|
+
await disputeChanged(paygate, event)
|
|
493
|
+
}
|
|
507
494
|
}
|
|
508
495
|
|
|
509
|
-
return {
|
|
510
|
-
handlers,
|
|
511
|
-
process: async (event: Stripe.Event): Promise<void> => {
|
|
512
|
-
const handler = handlers[event.type]
|
|
513
|
-
if (handler != null) {
|
|
514
|
-
await handler(event)
|
|
515
|
-
}
|
|
516
|
-
},
|
|
517
|
-
}
|
|
496
|
+
return { apply }
|
|
518
497
|
}
|
|
498
|
+
|
|
499
|
+
/** The paygate event dispatch of a context — one per context. */
|
|
500
|
+
export const paymentEventsOf = memoHelper.oncePer(makePaymentEventsHelper)
|