@owlmeans/server-payment 0.1.20-rc.1 → 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/catalogue.ts
CHANGED
|
@@ -2,7 +2,6 @@ import type { PermissionSet } from '@owlmeans/auth'
|
|
|
2
2
|
import { ENTITLING_STATUSES, PlanRequired, ProductError, promoHelper } from '@owlmeans/payment'
|
|
3
3
|
import type { Context as ApiContext } from '@owlmeans/server-api'
|
|
4
4
|
import { memoHelper } from '@owlmeans/context'
|
|
5
|
-
import { STRIPE_PAYGATE_ALIAS } from './consts.js'
|
|
6
5
|
import { paymentAccessOf } from './access.js'
|
|
7
6
|
import { planHelper } from './plan.js'
|
|
8
7
|
import { subscriptionHelper } from './subscription.js'
|
|
@@ -97,15 +96,12 @@ export const makeCatalogueHelper = (ctx: ApiContext): CatalogueHelper => {
|
|
|
97
96
|
.map(({ promo: _promo, ...set }) => set)
|
|
98
97
|
}
|
|
99
98
|
|
|
100
|
-
const
|
|
99
|
+
const plansSoldThrough = async (paygate: string): Promise<Array<{ product: PaymentProduct, plans: PaymentPlan[] }>> => {
|
|
101
100
|
const products = await access.payment().products() as PaymentProduct[]
|
|
102
101
|
const result: Array<{ product: PaymentProduct, plans: PaymentPlan[] }> = []
|
|
103
102
|
for (const product of products) {
|
|
104
|
-
if (!(product.gateways ?? []).includes(STRIPE_PAYGATE_ALIAS)) {
|
|
105
|
-
continue
|
|
106
|
-
}
|
|
107
103
|
const plans = (await access.payment().allPlans(product.sku) as PaymentPlan[])
|
|
108
|
-
.filter(plan => planHelper.isSoldThrough(product, plan,
|
|
104
|
+
.filter(plan => planHelper.isSoldThrough(product, plan, paygate))
|
|
109
105
|
if (plans.length > 0) {
|
|
110
106
|
result.push({ product, plans })
|
|
111
107
|
}
|
|
@@ -119,7 +115,7 @@ export const makeCatalogueHelper = (ctx: ApiContext): CatalogueHelper => {
|
|
|
119
115
|
): Promise<{ product: PaymentProduct, plan: PaymentPlan }> => {
|
|
120
116
|
const product = await access.payment().product(productSku) as PaymentProduct
|
|
121
117
|
const plans = (await access.payment().allPlans(product.sku) as PaymentPlan[])
|
|
122
|
-
.filter(plan => planHelper.
|
|
118
|
+
.filter(plan => planHelper.isForSale(product, plan))
|
|
123
119
|
if (planSku != null && !plans.some(plan => plan.sku === planSku)) {
|
|
124
120
|
throw new ProductError(`plan:${planSku}`)
|
|
125
121
|
}
|
|
@@ -130,7 +126,7 @@ export const makeCatalogueHelper = (ctx: ApiContext): CatalogueHelper => {
|
|
|
130
126
|
}
|
|
131
127
|
|
|
132
128
|
return {
|
|
133
|
-
findPlan, findProduct, catalogPlans, freePlanOf, resolveEffectivePlan, entitlementsOf,
|
|
129
|
+
findPlan, findProduct, catalogPlans, freePlanOf, resolveEffectivePlan, entitlementsOf, plansSoldThrough,
|
|
134
130
|
consumablePlanOf,
|
|
135
131
|
}
|
|
136
132
|
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { CheckoutPlugin, CreateLinkParams } from '../types.js'
|
|
2
|
+
|
|
3
|
+
/** The checkout of a context, through any registered paygate. */
|
|
4
|
+
export interface CheckoutHelper {
|
|
5
|
+
/**
|
|
6
|
+
* A paygate checkout URL: an amount or quantity purchase of a consumable product, or a subscription
|
|
7
|
+
* to `planSku` (else the product's first recurring plan). The paygate is `params.paygate`, else the
|
|
8
|
+
* first registered one the plan is for sale through (`paygatesOf(ctx).forSale`); a plan no paygate
|
|
9
|
+
* sells is refused (`ProductError('plan:<sku>')`). A free plan is never checked out.
|
|
10
|
+
*
|
|
11
|
+
* With a consumer-rights policy: a locked billing country overrides the declared one (another is
|
|
12
|
+
* `BillingCountryLocked`); the charge currency is the profile's, else the region's; an amount
|
|
13
|
+
* checkout is narrowed by the checkout plugins (`CheckoutLimitExceeded`) and charged without FX
|
|
14
|
+
* when its policy currency is the charge currency; a subscription needs a fresh start request
|
|
15
|
+
* bound to its plan; the terms checkbox and the legal submit texts come from the copy.
|
|
16
|
+
*
|
|
17
|
+
* Under the paygate's customer e-mail lock the session's customer carries `params.email`
|
|
18
|
+
* (required, else `PaygateError('customer-email')`), so the paygate shows it read-only.
|
|
19
|
+
*/
|
|
20
|
+
createCheckoutLink: (params: CreateLinkParams, plugins?: readonly CheckoutPlugin[]) => Promise<string>
|
|
21
|
+
}
|
package/src/checkout.ts
ADDED
|
@@ -0,0 +1,414 @@
|
|
|
1
|
+
import {
|
|
2
|
+
BillingCountryLocked, CheckoutPricingMode, CONSUMER_RIGHTS_COPY_VERSION, ConsumerRightsError, PaygateError,
|
|
3
|
+
ProductError, ProductType, TaxBehavior, checkoutPricingHelper, consumerCopyHelper, consumerRegionHelper,
|
|
4
|
+
consumerRightsPolicyHelper,
|
|
5
|
+
} from '@owlmeans/payment'
|
|
6
|
+
import type { Context as ApiContext } from '@owlmeans/server-api'
|
|
7
|
+
import { memoHelper } from '@owlmeans/context'
|
|
8
|
+
import type { Admitted } from './plugins/types.js'
|
|
9
|
+
import type {
|
|
10
|
+
CheckoutAttempt, CheckoutPlugin, CheckoutTextContext, CreateLinkParams, PaymentPlan, PaymentProduct,
|
|
11
|
+
} from './types.js'
|
|
12
|
+
import type { Paygate, PaygateCustomer, PaygatePrice, PaygateSession, SessionInput } from './paygate/types.js'
|
|
13
|
+
import { log } from './log.js'
|
|
14
|
+
import { EMAIL } from './plugins/consts.local.js'
|
|
15
|
+
import type { BuyerContext } from './plugins/types.local.js'
|
|
16
|
+
import { fxOf } from './plugins/fx.js'
|
|
17
|
+
import { paymentAccessOf } from './access.js'
|
|
18
|
+
import { paymentUtils } from './utils.js'
|
|
19
|
+
import { planHelper } from './plan.js'
|
|
20
|
+
import { paygatesOf } from './paygate/registry.js'
|
|
21
|
+
import { checkoutPluginsOf } from './plugins/checkout-plugins.js'
|
|
22
|
+
import { checkoutPolicyHelper } from './plugins/checkout-policy.js'
|
|
23
|
+
import type { CheckoutHelper } from './checkout/types.js'
|
|
24
|
+
import { consumerFormatHelper } from './consumer/format.js'
|
|
25
|
+
import { consumerRecordsOf } from './consumer/records.js'
|
|
26
|
+
|
|
27
|
+
/** The metadata every session carries: what the checkout events read back. */
|
|
28
|
+
const sharedMetadata = (
|
|
29
|
+
params: CreateLinkParams, product: PaymentProduct, plan: PaymentPlan, metadata: Record<string, string>,
|
|
30
|
+
): Record<string, string> => ({
|
|
31
|
+
pricingMode: plan.pricingMode ?? CheckoutPricingMode.Quantity,
|
|
32
|
+
currency: (plan.currency ?? 'usd').toLowerCase(),
|
|
33
|
+
entityId: params.entityId,
|
|
34
|
+
...(params.profileId && { profileId: params.profileId }),
|
|
35
|
+
service: params.service,
|
|
36
|
+
productSku: product.sku,
|
|
37
|
+
planSku: plan.sku,
|
|
38
|
+
...metadata,
|
|
39
|
+
})
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* The consumer-rights metadata every session (and its subscription) carries. `termsCollected`
|
|
43
|
+
* says whether the session asks for the terms checkbox — a paygate that drops it says `'false'`;
|
|
44
|
+
* `countryPinned` that tax was calculated on `country`, held on the customer by the paygate's
|
|
45
|
+
* customer country lock, so that country is the one the purchase locks.
|
|
46
|
+
*/
|
|
47
|
+
const consumerMetadata = (buyer: BuyerContext, params: CreateLinkParams, startRequestId?: string): Record<string, string> =>
|
|
48
|
+
buyer.policy == null ? {} : paymentUtils.compact({
|
|
49
|
+
region: buyer.region ?? undefined,
|
|
50
|
+
country: buyer.country,
|
|
51
|
+
language: buyer.language,
|
|
52
|
+
termsVersion: buyer.policy.textVersion,
|
|
53
|
+
copyVersion: CONSUMER_RIGHTS_COPY_VERSION,
|
|
54
|
+
termsCollected: String(buyer.policy.mechanisms.checkoutTerms === true),
|
|
55
|
+
ipCountry: params.ipCountry?.toUpperCase(),
|
|
56
|
+
startRequestId,
|
|
57
|
+
countryPinned: buyer.countryPinned ? 'true' : undefined,
|
|
58
|
+
}) as Record<string, string>
|
|
59
|
+
|
|
60
|
+
const textContextOf = (buyer: BuyerContext, currency: string, extra: Partial<CheckoutTextContext> = {}): CheckoutTextContext => paymentUtils.compact({
|
|
61
|
+
language: buyer.language, currency, region: buyer.region, country: buyer.country, ...extra,
|
|
62
|
+
}) as CheckoutTextContext
|
|
63
|
+
|
|
64
|
+
const submitTextOf = (params: CreateLinkParams, context: CheckoutTextContext): string | undefined => {
|
|
65
|
+
if (params.submitText == null) {
|
|
66
|
+
return undefined
|
|
67
|
+
}
|
|
68
|
+
const message = typeof params.submitText === 'function' ? params.submitText(context) : params.submitText
|
|
69
|
+
|
|
70
|
+
return message.trim() === '' ? undefined : message
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export const makeCheckoutHelper = (ctx: ApiContext): CheckoutHelper => {
|
|
74
|
+
const access = paymentAccessOf(ctx)
|
|
75
|
+
|
|
76
|
+
/** A text within the paygate's `customTextMax`. @throws ConsumerRightsError('copy:length:<field>') */
|
|
77
|
+
const limited = (paygate: Paygate, message: string, field: string): string => {
|
|
78
|
+
const max = paygate.features.customTextMax
|
|
79
|
+
if (max != null && message.length > max) {
|
|
80
|
+
throw new ConsumerRightsError(`copy:length:${field}`)
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
return message
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** The terms checkbox and its text, when the policy asks for them on every checkout. */
|
|
87
|
+
const termsOf = (paygate: Paygate, buyer: BuyerContext): { collect: boolean, text?: string } => {
|
|
88
|
+
const policy = buyer.policy
|
|
89
|
+
if (policy?.mechanisms.checkoutTerms !== true) {
|
|
90
|
+
return { collect: false }
|
|
91
|
+
}
|
|
92
|
+
const links = consumerRightsPolicyHelper.linksOf(policy, buyer.language)
|
|
93
|
+
const withInformation = buyer.inScope && links.withdrawalInformation != null
|
|
94
|
+
const message = limited(paygate, consumerCopyHelper.consumerText(buyer.language, `checkout.terms-acceptance.${withInformation ? 'in-scope' : 'other'}`, {
|
|
95
|
+
billingTerms: links.billingTerms, ...(withInformation ? { withdrawalInformation: links.withdrawalInformation as string } : {}),
|
|
96
|
+
}), 'terms')
|
|
97
|
+
|
|
98
|
+
return { collect: true, text: message }
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* The e-mail a checkout pins on its paygate customer: `params.email` under the paygate's customer
|
|
103
|
+
* e-mail lock, `undefined` without the lock.
|
|
104
|
+
*
|
|
105
|
+
* @throws PaygateError('customer-email') — the lock is declared and no usable e-mail was passed
|
|
106
|
+
*/
|
|
107
|
+
const lockedEmailOf = async (paygate: Paygate, params: CreateLinkParams): Promise<string | undefined> => {
|
|
108
|
+
if ((await paygate.customers.locks()).email !== true) {
|
|
109
|
+
return undefined
|
|
110
|
+
}
|
|
111
|
+
const email = params.email?.trim()
|
|
112
|
+
if (email == null || !EMAIL.test(email)) {
|
|
113
|
+
throw new PaygateError('customer-email')
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
return email
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* The buyer as the consumer-rights policy sees it — a locked profile overrides the declared
|
|
121
|
+
* country (a different one is `BillingCountryLocked`), an organization that already paid before
|
|
122
|
+
* its country was locked is locked lazily from its paygate customer's address, and a locked
|
|
123
|
+
* customer address that no longer carries the locked country refuses (the operator relocks).
|
|
124
|
+
*
|
|
125
|
+
* Under the paygate's customer country lock the known country (the locked one, else the declared
|
|
126
|
+
* one) is written to the customer — over a saved address of another country only before any lock —
|
|
127
|
+
* and the session keeps it wherever the paygate can calculate tax on it.
|
|
128
|
+
*/
|
|
129
|
+
const buyerOf = async (
|
|
130
|
+
paygate: Paygate, params: CreateLinkParams, catalogueCurrency: string,
|
|
131
|
+
): Promise<{ buyer: BuyerContext, customer: PaygateCustomer }> => {
|
|
132
|
+
const policy = await access.payment().consumerRightsPolicy()
|
|
133
|
+
const rights = policy != null ? access.consumerRightsOf() : null
|
|
134
|
+
let profile = rights != null ? await rights.profile(params.entityId) : null
|
|
135
|
+
const declared = params.country != null && params.country.trim() !== '' ? params.country.trim().toUpperCase() : undefined
|
|
136
|
+
if (profile?.locked === true && declared != null && declared !== profile.country) {
|
|
137
|
+
throw new BillingCountryLocked({ country: profile.country as string, requested: declared })
|
|
138
|
+
}
|
|
139
|
+
const email = await lockedEmailOf(paygate, params)
|
|
140
|
+
let customer = await paygate.customers.ensure(paymentUtils.compact({
|
|
141
|
+
entityId: params.entityId, profileId: params.profileId, service: params.service, locale: params.locale, email,
|
|
142
|
+
}))
|
|
143
|
+
const customerCountry = customer.country?.toUpperCase() ?? undefined
|
|
144
|
+
if (rights != null && policy?.mechanisms.countryLock === true && profile == null && customerCountry != null
|
|
145
|
+
&& await consumerRecordsOf(ctx).hasPaid(params.entityId)
|
|
146
|
+
&& !await consumerRecordsOf(ctx).wasUnlocked(params.entityId)) {
|
|
147
|
+
// An organization that paid before countries were locked: its saved address is its country.
|
|
148
|
+
// One an operator unlocked is locked again by its next completed purchase instead.
|
|
149
|
+
profile = await rights.lock(params.entityId, customerCountry, 'customer', { customerId: customer.id, paygate: paygate.id })
|
|
150
|
+
}
|
|
151
|
+
if (profile?.locked === true && declared != null && declared !== profile.country) {
|
|
152
|
+
throw new BillingCountryLocked({ country: profile.country as string, requested: declared })
|
|
153
|
+
}
|
|
154
|
+
if (profile?.locked === true && customerCountry != null && customerCountry !== profile.country) {
|
|
155
|
+
throw new BillingCountryLocked({ country: profile.country as string, requested: customerCountry })
|
|
156
|
+
}
|
|
157
|
+
const pinning = (await paygate.customers.locks()).country === true
|
|
158
|
+
const country = profile?.country ?? declared
|
|
159
|
+
if (pinning && country != null && customerCountry !== country) {
|
|
160
|
+
// Pinned: the known country replaces whatever an unlocked customer saved (a locked customer's
|
|
161
|
+
// other country was refused above), so the paygate has nothing else to offer.
|
|
162
|
+
customer = await paygate.customers.setCountry(customer.id, country, { replace: true })
|
|
163
|
+
} else if (policy != null && profile == null && declared != null && customerCountry == null) {
|
|
164
|
+
// Preselect the declared country on the paygate's address form; never over a saved address.
|
|
165
|
+
customer = await paygate.customers.setCountry(customer.id, declared, { replace: false })
|
|
166
|
+
}
|
|
167
|
+
const savedCountry = customer.country?.toUpperCase() ?? undefined
|
|
168
|
+
const kept = savedCountry != null && savedCountry === country && customer.taxLocatable
|
|
169
|
+
const countryPinned = pinning && kept
|
|
170
|
+
const region = policy != null ? consumerRegionHelper.regionOf(country, policy) : null
|
|
171
|
+
const settlement = (await paygate.settlementCurrency())?.toLowerCase()
|
|
172
|
+
const regional = policy?.currencies != null && Object.keys(policy.currencies).length > 0
|
|
173
|
+
|
|
174
|
+
return {
|
|
175
|
+
customer,
|
|
176
|
+
buyer: {
|
|
177
|
+
policy,
|
|
178
|
+
profile,
|
|
179
|
+
...(country != null ? { country } : {}),
|
|
180
|
+
region,
|
|
181
|
+
inScope: policy != null ? consumerRegionHelper.inScope(region, country, policy) : false,
|
|
182
|
+
language: params.consumerLanguage ?? profile?.language ?? consumerRegionHelper.billingLanguageOf(country, policy),
|
|
183
|
+
chargeCurrency: regional
|
|
184
|
+
? (profile?.currency ?? consumerRegionHelper.chargeCurrencyOf(region, policy, settlement ?? catalogueCurrency)).toLowerCase()
|
|
185
|
+
: null,
|
|
186
|
+
addressLocked: kept && (profile?.locked === true || countryPinned),
|
|
187
|
+
countryPinned,
|
|
188
|
+
},
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/** Whether the synced reusable price of a plan can be charged in `currency` (its default or a further currency). */
|
|
193
|
+
const priceCarries = async (
|
|
194
|
+
product: PaymentProduct, plan: PaymentPlan, price: PaygatePrice, currency: string,
|
|
195
|
+
): Promise<{ carries: boolean, unitAmount?: number }> => {
|
|
196
|
+
if (price.currency === currency) {
|
|
197
|
+
return { carries: true, ...(price.unitAmountMinor != null ? { unitAmount: price.unitAmountMinor } : {}) }
|
|
198
|
+
}
|
|
199
|
+
const listed = price.options[currency]
|
|
200
|
+
if (listed != null) {
|
|
201
|
+
return { carries: true, ...(listed.unitAmountMinor != null ? { unitAmount: listed.unitAmountMinor } : {}) }
|
|
202
|
+
}
|
|
203
|
+
const synced = (await access.fingerprints().bySku(product.sku))?.prices?.find(entry => entry.planSku === plan.sku && entry.priceId === price.id)
|
|
204
|
+
const option = synced?.options.find(entry => entry.currency === currency)
|
|
205
|
+
|
|
206
|
+
return option != null ? { carries: true, unitAmount: option.unitAmount } : { carries: false }
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* Create the session, then tell the plugins it exists. A plugin's `created` that throws expires
|
|
211
|
+
* the fresh session and releases every admission before the error propagates; so does a paygate
|
|
212
|
+
* refusal or a session without a URL.
|
|
213
|
+
*/
|
|
214
|
+
const createSession = async (
|
|
215
|
+
paygate: Paygate, plugins: readonly CheckoutPlugin[], attempt: CheckoutAttempt, input: SessionInput,
|
|
216
|
+
): Promise<string> => {
|
|
217
|
+
const admitted: Admitted[] = await checkoutPluginsOf(ctx).admitCheckout(plugins, attempt)
|
|
218
|
+
const holders = admitted.filter(entry => entry.plugin.admit != null)
|
|
219
|
+
let session: PaygateSession
|
|
220
|
+
try {
|
|
221
|
+
session = await paygate.checkout.createSession(input)
|
|
222
|
+
} catch (error) {
|
|
223
|
+
await checkoutPluginsOf(ctx).releaseAdmitted(holders, attempt)
|
|
224
|
+
throw error
|
|
225
|
+
}
|
|
226
|
+
if (session.url == null) {
|
|
227
|
+
await checkoutPluginsOf(ctx).releaseAdmitted(holders, attempt, session.id)
|
|
228
|
+
throw new PaygateError('session')
|
|
229
|
+
}
|
|
230
|
+
for (const { plugin, reservationId } of admitted) {
|
|
231
|
+
if (plugin.created == null) {
|
|
232
|
+
continue
|
|
233
|
+
}
|
|
234
|
+
try {
|
|
235
|
+
await plugin.created(ctx, { ...attempt, sessionId: session.id, url: session.url, ...(reservationId != null ? { reservationId } : {}) })
|
|
236
|
+
} catch (error) {
|
|
237
|
+
try {
|
|
238
|
+
await paygate.checkout.expireSession(session.id)
|
|
239
|
+
} catch (expireError) {
|
|
240
|
+
log.error('Could not expire a checkout a plugin refused', { sessionId: session.id, error: expireError })
|
|
241
|
+
}
|
|
242
|
+
await checkoutPluginsOf(ctx).releaseAdmitted(holders, attempt, session.id)
|
|
243
|
+
throw error
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
return session.url
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
const createCheckoutLink = async (params: CreateLinkParams, plugins: readonly CheckoutPlugin[] = []): Promise<string> => {
|
|
251
|
+
const paygates = paygatesOf(ctx)
|
|
252
|
+
const product = await access.payment().product(params.productSku) as PaymentProduct
|
|
253
|
+
const plans = (await access.payment().allPlans(product.sku) as PaymentPlan[])
|
|
254
|
+
.filter(plan => paygates.forSale(product, plan, params.paygate).length > 0)
|
|
255
|
+
if (params.planSku != null && !plans.some(plan => plan.sku === params.planSku)) {
|
|
256
|
+
throw new ProductError(`plan:${params.planSku}`)
|
|
257
|
+
}
|
|
258
|
+
const consumable = product.type === ProductType.Consumable
|
|
259
|
+
const plan = consumable
|
|
260
|
+
? plans.find(item => item.sku === params.planSku) ?? plans[0]
|
|
261
|
+
: plans.find(item => item.sku === params.planSku) ?? plans.find(item => item.recurring != null) ?? plans[0]
|
|
262
|
+
if (plan == null) throw new ProductError('plan')
|
|
263
|
+
const paygate = paygates.forSale(product, plan, params.paygate)[0]
|
|
264
|
+
const catalogueCurrency = (plan.amountPolicy?.currency ?? plan.currency ?? 'usd').toLowerCase()
|
|
265
|
+
const { buyer, customer } = await buyerOf(paygate, params, catalogueCurrency)
|
|
266
|
+
const pricing = await access.payment().pricingPolicy()
|
|
267
|
+
const settlement = (await paygate.settlementCurrency())?.toLowerCase()
|
|
268
|
+
const ttl = checkoutPolicyHelper.sessionTtlOf(plugins, paygate.features.sessionTtl)
|
|
269
|
+
const now = new Date()
|
|
270
|
+
const expiresAt = ttl != null ? new Date((Math.floor(now.getTime() / 1000) + ttl) * 1000) : undefined
|
|
271
|
+
const terms = termsOf(paygate, buyer)
|
|
272
|
+
const base = {
|
|
273
|
+
entityId: params.entityId, productSku: product.sku, planSku: plan.sku, at: now,
|
|
274
|
+
...(ttl != null ? { sessionTtlSeconds: ttl } : {}), ...(expiresAt != null ? { expiresAt } : {}),
|
|
275
|
+
}
|
|
276
|
+
const shared = {
|
|
277
|
+
entityId: params.entityId, productSku: product.sku, planSku: plan.sku, customerId: customer.id,
|
|
278
|
+
successUrl: params.successUrl, cancelUrl: params.cancelUrl ?? params.successUrl,
|
|
279
|
+
...(params.locale != null ? { locale: params.locale } : {}),
|
|
280
|
+
...(expiresAt != null ? { expiresAt } : {}),
|
|
281
|
+
automaticTax: Boolean(pricing.tax.automatic), collectTaxId: Boolean(pricing.tax.collectTaxId),
|
|
282
|
+
keepAddress: buyer.addressLocked, collectTerms: terms.collect,
|
|
283
|
+
}
|
|
284
|
+
const adaptiveOf = (allowed: boolean): boolean => pricing.currency.adaptive === true && allowed
|
|
285
|
+
|
|
286
|
+
if (consumable && plan.pricingMode === CheckoutPricingMode.Amount) {
|
|
287
|
+
if (params.amountMinor == null) throw new ProductError('amount')
|
|
288
|
+
if (plan.amountPolicy == null) throw new ProductError(`amount-policy:${plan.sku}`)
|
|
289
|
+
checkoutPricingHelper.assertCheckoutAmount(plan.amountPolicy, params.amountMinor)
|
|
290
|
+
const sourceChargeMinor = checkoutPricingHelper.chargeAmountMinor(params.amountMinor, plan.amountPolicy)
|
|
291
|
+
const amountCurrency = plan.amountPolicy.currency.toLowerCase()
|
|
292
|
+
const view = await checkoutPluginsOf(ctx).narrowAmountFor(plugins, {
|
|
293
|
+
entityId: params.entityId, productSku: product.sku, planSku: plan.sku, base: plan.amountPolicy, at: now,
|
|
294
|
+
})
|
|
295
|
+
checkoutPolicyHelper.assertAmountAllowed(view, params.amountMinor)
|
|
296
|
+
const charged = buyer.chargeCurrency != null
|
|
297
|
+
? await fxOf(ctx).chargeAmount(paygate, sourceChargeMinor, amountCurrency, buyer.chargeCurrency)
|
|
298
|
+
: await fxOf(ctx).settlementAmount(paygate, sourceChargeMinor, amountCurrency)
|
|
299
|
+
const adaptive = buyer.chargeCurrency == null || charged.currency === (settlement ?? amountCurrency)
|
|
300
|
+
const context = textContextOf(buyer, charged.currency, { unitAmountMinor: charged.amountMinor })
|
|
301
|
+
const submit = submitTextOf(params, context)
|
|
302
|
+
?? (buyer.policy != null && buyer.inScope && buyer.country != null
|
|
303
|
+
? consumerCopyHelper.consumerText(buyer.language, 'checkout.top-up', {
|
|
304
|
+
product: product.title, country: consumerFormatHelper.countryName(buyer.country, buyer.language),
|
|
305
|
+
})
|
|
306
|
+
: undefined)
|
|
307
|
+
|
|
308
|
+
return await createSession(paygate, plugins, {
|
|
309
|
+
...base, mode: 'amount', amountMinor: params.amountMinor, amountCurrency, chargeMinor: charged.amountMinor,
|
|
310
|
+
currency: charged.currency,
|
|
311
|
+
}, {
|
|
312
|
+
...shared, mode: 'amount',
|
|
313
|
+
line: {
|
|
314
|
+
kind: 'amount', productSku: product.sku, currency: charged.currency, unitAmountMinor: charged.amountMinor,
|
|
315
|
+
...(pricing.tax.behavior != null ? { taxBehavior: pricing.tax.behavior } : {}),
|
|
316
|
+
},
|
|
317
|
+
currency: charged.currency, forceCurrency: false, adaptiveCurrency: adaptiveOf(adaptive),
|
|
318
|
+
texts: paymentUtils.compact({
|
|
319
|
+
submit: submit != null ? limited(paygate, submit, 'submit') : undefined, terms: terms.text,
|
|
320
|
+
}),
|
|
321
|
+
metadata: sharedMetadata(params, product, plan, {
|
|
322
|
+
pricingMode: CheckoutPricingMode.Amount,
|
|
323
|
+
currency: charged.currency,
|
|
324
|
+
amountCurrency,
|
|
325
|
+
amountMinor: String(params.amountMinor),
|
|
326
|
+
sourceChargeAmountMinor: String(sourceChargeMinor),
|
|
327
|
+
chargeAmountMinor: String(charged.amountMinor),
|
|
328
|
+
...consumerMetadata(buyer, params),
|
|
329
|
+
}),
|
|
330
|
+
})
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
const lookupKey = planHelper.planLookupKey(product, plan)
|
|
334
|
+
if (paygate.catalogue == null) throw new ProductError(`price:${lookupKey}`)
|
|
335
|
+
const price = await paygate.catalogue.price(product.sku, lookupKey)
|
|
336
|
+
const forced = buyer.chargeCurrency != null
|
|
337
|
+
? await priceCarries(product, plan, price, buyer.chargeCurrency) : { carries: false }
|
|
338
|
+
if (buyer.chargeCurrency != null && !forced.carries) {
|
|
339
|
+
log.warn('Plan has no price in the charge currency; the paygate picks the currency', { plan: plan.sku, currency: buyer.chargeCurrency })
|
|
340
|
+
}
|
|
341
|
+
const currency = forced.carries ? buyer.chargeCurrency as string : price.currency
|
|
342
|
+
const adaptive = buyer.chargeCurrency == null || currency === (settlement ?? price.currency)
|
|
343
|
+
|
|
344
|
+
if (consumable) {
|
|
345
|
+
const quantityPolicy = plan.quantityPolicy ?? {
|
|
346
|
+
minimum: plan.minQuantity ?? 1,
|
|
347
|
+
maximum: plan.maxQuantity ?? Math.max(100_000, plan.minQuantity ?? 1),
|
|
348
|
+
default: plan.defaultQuantity ?? plan.minQuantity ?? 1,
|
|
349
|
+
}
|
|
350
|
+
const submit = submitTextOf(params, textContextOf(buyer, currency, paymentUtils.compact({ unitAmountMinor: forced.unitAmount ?? price.unitAmountMinor ?? undefined })))
|
|
351
|
+
|
|
352
|
+
return await createSession(paygate, plugins, { ...base, mode: 'quantity', currency }, {
|
|
353
|
+
...shared, mode: 'quantity',
|
|
354
|
+
line: {
|
|
355
|
+
kind: 'quantity', priceId: price.id, minimum: quantityPolicy.minimum, maximum: quantityPolicy.maximum,
|
|
356
|
+
default: quantityPolicy.default,
|
|
357
|
+
},
|
|
358
|
+
currency, forceCurrency: forced.carries, adaptiveCurrency: adaptiveOf(adaptive),
|
|
359
|
+
texts: paymentUtils.compact({
|
|
360
|
+
submit: submit != null ? limited(paygate, submit, 'submit') : undefined, terms: terms.text,
|
|
361
|
+
}),
|
|
362
|
+
metadata: sharedMetadata(params, product, plan, {
|
|
363
|
+
pricingMode: CheckoutPricingMode.Quantity,
|
|
364
|
+
...(forced.carries ? { currency } : {}),
|
|
365
|
+
...consumerMetadata(buyer, params),
|
|
366
|
+
}),
|
|
367
|
+
})
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
// A subscription starts services at once: in scope (or unknown and protected) it needs the
|
|
371
|
+
// consumer's express start request, fresh and bound to this organization and plan.
|
|
372
|
+
const start = buyer.policy != null ? await access.consumerRightsOf()?.assertStartRequest(params.entityId, plan.sku, params.startRequestId) ?? null : null
|
|
373
|
+
const unitAmount = forced.unitAmount ?? price.unitAmountMinor ?? undefined
|
|
374
|
+
const interval = plan.recurring?.interval
|
|
375
|
+
const context = textContextOf(buyer, currency, paymentUtils.compact({ unitAmountMinor: unitAmount, interval }))
|
|
376
|
+
const renewal = buyer.policy != null && unitAmount != null && interval != null
|
|
377
|
+
? consumerCopyHelper.consumerText(buyer.language, `checkout.renewal.${interval}`, {
|
|
378
|
+
price: consumerCopyHelper.consumerText(buyer.language, `checkout.price.${pricing.tax.behavior === TaxBehavior.Inclusive ? 'inclusive' : 'exclusive'}`, {
|
|
379
|
+
amount: consumerFormatHelper.formatMoney(unitAmount, currency, buyer.language),
|
|
380
|
+
}),
|
|
381
|
+
})
|
|
382
|
+
: undefined
|
|
383
|
+
const submit = submitTextOf(params, context) ?? renewal
|
|
384
|
+
const links = buyer.policy != null ? consumerRightsPolicyHelper.linksOf(buyer.policy, buyer.language) : null
|
|
385
|
+
const afterSubmit = buyer.policy?.mechanisms.cancellation === true && links?.cancellation != null
|
|
386
|
+
? consumerCopyHelper.consumerText(buyer.language, 'checkout.renewal.after-submit', { cancelUrl: links.cancellation })
|
|
387
|
+
: undefined
|
|
388
|
+
const texts = paymentUtils.compact({
|
|
389
|
+
submit: submit != null ? limited(paygate, submit, 'submit') : undefined,
|
|
390
|
+
afterSubmit: afterSubmit != null ? limited(paygate, afterSubmit, 'after-submit') : undefined,
|
|
391
|
+
terms: terms.text,
|
|
392
|
+
})
|
|
393
|
+
const startRequestId = start?.id ?? undefined
|
|
394
|
+
const metadata = consumerMetadata(buyer, params, startRequestId)
|
|
395
|
+
|
|
396
|
+
return await createSession(paygate, plugins, { ...base, mode: 'subscription', currency }, {
|
|
397
|
+
...shared, mode: 'subscription',
|
|
398
|
+
line: { kind: 'subscription', priceId: price.id },
|
|
399
|
+
currency, forceCurrency: forced.carries, adaptiveCurrency: adaptiveOf(adaptive), texts,
|
|
400
|
+
subscriptionMetadata: {
|
|
401
|
+
pricingMode: CheckoutPricingMode.Quantity, entityId: params.entityId,
|
|
402
|
+
service: params.service, productSku: product.sku, planSku: plan.sku,
|
|
403
|
+
...(params.profileId != null ? { profileId: params.profileId } : {}),
|
|
404
|
+
...metadata,
|
|
405
|
+
},
|
|
406
|
+
metadata: sharedMetadata(params, product, plan, metadata),
|
|
407
|
+
})
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
return { createCheckoutLink }
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
/** The checkout of a context — one per context. */
|
|
414
|
+
export const checkoutOf = memoHelper.oncePer(makeCheckoutHelper)
|
package/src/config.ts
CHANGED
|
@@ -1,13 +1,9 @@
|
|
|
1
1
|
|
|
2
2
|
import { plugin, PLUGIN_RECORD, configHelper } from '@owlmeans/config'
|
|
3
3
|
import { CAPABILITY_LIMIT_SCOPE, CheckoutPricingMode, CONSUMER_RIGHTS_RECORD_ID, CONSUMER_RIGHTS_RECORD_TYPE, ConsumerRightsError, LimitKind, LimitMisdeclared, makeConsumerRightsPolicy, PLAN_RECORD_PREFIX, PLAN_RECORD_TYPE, PaymentError, PlanRankConflict, PlanStatus, PRICING_POLICY_RECORD_ID, PRICING_POLICY_RECORD_TYPE, PRODUCT_RECORD_PREFIX, PRODUCT_RECORD_TYPE, ProductError, type ConsumerRightsPolicy, type LimitDeclaration, type PlanWithdrawalComponent, checkoutPricingHelper, priceEstimateHelper } from '@owlmeans/payment'
|
|
4
|
-
import {
|
|
5
|
-
CONSUMER_RIGHTS_MAIL_PLUGIN_CONFIG, STRIPE_PAYGATE_ALIAS, STRIPE_PLUGIN_CONFIG, STRIPE_PORTAL_PLUGIN_CONFIG,
|
|
6
|
-
STRIPE_PRICING_PLUGIN_CONFIG,
|
|
7
|
-
} from './consts.js'
|
|
4
|
+
import { CONSUMER_RIGHTS_MAIL_PLUGIN_CONFIG } from './consts.js'
|
|
8
5
|
import type {
|
|
9
|
-
Config, ConsumerRightsDef, PaymentPlan, PaymentPlanDef, PaymentProduct, PaymentProductDef,
|
|
10
|
-
PricingDef, StripeSecretsDef,
|
|
6
|
+
Config, ConsumerRightsDef, PaymentPlan, PaymentPlanDef, PaymentProduct, PaymentProductDef, PricingDef,
|
|
11
7
|
} from './types.js'
|
|
12
8
|
import { CURRENCY, LIMIT_KINDS, LIMIT_WINDOWS } from './consts.local.js'
|
|
13
9
|
|
|
@@ -16,7 +12,8 @@ export const declarePaymentProduct = (cfg: Config, def: PaymentProductDef): void
|
|
|
16
12
|
const product: PaymentProduct = {
|
|
17
13
|
type: def.type, sku: def.sku, title: def.name, description: def.description,
|
|
18
14
|
defaultLng: def.defaultLng ?? 'en', services: def.services,
|
|
19
|
-
|
|
15
|
+
// Absent: sold through every registered paygate (`planHelper.isSoldThrough`).
|
|
16
|
+
...(def.gateways != null ? { gateways: def.gateways } : {}), capabilities: def.capabilities,
|
|
20
17
|
taxCode: def.taxCode, unitLabel: def.unitLabel,
|
|
21
18
|
}
|
|
22
19
|
cfg.records.push({ ...configHelper.toConfigRecord(product), recordType: PRODUCT_RECORD_TYPE, id: `${PRODUCT_RECORD_PREFIX}:${def.sku}` })
|
|
@@ -149,75 +146,31 @@ const assertWithdrawalComponents = (def: PaymentPlanDef): void => {
|
|
|
149
146
|
}
|
|
150
147
|
|
|
151
148
|
/**
|
|
152
|
-
*
|
|
153
|
-
*
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
api: paths.api, ...(paths.webhook != null && paths.webhook !== '' ? { webhook: paths.webhook } : {}),
|
|
158
|
-
}, STRIPE_PLUGIN_CONFIG)
|
|
159
|
-
}
|
|
160
|
-
|
|
161
|
-
/** Branding and the default return URL of the managed customer portal configuration. */
|
|
162
|
-
export const portalBranding = (cfg: Config, def: PortalBrandingDef): void => {
|
|
163
|
-
plugin(cfg, {
|
|
164
|
-
returnUrl: def.returnUrl,
|
|
165
|
-
...(def.headline != null ? { headline: def.headline } : {}),
|
|
166
|
-
...(def.privacyPolicyUrl != null ? { privacyPolicyUrl: def.privacyPolicyUrl } : {}),
|
|
167
|
-
...(def.termsOfServiceUrl != null ? { termsOfServiceUrl: def.termsOfServiceUrl } : {}),
|
|
168
|
-
}, STRIPE_PORTAL_PLUGIN_CONFIG)
|
|
169
|
-
}
|
|
170
|
-
|
|
171
|
-
/**
|
|
172
|
-
* Declare the pricing policy: whether checkout collects tax and a VAT/GST id, what `tax_behavior`
|
|
173
|
-
* synced prices are given, Adaptive Pricing, and whether the estimate endpoints are served. A
|
|
174
|
-
* config never carries more than one — a second call replaces the first, so re-declaring (a test, a
|
|
175
|
-
* config module re-run) is safe rather than silently ignored (a config resource resolves an id to
|
|
176
|
-
* its FIRST match).
|
|
149
|
+
* Declare the pricing policy: whether checkout collects tax and a VAT/GST id, what tax behavior synced
|
|
150
|
+
* prices are given, local-currency pricing, and whether the estimate endpoints are served. A config
|
|
151
|
+
* never carries more than one — a second call replaces the first, so re-declaring (a test, a config
|
|
152
|
+
* module re-run) is safe rather than silently ignored (a config resource resolves an id to its FIRST
|
|
153
|
+
* match).
|
|
177
154
|
*
|
|
178
|
-
*
|
|
179
|
-
*
|
|
155
|
+
* The record is ADVERTISED to the browser, so it takes `tax` and `currency` only: a provider's own
|
|
156
|
+
* settings (a settlement currency, payment methods, customer locks) are declared through the
|
|
157
|
+
* provider's package, and any other field is refused rather than published.
|
|
180
158
|
*
|
|
181
159
|
* @throws PaymentError (`assertPricingPolicy`) when an estimate is declared without the tax or
|
|
182
|
-
* currency capability it requires
|
|
160
|
+
* currency capability it requires; `pricing-policy:field:<name>` for a field beyond `tax` and `currency`.
|
|
183
161
|
*/
|
|
184
162
|
export const declarePaymentPricing = (cfg: Config, def: PricingDef): void => {
|
|
185
|
-
const {
|
|
163
|
+
const { tax, currency, ...rest } = def
|
|
164
|
+
const unknown = Object.keys(rest)[0]
|
|
165
|
+
if (unknown != null) {
|
|
166
|
+
throw new PaymentError(`pricing-policy:field:${unknown}`)
|
|
167
|
+
}
|
|
168
|
+
const policy = { tax, currency }
|
|
186
169
|
priceEstimateHelper.assertPricingPolicy(policy)
|
|
187
170
|
cfg.records = (cfg.records ?? []).filter(record => record.id !== PRICING_POLICY_RECORD_ID)
|
|
188
171
|
cfg.records.push({
|
|
189
172
|
...configHelper.toConfigRecord(policy), recordType: PRICING_POLICY_RECORD_TYPE, id: PRICING_POLICY_RECORD_ID,
|
|
190
173
|
})
|
|
191
|
-
if (stripe != null) {
|
|
192
|
-
const settlementCurrency = stripe.settlementCurrency?.toLowerCase()
|
|
193
|
-
if (settlementCurrency != null && !/^[a-z]{3}$/.test(settlementCurrency)) {
|
|
194
|
-
throw new PaymentError('pricing-policy:settlement-currency')
|
|
195
|
-
}
|
|
196
|
-
const normalizeMethods = (methods: string[]): string[] => {
|
|
197
|
-
const normalized = methods.map(type => type.toLowerCase())
|
|
198
|
-
if (normalized.length === 0 || normalized.some(type => !/^[a-z][a-z0-9_]*$/.test(type))
|
|
199
|
-
|| new Set(normalized).size !== normalized.length) {
|
|
200
|
-
throw new PaymentError('pricing-policy:subscription-payment-methods')
|
|
201
|
-
}
|
|
202
|
-
return normalized
|
|
203
|
-
}
|
|
204
|
-
const subscriptionPaymentMethodTypes = stripe.subscriptionPaymentMethodTypes != null
|
|
205
|
-
? normalizeMethods(stripe.subscriptionPaymentMethodTypes) : undefined
|
|
206
|
-
const subscriptionPaymentMethodTypesByCurrency: Record<string, string[]> = {}
|
|
207
|
-
for (const [key, methods] of Object.entries(stripe.subscriptionPaymentMethodTypesByCurrency ?? {})) {
|
|
208
|
-
const currency = key.toLowerCase()
|
|
209
|
-
if (!/^[a-z]{3}$/.test(currency) || Object.hasOwn(subscriptionPaymentMethodTypesByCurrency, currency)) {
|
|
210
|
-
throw new PaymentError('pricing-policy:subscription-payment-methods-currency')
|
|
211
|
-
}
|
|
212
|
-
subscriptionPaymentMethodTypesByCurrency[currency] = normalizeMethods(methods)
|
|
213
|
-
}
|
|
214
|
-
plugin(cfg, {
|
|
215
|
-
...stripe,
|
|
216
|
-
...(settlementCurrency != null ? { settlementCurrency } : {}),
|
|
217
|
-
...(subscriptionPaymentMethodTypes != null ? { subscriptionPaymentMethodTypes } : {}),
|
|
218
|
-
...(stripe.subscriptionPaymentMethodTypesByCurrency != null ? { subscriptionPaymentMethodTypesByCurrency } : {}),
|
|
219
|
-
}, STRIPE_PRICING_PLUGIN_CONFIG)
|
|
220
|
-
}
|
|
221
174
|
}
|
|
222
175
|
|
|
223
176
|
/**
|