Skip to content

Self-hosted personal gallery application with online photo management and albums, supporting Live/Motion Photos, EXIF parsing, geolocation recognition, and an explore map.

fix(payments): reconcile adaptive charges and terminal Dodo checkouts

Timothy Yin8640f8124256
diff --git a/apps/cloud/app/components/CloudPricing.vue b/apps/cloud/app/components/CloudPricing.vue
index 64207baa..4f9874c0 100644
--- a/apps/cloud/app/components/CloudPricing.vue
+++ b/apps/cloud/app/components/CloudPricing.vue
@@ -35,7 +35,12 @@ const billing = props.portal
: null
const payments = props.portal
? (props.paymentController ??
- useCloudPayments(() => billing?.selected.value ?? 0))
+ useCloudPayments(
+ () => billing?.selected.value ?? 0,
+ async () => {
+ await billing?.refresh()
+ },
+ ))
: null
const { data, error, refresh } = await useFetch<any>('/api/billing/catalog', {
key: 'public-pricing-catalog',
@@ -100,6 +105,7 @@ const pendingFor = (plan: any) => payment.value?.pending?.planId === plan.id
async function resume() {
if (payment.value?.pending?.url)
await navigateTo(payment.value.pending.url, { external: true })
+ else await Promise.all([payments?.refresh(), billing?.refresh()])
}
const offer = (plan: any) =>
payment.value?.enabled &&
@@ -177,6 +183,20 @@ async function checkout(plan: any) {
: $t('cloud.billing.purchaseHelp')
}}
</p>
+ <p
+ v-if="payment?.pending?.state === 'uncertain'"
+ class="cf-field-hint"
+ role="status"
+ >
+ {{ $t('cloud.payments.confirmationReview') }}
+ <code
+ v-if="
+ payment.pending.error &&
+ payment.pending.error !== 'payment_confirmation_pending'
+ "
+ >{{ payment.pending.error }}</code
+ >
+ </p>
<p
v-if="paymentError"
class="cf-error-message"
@@ -303,14 +323,18 @@ async function checkout(plan: any) {
>
<CfButton
v-else-if="portal && pendingFor(plan)"
- :disabled="!payment.pending.url || !!paying"
+ :disabled="
+ !!paying ||
+ payments?.busy.value ||
+ (!payment.pending.url && !payment.pending.canRefresh)
+ "
@click="resume"
>
{{
$t(
payment.pending.url
? 'cloud.payments.resume'
- : 'cloud.payments.waiting',
+ : 'cloud.payments.checkAgain',
)
}}
</CfButton>
diff --git a/apps/cloud/app/composables/useCloudPayments.ts b/apps/cloud/app/composables/useCloudPayments.ts
index 20d3753b..7502e1b7 100644
--- a/apps/cloud/app/composables/useCloudPayments.ts
+++ b/apps/cloud/app/composables/useCloudPayments.ts
@@ -1,6 +1,7 @@
import type { MaybeRefOrGetter } from 'vue'
export function useCloudPayments(
workspaceId: MaybeRefOrGetter<number | string>,
+ onReconciled?: () => Promise<void>,
) {
const { t } = useI18n(),
data = ref<any>(),
@@ -14,14 +15,44 @@ export function useCloudPayments(
id = Number(toValue(workspaceId))
if (!id) {
pending = false
+ busy.value = false
return
}
pending = true
+ busy.value = true
try {
- const result = await $fetch('/api/billing/payments', {
+ let result = await $fetch<any>('/api/billing/payments', {
query: { workspaceId: id },
timeout: 15000,
})
+ if (
+ alive &&
+ current === generation &&
+ result.canManage &&
+ result.pending?.canRefresh
+ ) {
+ // A stored checkout must converge even when the return URL parameters are gone.
+ try {
+ await $fetch('/api/billing/payments', {
+ method: 'POST',
+ timeout: 15000,
+ body: {
+ action: 'refresh',
+ workspaceId: id,
+ checkoutId: result.pending.id,
+ },
+ })
+ } catch {
+ // Re-read the local state/diagnostic persisted by the authenticated check.
+ }
+ if (!alive || current !== generation) return
+ result = await $fetch<any>('/api/billing/payments', {
+ query: { workspaceId: id },
+ timeout: 15000,
+ })
+ if (alive && current === generation && !result.pending)
+ await onReconciled?.()
+ }
if (alive && current === generation) {
data.value = result
error.value = ''
@@ -30,7 +61,10 @@ export function useCloudPayments(
if (alive && current === generation)
error.value = t('cloud.payments.failed')
} finally {
- if (current === generation) pending = false
+ if (current === generation) {
+ pending = false
+ busy.value = false
+ }
}
}
watch(
diff --git a/apps/cloud/app/composables/useDodoCheckoutReturn.ts b/apps/cloud/app/composables/useDodoCheckoutReturn.ts
index 4d553f4c..b4154ef2 100644
--- a/apps/cloud/app/composables/useDodoCheckoutReturn.ts
+++ b/apps/cloud/app/composables/useDodoCheckoutReturn.ts
@@ -34,7 +34,7 @@ export function useDodoCheckoutReturn(
if (!alive || current !== generation) return
await refresh()
if (!alive || current !== generation) return
- if (['completed', 'expired'].includes(result.state)) {
+ if (['completed', 'expired', 'inactive'].includes(result.state)) {
state.value = result.state
return
}
@@ -46,6 +46,7 @@ export function useDodoCheckoutReturn(
)
) {
state.value = 'failed'
+ await refresh()
return
}
}
diff --git a/apps/cloud/app/pages/account/plan.vue b/apps/cloud/app/pages/account/plan.vue
index 9a7771aa..b74a60da 100644
--- a/apps/cloud/app/pages/account/plan.vue
+++ b/apps/cloud/app/pages/account/plan.vue
@@ -6,7 +6,7 @@ const { t, locale } = useI18n(),
billing = useWorkspaceBilling()
const { selected, data, error, listError, status, refresh, retry, ready } =
billing
-const payments = useCloudPayments(() => selected.value)
+const payments = useCloudPayments(() => selected.value, refresh)
const returned = useDodoCheckoutReturn(
() => selected.value,
() => !!payments.data.value?.enabled,
diff --git a/apps/cloud/i18n/locales/en.json b/apps/cloud/i18n/locales/en.json
index 9c8a33c0..498c7dbd 100644
--- a/apps/cloud/i18n/locales/en.json
+++ b/apps/cloud/i18n/locales/en.json
@@ -414,6 +414,7 @@
"draft": "Draft",
"photograph": "Photograph",
"photographs": "Photographs",
+ "confirmationReview": "Your payment is being verified. Do not pay again. If verification reports an error, contact support with the code below.",
"processing": "Processing",
"yourPublicAddressAndSharedLinksWillReturn40": "Your public address and shared links will return 404. Your photographs, albums and storage will remain in your workspace. You can publish again later.",
"chooseHostedOrSelfHosted": "Choose ChronoFrame Cloud for a hosted gallery, or self-host with your own infrastructure."
@@ -711,6 +712,7 @@
},
"waiting": "Waiting for confirmation",
"checkingStatus": "Checking subscription…",
+ "confirmationReview": "Your payment is being verified. Do not pay again. If verification reports an error, contact support with the code below.",
"processing": "Processing payment",
"return_checking": "Confirming your payment and updating your plan…",
"return_pending": "Your payment is still being confirmed. You can check again; do not start another checkout.",
diff --git a/apps/cloud/i18n/locales/zh-Hans.json b/apps/cloud/i18n/locales/zh-Hans.json
index acebdef8..cea59f12 100644
--- a/apps/cloud/i18n/locales/zh-Hans.json
+++ b/apps/cloud/i18n/locales/zh-Hans.json
@@ -414,6 +414,7 @@
"draft": "草稿",
"photograph": "照片",
"photographs": "照片",
+ "confirmationReview": "这笔付款正在核验,请勿重复支付。如果核验异常,请携带下方错误码联系支持。",
"processing": "处理中",
"yourPublicAddressAndSharedLinksWillReturn40": "公开地址和分享链接将返回 404。照片、相簿和存储会保留在工作区中,你可以稍后重新发布。",
"chooseHostedOrSelfHosted": "选择 ChronoFrame Cloud 托管图库,或在自己的基础设施上自部署。"
@@ -711,6 +712,7 @@
},
"waiting": "等待确认",
"checkingStatus": "正在核对订阅…",
+ "confirmationReview": "这笔付款正在核验,请勿重复支付。如果核验异常,请携带下方错误码联系支持。",
"processing": "正在处理支付",
"return_checking": "正在确认付款并更新套餐与额度…",
"return_pending": "付款仍在确认中,可以稍后再次检查,请勿重复发起付款。",
diff --git a/packages/platform/src/dodo-payments.ts b/packages/platform/src/dodo-payments.ts
index ba92dfbc..47c800f7 100644
--- a/packages/platform/src/dodo-payments.ts
+++ b/packages/platform/src/dodo-payments.ts
@@ -371,6 +371,7 @@ export async function createDodoCheckout(
client.checkoutSessions.create(
{
product_cart: [{ product_id: product.product_id, quantity: 1 }],
+ billing_currency: product.currency,
customer: { email: member.email },
metadata: {
chronoframe_checkout_id: id,
@@ -538,6 +539,26 @@ async function reconcileDodoSubscription(
.bind(checkout.workspace_id, token, now + 60000, now)
.first<any>()
if (lock?.token !== token) fail('payment_busy')
+ const checkoutState = async (
+ state: 'uncertain' | 'expired',
+ error: string,
+ ) => {
+ await db
+ .prepare(
+ `UPDATE platform_payment_checkouts SET state=?,error=?,updated_at=? WHERE id=? AND state IN('creating','open','uncertain') AND ${activeFence} AND EXISTS(SELECT 1 FROM platform_payment_locks WHERE workspace_id=? AND token=?)`,
+ )
+ .bind(
+ state,
+ error,
+ now,
+ checkout.id,
+ key,
+ revision,
+ checkout.workspace_id,
+ token,
+ )
+ .run()
+ }
try {
subscription = await dodoRequest(() =>
client.subscriptions.retrieve(subscriptionId),
@@ -551,7 +572,6 @@ async function reconcileDodoSubscription(
if (
subscription.subscription_id !== subscriptionId ||
subscription.product_id !== checkout.product_id ||
- subscription.currency !== checkout.currency ||
subscription.quantity !== 1 ||
subscription.payment_frequency_interval !== 'Month' ||
subscription.payment_frequency_count !== checkout.interval ||
@@ -569,12 +589,10 @@ async function reconcileDodoSubscription(
const session = await dodoRequest(() =>
client.checkoutSessions.retrieve(rawDodoId(checkout.provider_id)),
)
- if (
- session.id !== rawDodoId(checkout.provider_id) ||
- !session.payment_id ||
- session.payment_status !== 'succeeded'
- )
- fail('payment_confirmation_pending')
+ if (session.id !== rawDodoId(checkout.provider_id))
+ fail('payment_checkout_mismatch', 422)
+ // The retrieved payment is authoritative; a session status may lag behind it.
+ if (!session.payment_id) fail('payment_confirmation_pending')
paymentId = session.payment_id ?? undefined
} else if (!known && !paymentId) {
const payments = await dodoRequest(() =>
@@ -591,26 +609,74 @@ async function reconcileDodoSubscription(
const payment = paymentId
? await dodoRequest(() => client.payments.retrieve(paymentId!))
: null
+ // A succeeded payment is never resumable, even when fulfillment needs investigation.
+ if (payment?.status === 'succeeded' && !known)
+ await checkoutState('uncertain', 'payment_confirmation_pending')
+ const identityError = !payment
+ ? null
+ : payment.payment_id !== paymentId ||
+ (payment.checkout_session_id &&
+ !known &&
+ checkout.provider_id &&
+ payment.checkout_session_id !== rawDodoId(checkout.provider_id))
+ ? 'payment_checkout_mismatch'
+ : payment.is_update_payment_method ||
+ payment.is_multi_subscription ||
+ !(
+ payment.subscription_id === subscriptionId ||
+ payment.subscription_ids?.includes(subscriptionId)
+ )
+ ? 'payment_subscription_mismatch'
+ : payment.customer.customer_id !== subscription.customer.customer_id
+ ? 'payment_customer_mismatch'
+ : payment.currency !== subscription.currency &&
+ subscription.currency !== checkout.currency
+ ? 'payment_currency_mismatch'
+ : (payment.metadata?.chronoframe_checkout_id &&
+ payment.metadata.chronoframe_checkout_id !== checkout.id) ||
+ (payment.metadata?.chronoframe_environment &&
+ payment.metadata.chronoframe_environment !== environment) ||
+ (payment.metadata?.chronoframe_profile_id &&
+ payment.metadata.chronoframe_profile_id !== key) ||
+ (!known &&
+ !checkout.provider_id &&
+ payment.metadata?.chronoframe_checkout_id !== checkout.id)
+ ? 'payment_checkout_mismatch'
+ : null
+ if (!known && identityError) fail(identityError, 422)
+ // Cancellation must converge even if an initial grant failed its amount/period checks.
+ // Only the authenticated, checkout-bound payment and subscription can release the slot.
+ if (
+ !known &&
+ payment &&
+ !identityError &&
+ ['cancelled', 'expired', 'failed'].includes(subscription.status)
+ ) {
+ await checkoutState('expired', 'payment_subscription_inactive')
+ return checkout.id as string
+ }
+ // Adaptive pricing charges the customer in a local currency. Compare the
+ // provider's settlement amount in the immutable product currency, never a
+ // browser amount, guessed exchange rate, or a numeric total in another currency.
+ const amountMatches =
+ payment &&
+ Number.isSafeInteger(payment.total_amount) &&
+ payment.total_amount > 0 &&
+ (payment.currency === checkout.currency
+ ? payment.total_amount === checkout.price
+ : payment.settlement_currency === checkout.currency &&
+ payment.settlement_amount === checkout.price)
const successful =
payment?.status === 'succeeded' &&
- !payment.is_update_payment_method &&
- !payment.is_multi_subscription &&
- (payment.subscription_id === subscriptionId ||
- payment.subscription_ids?.includes(subscriptionId)) &&
- payment.customer.customer_id === subscription.customer.customer_id &&
- payment.currency === checkout.currency &&
- payment.total_amount === checkout.price &&
- (!payment.metadata?.chronoframe_checkout_id ||
- payment.metadata.chronoframe_checkout_id === checkout.id) &&
- (!payment.metadata?.chronoframe_environment ||
- payment.metadata.chronoframe_environment === environment) &&
- (!payment.metadata?.chronoframe_profile_id ||
- payment.metadata.chronoframe_profile_id === key) &&
- (!!known ||
- !!checkout.provider_id ||
- payment.metadata?.chronoframe_checkout_id === checkout.id) &&
+ !identityError &&
+ amountMatches &&
!payment.refunds?.length &&
!payment.disputes?.length
+ if (!known && payment?.status === 'succeeded' && !successful) {
+ if (payment.refunds?.length || payment.disputes?.length)
+ fail('payment_refunded_or_disputed', 422)
+ fail('payment_amount_mismatch', 422)
+ }
const period = successful
? payment.service_periods?.find(
(p) => p.subscription_id === subscriptionId,
@@ -777,6 +843,10 @@ async function reconcileDodoSubscription(
}
await db.batch(writes)
return checkout.id as string
+ } catch (error) {
+ if (error instanceof SubscriptionError && error.statusCode === 422)
+ await checkoutState('uncertain', error.code)
+ throw error
} finally {
await db
.prepare(
@@ -907,7 +977,7 @@ export async function refreshDodoCheckout(
.first<any>()
if (!row) fail('payment_checkout_unavailable', 404)
if (!row.provider_id) return { state: row.state }
- const { client } = await dodoClient(
+ const { client, revision } = await dodoClient(
db,
secret,
environment,
@@ -918,10 +988,30 @@ export async function refreshDodoCheckout(
const session = await dodoRequest(() =>
client.checkoutSessions.retrieve(rawDodoId(row.provider_id)),
)
+ if (session.id !== rawDodoId(row.provider_id))
+ fail('payment_checkout_mismatch', 422)
if (session.payment_id) {
const payment = await dodoRequest(() =>
client.payments.retrieve(session.payment_id!),
)
+ if (
+ payment.payment_id !== session.payment_id ||
+ (payment.checkout_session_id &&
+ payment.checkout_session_id !== session.id)
+ )
+ fail('payment_checkout_mismatch', 422)
+ if (
+ !payment.subscription_id &&
+ !payment.subscription_ids?.length &&
+ ['failed', 'cancelled'].includes(payment.status ?? '')
+ ) {
+ await db
+ .prepare(
+ `UPDATE platform_payment_checkouts SET state='expired',error='payment_not_completed',updated_at=? WHERE id=? AND state IN('creating','open','uncertain') AND ${activeFence}`,
+ )
+ .bind(now, row.id, key, revision)
+ .run()
+ }
if (payment.subscription_id && !payment.is_multi_subscription)
await reconcileDodoSubscription(
db,
@@ -946,13 +1036,18 @@ export async function refreshDodoCheckout(
)
.bind(now, row.id)
.run()
+ const latest = await db
+ .prepare(
+ 'SELECT c.state,c.error,s.status FROM platform_payment_checkouts c LEFT JOIN platform_payment_subscriptions s ON s.checkout_id=c.id WHERE c.id=?',
+ )
+ .bind(row.id)
+ .first<any>()
return {
- state: (
- await db
- .prepare('SELECT state FROM platform_payment_checkouts WHERE id=?')
- .bind(row.id)
- .first<any>()
- ).state,
+ state:
+ latest.error === 'payment_subscription_inactive' ||
+ ['canceled', 'expired', 'failed'].includes(latest.status)
+ ? 'inactive'
+ : latest.state,
}
}
export async function reconcileDodoPayments(
@@ -1015,14 +1110,14 @@ export async function reconcileDodoPayments(
// The session's 24-hour validity has elapsed. Keep the immutable row for late provider events.
await db
.prepare(
- "UPDATE platform_payment_checkouts SET state='expired',error='payment_confirmation_unresolved',updated_at=? WHERE provider='dodo' AND environment=? AND provider_key=? AND state IN('creating','uncertain') AND updated_at<?",
+ "UPDATE platform_payment_checkouts SET state='expired',error='payment_confirmation_unresolved',updated_at=? WHERE provider='dodo' AND environment=? AND provider_key=? AND state IN('creating','uncertain') AND provider_id IS NULL AND updated_at<?",
)
.bind(now, environment, key, now - 86400000)
.run()
const pending = await allRows<any>(
db
.prepare(
- "SELECT id,workspace_id,user_id FROM platform_payment_checkouts WHERE provider='dodo' AND environment=? AND provider_key=? AND state='open' AND user_id IS NOT NULL ORDER BY updated_at LIMIT 2",
+ "SELECT id,workspace_id,user_id FROM platform_payment_checkouts WHERE provider='dodo' AND environment=? AND provider_key=? AND state IN('open','uncertain') AND provider_id IS NOT NULL AND user_id IS NOT NULL ORDER BY updated_at LIMIT 2",
)
.bind(environment, key),
)
@@ -1038,7 +1133,7 @@ export async function reconcileDodoPayments(
).catch(async () => {
await db
.prepare(
- "UPDATE platform_payment_checkouts SET updated_at=?,error='payment_reconciliation_failed' WHERE id=? AND state='open'",
+ "UPDATE platform_payment_checkouts SET updated_at=?,error=COALESCE(error,'payment_reconciliation_failed') WHERE id=? AND state IN('open','uncertain')",
)
.bind(now, row.id)
.run()
diff --git a/packages/platform/src/payments.ts b/packages/platform/src/payments.ts
index cce5ad65..ef957796 100644
--- a/packages/platform/src/payments.ts
+++ b/packages/platform/src/payments.ts
@@ -199,9 +199,11 @@ export async function paymentStatus(
settings.purchaseMethod === 'payment'
? await db
.prepare(
- "SELECT id,state,plan_id AS planId,interval,error,CASE WHEN state='open' AND user_id=? AND ?='admin' THEN checkout_url ELSE NULL END AS url FROM platform_payment_checkouts WHERE workspace_id=? AND provider='dodo' AND environment=? AND provider_key=? AND state IN('creating','open','uncertain') ORDER BY created_at DESC LIMIT 1",
+ "SELECT id,state,plan_id AS planId,interval,error,CASE WHEN user_id=? AND ?='admin' THEN 1 ELSE 0 END AS canRefresh,CASE WHEN state='open' AND user_id=? AND ?='admin' THEN checkout_url ELSE NULL END AS url FROM platform_payment_checkouts WHERE workspace_id=? AND provider='dodo' AND environment=? AND provider_key=? AND state IN('creating','open','uncertain') ORDER BY created_at DESC LIMIT 1",
)
.bind(
+ userId,
+ membership.role,
userId,
membership.role,
workspaceId,
diff --git a/tests/dodo-checkout-return.test.ts b/tests/dodo-checkout-return.test.ts
index 0650868d..b35a2f55 100644
--- a/tests/dodo-checkout-return.test.ts
+++ b/tests/dodo-checkout-return.test.ts
@@ -140,3 +140,14 @@ test('delayed confirmation has bounded polling and ignores late results after le
await flush()
assert.equal(late.returned.state.value, 'checking')
})
+
+test('an authoritative inactive subscription exits processing after cancellation', async () => {
+ const f = fixture(async () => ({ state: 'inactive' }))
+ try {
+ await flush()
+ assert.equal(f.returned.state.value, 'inactive')
+ assert.equal(f.timers.length, 0)
+ } finally {
+ f.dispose()
+ }
+})
diff --git a/tests/dodo-payments.test.ts b/tests/dodo-payments.test.ts
index f8779c34..c2cf0b4e 100644
--- a/tests/dodo-payments.test.ts
+++ b/tests/dodo-payments.test.ts
@@ -1341,3 +1341,228 @@ for (const months of [1, 3]) {
}
})
}
+
+test('adaptive-currency payments fulfill before any refund and cancellation later converges', async () => {
+ const f = await fixture()
+ try {
+ await f.db
+ .prepare(
+ "UPDATE platform_plans SET monthly_price=499,monthly_discount_bps=1000,revision=revision+1 WHERE id='pro'",
+ )
+ .run()
+ await syncDodoProducts(f.db, root, f.transport)
+ const checkout = await createPaymentCheckout(
+ f.db,
+ root,
+ 1,
+ input(),
+ 'https://portal.example',
+ f.transport,
+ )
+ const request = f.calls.find(
+ (c) => new URL(c.url).pathname === '/checkouts' && c.method === 'POST',
+ )!
+ assert.equal(request.body.billing_currency, 'USD')
+ const { sub, payment, session } = await f.paid(checkout)
+ const adaptive = payment as any
+ adaptive.currency = 'CNY'
+ adaptive.total_amount = 3110
+ adaptive.settlement_currency = 'USD'
+ adaptive.settlement_amount = 449
+ delete adaptive.service_periods
+ session.payment_status = 'processing' // Session status can lag the actual payment.
+ assert.equal(
+ (await refreshDodoCheckout(f.db, root, 1, 1, checkout.id, f.transport))
+ .state,
+ 'completed',
+ )
+ assert.equal((await paymentStatus(f.db, 1, 1)).pending, null)
+ assert.equal(
+ (
+ await f.db
+ .prepare(
+ 'SELECT plan_id FROM platform_workspace_plans WHERE workspace_id=1',
+ )
+ .first<any>()
+ ).plan_id,
+ 'pro',
+ )
+ // This occurs after fulfillment; refunds must not be blamed for the initial failure.
+ adaptive.refunds.push({ status: 'succeeded', amount: 500 })
+ sub.status = 'cancelled'
+ assert.equal(
+ (await refreshDodoCheckout(f.db, root, 1, 1, checkout.id, f.transport))
+ .state,
+ 'inactive',
+ )
+ assert.equal((await paymentStatus(f.db, 1, 1)).pending, null)
+ assert.equal(
+ (
+ await f.db
+ .prepare(
+ 'SELECT plan_id FROM platform_workspace_plans WHERE workspace_id=1',
+ )
+ .first<any>()
+ ).plan_id,
+ 'free',
+ )
+ } finally {
+ await f.mf.dispose()
+ }
+})
+
+test('unfulfilled partial refunds stop offering checkout and cancellation releases the pending slot without granting access', async () => {
+ const f = await fixture()
+ try {
+ await syncDodoProducts(f.db, root, f.transport)
+ const checkout = await createPaymentCheckout(
+ f.db,
+ root,
+ 1,
+ input(),
+ 'https://portal.example',
+ f.transport,
+ )
+ const { sub, payment } = await f.paid(checkout)
+ const adaptive = payment as any
+ adaptive.currency = 'CNY'
+ adaptive.total_amount = 8320
+ adaptive.settlement_currency = 'USD'
+ adaptive.settlement_amount = 1200
+ adaptive.refunds.push({ status: 'succeeded', amount: 500 })
+ await assert.rejects(
+ refreshDodoCheckout(f.db, root, 1, 1, checkout.id, f.transport),
+ { code: 'payment_refunded_or_disputed', statusCode: 422 },
+ )
+ let status = await paymentStatus(f.db, 1, 1)
+ assert.equal(status.pending.state, 'uncertain')
+ assert.equal(status.pending.url, null)
+ assert.equal(status.pending.canRefresh, 1)
+ assert.equal(status.pending.error, 'payment_refunded_or_disputed')
+ // A scheduled cancellation is still an active provider subscription: do not open a second one.
+ sub.cancel_at_next_billing_date = true
+ await assert.rejects(
+ refreshDodoCheckout(f.db, root, 1, 1, checkout.id, f.transport),
+ { code: 'payment_refunded_or_disputed' },
+ )
+ sub.status = 'cancelled'
+ await reconcileDodoPayments(f.db, root, f.transport)
+ status = await paymentStatus(f.db, 1, 1)
+ assert.equal(status.pending, null)
+ assert.equal(
+ (await refreshDodoCheckout(f.db, root, 1, 1, checkout.id, f.transport))
+ .state,
+ 'inactive',
+ )
+ assert.equal(
+ (
+ await f.db
+ .prepare(
+ 'SELECT plan_id FROM platform_workspace_plans WHERE workspace_id=1',
+ )
+ .first<any>()
+ ).plan_id,
+ 'free',
+ )
+ assert.equal(
+ (
+ await f.db
+ .prepare(
+ 'SELECT COUNT(*) AS count FROM platform_payment_subscriptions',
+ )
+ .first<any>()
+ ).count,
+ 0,
+ )
+ await createPaymentCheckout(
+ f.db,
+ root,
+ 1,
+ input('new_after_cancel'),
+ 'https://portal.example',
+ f.transport,
+ )
+ } finally {
+ await f.mf.dispose()
+ }
+})
+
+test('amount and identity mismatches have safe diagnostics, cannot grant, and cannot be resumed as unpaid', async () => {
+ const f = await fixture()
+ try {
+ await syncDodoProducts(f.db, root, f.transport)
+ const checkout = await createPaymentCheckout(
+ f.db,
+ root,
+ 1,
+ input(),
+ 'https://portal.example',
+ f.transport,
+ )
+ const { sub, payment } = await f.paid(checkout)
+ const adaptive = payment as any
+ adaptive.currency = 'CNY'
+ adaptive.total_amount = 8320
+ adaptive.settlement_currency = 'USD'
+ adaptive.settlement_amount = 1
+ const refresh = () =>
+ refreshDodoCheckout(f.db, root, 1, 1, checkout.id, f.transport)
+ await assert.rejects(refresh(), {
+ code: 'payment_amount_mismatch',
+ statusCode: 422,
+ })
+ assert.equal((await paymentStatus(f.db, 1, 1)).pending.url, null)
+ adaptive.settlement_amount = 1200
+ adaptive.settlement_currency = 'EUR'
+ await assert.rejects(refresh(), { code: 'payment_amount_mismatch' })
+ adaptive.settlement_currency = 'USD'
+ adaptive.customer = { customer_id: 'cus_other' }
+ sub.status = 'cancelled'
+ await assert.rejects(refresh(), { code: 'payment_customer_mismatch' })
+ assert.notEqual((await paymentStatus(f.db, 1, 1)).pending, null)
+ assert.equal(
+ (
+ await f.db
+ .prepare(
+ 'SELECT plan_id FROM platform_workspace_plans WHERE workspace_id=1',
+ )
+ .first<any>()
+ ).plan_id,
+ 'free',
+ )
+ adaptive.customer = sub.customer
+ sub.status = 'active'
+ sub.currency = 'CNY' // Both base-currency and local-currency subscription responses are supported.
+ assert.equal((await refresh()).state, 'completed')
+ } finally {
+ await f.mf.dispose()
+ }
+})
+
+test('failed payments without a subscription close the unpaid checkout', async () => {
+ const f = await fixture()
+ try {
+ await syncDodoProducts(f.db, root, f.transport)
+ const checkout = await createPaymentCheckout(
+ f.db,
+ root,
+ 1,
+ input(),
+ 'https://portal.example',
+ f.transport,
+ )
+ const { payment } = await f.paid(checkout)
+ const failed = payment as any
+ failed.status = 'failed'
+ failed.subscription_id = null
+ failed.subscription_ids = []
+ assert.equal(
+ (await refreshDodoCheckout(f.db, root, 1, 1, checkout.id, f.transport))
+ .state,
+ 'expired',
+ )
+ assert.equal((await paymentStatus(f.db, 1, 1)).pending, null)
+ } finally {
+ await f.mf.dispose()
+ }
+})
diff --git a/tests/portal-review-regressions.test.ts b/tests/portal-review-regressions.test.ts
index fe3ccf89..b56b4597 100644
--- a/tests/portal-review-regressions.test.ts
+++ b/tests/portal-review-regressions.test.ts
@@ -554,3 +554,104 @@ test('payments polling preserves in-flight timeout errors and retries without su
scope.stop()
}
})
+
+test('payments loaded without return parameters reconcile the owned checkout and refresh the plan', async () => {
+ const calls: { method: string; body?: any }[] = []
+ let planRefreshes = 0
+ let reads = 0
+ const module = load('apps/cloud/app/composables/useCloudPayments.ts', {
+ toValue,
+ $fetch: async (_path: string, options: any) => {
+ calls.push({ method: options.method ?? 'GET', body: options.body })
+ if (options.method === 'POST') return { state: 'inactive' }
+ return {
+ canManage: true,
+ pending:
+ reads++ === 0
+ ? {
+ id: 'stored-checkout',
+ canRefresh: 1,
+ state: 'open',
+ url: 'https://test.checkout.dodopayments.com/session/stale',
+ }
+ : null,
+ }
+ },
+ onMounted: () => {},
+ onBeforeUnmount: () => {},
+ useIntervalFn: () => {},
+ })
+ const scope = effectScope()
+ try {
+ const payments = scope.run(() =>
+ module.useCloudPayments(1, async () => {
+ planRefreshes++
+ }),
+ )!
+ await payments.refresh()
+ assert.deepEqual(
+ calls.map((c) => c.method),
+ ['GET', 'POST', 'GET'],
+ )
+ assert.equal(
+ JSON.stringify(calls[1]!.body),
+ JSON.stringify({
+ action: 'refresh',
+ workspaceId: 1,
+ checkoutId: 'stored-checkout',
+ }),
+ )
+ assert.equal(payments.data.value.pending, null)
+ assert.equal(planRefreshes, 1)
+ assert.equal(payments.busy.value, false)
+ } finally {
+ scope.stop()
+ }
+})
+
+test('checkout verification diagnostics are re-read after 422 and non-owners do not reconcile another checkout', async () => {
+ for (const canRefresh of [0, 1]) {
+ let reads = 0
+ let writes = 0
+ const module = load('apps/cloud/app/composables/useCloudPayments.ts', {
+ toValue,
+ $fetch: async (_path: string, options: any) => {
+ if (options.method === 'POST') {
+ writes++
+ throw { statusCode: 422 }
+ }
+ reads++
+ return {
+ canManage: true,
+ pending: {
+ id: 'stored-checkout',
+ canRefresh,
+ state: reads > 1 ? 'uncertain' : 'open',
+ url: reads > 1 ? null : 'provider-url',
+ error: reads > 1 ? 'payment_amount_mismatch' : null,
+ },
+ }
+ },
+ onMounted: () => {},
+ onBeforeUnmount: () => {},
+ useIntervalFn: () => {},
+ })
+ const scope = effectScope()
+ try {
+ const payments = scope.run(() => module.useCloudPayments(1))!
+ await payments.refresh()
+ assert.equal(writes, canRefresh)
+ assert.equal(
+ payments.data.value.pending.url,
+ canRefresh ? null : 'provider-url',
+ )
+ if (canRefresh)
+ assert.equal(
+ payments.data.value.pending.error,
+ 'payment_amount_mismatch',
+ )
+ } finally {
+ scope.stop()
+ }
+ }
+})