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(billing): close expired unpaid checkouts and bound return processing

Timothy Yinb61227228bb8
diff --git a/apps/cloud/app/composables/useDodoCheckoutReturn.ts b/apps/cloud/app/composables/useDodoCheckoutReturn.ts
index 45edb6a0..f50043d4 100644
--- a/apps/cloud/app/composables/useDodoCheckoutReturn.ts
+++ b/apps/cloud/app/composables/useDodoCheckoutReturn.ts
@@ -9,17 +9,38 @@ export function useDodoCheckoutReturn(
state = ref('idle')
let generation = 0,
alive = true,
- timer: ReturnType<typeof setTimeout> | undefined
+ timer: ReturnType<typeof setTimeout> | undefined,
+ deadlineTimer: ReturnType<typeof setTimeout> | undefined,
+ windowKey = '',
+ deadline = 0
async function check() {
const current = ++generation
if (timer) clearTimeout(timer)
+ if (deadlineTimer) clearTimeout(deadlineTimer)
const id = toValue(workspaceId),
checkout = route.query.checkout
if (!toValue(enabled) || !id || typeof checkout !== 'string') {
state.value = 'idle'
return
}
+ const key = `${id}:${checkout}`
+ if (windowKey !== key) {
+ windowKey = key
+ deadline = Date.now() + 60000
+ }
+ if (Date.now() >= deadline) {
+ state.value = 'pending'
+ return
+ }
state.value = 'checking'
+ // Bound the whole return flow, including slow refreshes and transient workspace resets.
+ deadlineTimer = setTimeout(() => {
+ if (!alive || current !== generation) return
+ generation++
+ deadline = 0
+ if (timer) clearTimeout(timer)
+ state.value = 'pending'
+ }, deadline - Date.now())
async function poll(attempt: number): Promise<void> {
if (!alive || current !== generation) return
try {
@@ -39,6 +60,7 @@ export function useDodoCheckoutReturn(
result.state,
)
) {
+ if (deadlineTimer) clearTimeout(deadlineTimer)
state.value = result.state
return
}
@@ -49,12 +71,14 @@ export function useDodoCheckoutReturn(
error?.statusCode ?? error?.status,
)
) {
+ if (deadlineTimer) clearTimeout(deadlineTimer)
state.value = 'failed'
await refresh()
return
}
}
if (attempt >= 7) {
+ if (deadlineTimer) clearTimeout(deadlineTimer)
state.value = 'pending'
return
}
@@ -77,6 +101,13 @@ export function useDodoCheckoutReturn(
alive = false
generation++
if (timer) clearTimeout(timer)
+ if (deadlineTimer) clearTimeout(deadlineTimer)
})
- return { state, retry: check }
+ return {
+ state,
+ retry: () => {
+ windowKey = ''
+ return check()
+ },
+ }
}
diff --git a/packages/platform/src/deferred-payments.ts b/packages/platform/src/deferred-payments.ts
index c1cce376..2598095c 100644
--- a/packages/platform/src/deferred-payments.ts
+++ b/packages/platform/src/deferred-payments.ts
@@ -1,3 +1,4 @@
+import { closeFailedInitialCheckout } from './unpaid-checkout.ts'
import type { PlatformD1 } from './index.ts'
import { DAY } from './payment-handover.ts'
import { SubscriptionError, subscriptionInvalidation } from './subscriptions.ts'
@@ -128,6 +129,20 @@ export async function reconcileDeferredAuthorization(
payment.disputes?.length)
)
fail('payment_subscription_mismatch')
+ if (
+ await closeFailedInitialCheckout(
+ db,
+ client,
+ checkout,
+ subscription,
+ payment,
+ known,
+ now,
+ fence,
+ fenceValues,
+ )
+ )
+ return { handled: true, paymentId }
const at = known?.handover_at ?? time(subscription.next_billing_date)
if (
!Number.isSafeInteger(at) ||
diff --git a/packages/platform/src/dodo-payments.ts b/packages/platform/src/dodo-payments.ts
index 361fda11..779c7658 100644
--- a/packages/platform/src/dodo-payments.ts
+++ b/packages/platform/src/dodo-payments.ts
@@ -1,3 +1,4 @@
+import { closeFailedInitialCheckout } from './unpaid-checkout.ts'
import { checkoutHandover } from './payment-handover.ts'
import { reconcileDeferredAuthorization } from './deferred-payments.ts'
import { discountedPrice } from '../../contracts/src/pricing.ts'
@@ -745,6 +746,21 @@ export async function reconcileDodoSubscription(
? 'payment_checkout_mismatch'
: null
if (!known && identityError) fail(identityError, 422)
+ if (
+ !identityError &&
+ (await closeFailedInitialCheckout(
+ db,
+ client,
+ checkout,
+ subscription,
+ payment,
+ known,
+ now,
+ `${activeFence} AND EXISTS(SELECT 1 FROM platform_payment_locks WHERE workspace_id=? AND token=?)`,
+ [key, revision, checkout.workspace_id, token],
+ ))
+ )
+ return checkout.id as string
// 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 (
@@ -1282,9 +1298,9 @@ export async function refreshDodoCheckout(
} else if (now - row.created_at > 86400000)
await db
.prepare(
- "UPDATE platform_payment_checkouts SET state='expired',updated_at=? WHERE id=? AND state='open' AND NOT EXISTS(SELECT 1 FROM platform_payment_subscriptions WHERE checkout_id=platform_payment_checkouts.id)",
+ `UPDATE platform_payment_checkouts SET state='expired',error='payment_checkout_expired',updated_at=? WHERE id=? AND state IN('open','uncertain') AND NOT EXISTS(SELECT 1 FROM platform_payment_subscriptions WHERE checkout_id=platform_payment_checkouts.id) AND ${activeFence}`,
)
- .bind(now, row.id)
+ .bind(now, row.id, key, revision)
.run()
await db
.prepare(
diff --git a/packages/platform/src/unpaid-checkout.ts b/packages/platform/src/unpaid-checkout.ts
new file mode 100644
index 00000000..9ef1ed6a
--- /dev/null
+++ b/packages/platform/src/unpaid-checkout.ts
@@ -0,0 +1,49 @@
+import type { PlatformD1 } from './index.ts'
+import { dodoRequest } from './dodo-client.ts'
+import { SubscriptionError } from './subscriptions.ts'
+
+/** Call only after binding the authoritative payment and subscription to our checkout. */
+export async function closeFailedInitialCheckout(
+ db: PlatformD1,
+ client: any,
+ checkout: any,
+ subscription: any,
+ payment: any,
+ known: any,
+ now: number,
+ fence: string,
+ fenceValues: (string | number | null)[],
+) {
+ // Session links last 24 hours. Only pre-charge states may be abandoned on age;
+ // processing, customer authentication, and capture states must keep reconciling.
+ const expiredBeforeCharge =
+ now - checkout.created_at > 86400000 &&
+ ['requires_payment_method', 'requires_confirmation'].includes(
+ payment?.status,
+ )
+ if (
+ known ||
+ subscription.status !== 'pending' ||
+ (!['failed', 'cancelled'].includes(payment?.status) && !expiredBeforeCharge)
+ )
+ return false
+ await dodoRequest(() =>
+ client.subscriptions.update(
+ subscription.subscription_id,
+ { status: 'cancelled' },
+ { headers: { 'Idempotency-Key': `cf-close-unpaid-${checkout.id}` } },
+ ),
+ )
+ const actual = (await dodoRequest(() =>
+ client.subscriptions.retrieve(subscription.subscription_id),
+ )) as any
+ if (actual.status !== 'cancelled')
+ throw new SubscriptionError(409, 'payment_confirmation_pending')
+ 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 NOT EXISTS(SELECT 1 FROM platform_payment_subscriptions WHERE checkout_id=platform_payment_checkouts.id) AND ${fence}`,
+ )
+ .bind(now, checkout.id, ...fenceValues)
+ .run()
+ return true
+}
diff --git a/tests/dodo-checkout-return.test.ts b/tests/dodo-checkout-return.test.ts
index fb5fd431..749ab562 100644
--- a/tests/dodo-checkout-return.test.ts
+++ b/tests/dodo-checkout-return.test.ts
@@ -12,6 +12,9 @@ function fixture(
) {
const exports: Record<string, any> = {}
const timers: (() => void)[] = []
+ const watchdogs: (() => void)[] = []
+ const handles = new Map<number, { list: (() => void)[]; fn: () => void }>()
+ let timerId = 0
const mounted: (() => void)[] = []
const unmounted: (() => void)[] = []
vm.runInNewContext(
@@ -39,11 +42,20 @@ function fixture(
onMounted: (fn: () => void) => mounted.push(fn),
onBeforeUnmount: (fn: () => void) => unmounted.push(fn),
$fetch: fetch,
- setTimeout: (fn: () => void) => {
- timers.push(fn)
- return timers.length
+ setTimeout: (fn: () => void, delay: number) => {
+ const list = delay > 5000 ? watchdogs : timers
+ list.push(fn)
+ handles.set(++timerId, { list, fn })
+ return timerId
+ },
+ clearTimeout: (id: number) => {
+ const value = handles.get(id)
+ if (value) {
+ const index = value.list.indexOf(value.fn)
+ if (index >= 0) value.list.splice(index, 1)
+ }
+ handles.delete(id)
},
- clearTimeout: () => {},
},
)
const scope = effectScope()
@@ -59,6 +71,7 @@ function fixture(
return {
returned,
timers,
+ watchdogs,
dispose: () => {
unmounted.forEach((fn) => fn())
scope.stop()
@@ -238,3 +251,69 @@ test('a confirmed deferred reservation closes the processing modal without furth
f.dispose()
}
})
+
+test('an expired checkout ends return processing without additional polls', async () => {
+ const f = fixture(async () => ({ state: 'expired' }))
+ try {
+ await flush()
+ assert.equal(f.returned.state.value, 'expired')
+ assert.equal(f.timers.length, 0)
+ assert.equal(f.watchdogs.length, 0)
+ } finally {
+ f.dispose()
+ }
+})
+test('the overall return deadline closes a hung request and ignores its late response until explicit retry', async () => {
+ let resolve!: (v: any) => void
+ let hung = true
+ const enabled = ref(true)
+ const f = fixture(
+ async () =>
+ hung
+ ? new Promise((r) => {
+ resolve = r
+ })
+ : { state: 'expired' },
+ async () => {},
+ { enabled: () => enabled.value },
+ )
+ try {
+ await flush()
+ f.watchdogs.shift()!()
+ assert.equal(f.returned.state.value, 'pending')
+ enabled.value = false
+ await flush()
+ enabled.value = true
+ await flush()
+ assert.equal(f.returned.state.value, 'pending')
+ resolve({ state: 'completed' })
+ await flush()
+ assert.equal(f.returned.state.value, 'pending')
+ hung = false
+ await f.returned.retry()
+ assert.equal(f.returned.state.value, 'expired')
+ } finally {
+ f.dispose()
+ }
+})
+test('the overall return deadline also covers a hung entitlement refresh', async () => {
+ let finish!: () => void
+ const f = fixture(
+ async () => ({ state: 'completed' }),
+ () =>
+ new Promise<void>((r) => {
+ finish = r
+ }),
+ )
+ try {
+ await flush()
+ assert.equal(f.returned.state.value, 'checking')
+ f.watchdogs.shift()!()
+ assert.equal(f.returned.state.value, 'pending')
+ finish()
+ await flush()
+ assert.equal(f.returned.state.value, 'pending')
+ } finally {
+ f.dispose()
+ }
+})
diff --git a/tests/dodo-payments.test.ts b/tests/dodo-payments.test.ts
index 35080b69..6599f0e2 100644
--- a/tests/dodo-payments.test.ts
+++ b/tests/dodo-payments.test.ts
@@ -2753,3 +2753,313 @@ test('confirmed cancellation of a provider-less checkout releases handover block
await f.mf.dispose()
}
})
+
+for (const outcome of [
+ 'failed',
+ 'cancelled',
+ 'requires_payment_method',
+ 'requires_confirmation',
+])
+ test(`unpaid ${outcome} with a pending subscription closes an expired checkout and releases the purchase slot`, async () => {
+ const f = await fixture()
+ try {
+ await syncDodoProducts(f.db, root, f.transport)
+ const checkout = await createPaymentCheckout(
+ f.db,
+ root,
+ 1,
+ input(),
+ origin,
+ f.transport,
+ f.now,
+ )
+ const { payment, sub } = await f.paid(checkout)
+ payment.status = outcome
+ payment.service_periods = []
+ sub.status = 'pending'
+ const later = f.now + 86400001
+ assert.equal(
+ (
+ await refreshDodoCheckout(
+ f.db,
+ root,
+ 1,
+ 1,
+ checkout.id,
+ f.transport,
+ later,
+ )
+ ).state,
+ 'expired',
+ )
+ assert.equal(sub.status, 'cancelled')
+ assert.equal((await paymentStatus(f.db, 1, 1)).pending, null)
+ assert.equal(
+ (
+ await f.db
+ .prepare('SELECT COUNT(*) AS n FROM platform_payment_subscriptions')
+ .first<any>()
+ ).n,
+ 0,
+ )
+ assert.equal(
+ (
+ await f.db
+ .prepare(
+ 'SELECT source FROM platform_workspace_plans WHERE workspace_id=1',
+ )
+ .first<any>()
+ ).source,
+ 'default',
+ )
+ const next = await createPaymentCheckout(
+ f.db,
+ root,
+ 1,
+ input('after_expired'),
+ origin,
+ f.transport,
+ later + 1000,
+ )
+ assert.notEqual(next.id, checkout.id)
+ } finally {
+ await f.mf.dispose()
+ }
+ })
+test('a failed linked payment closes without waiting for the checkout age limit', async () => {
+ const f = await fixture()
+ try {
+ await syncDodoProducts(f.db, root, f.transport)
+ const checkout = await createPaymentCheckout(
+ f.db,
+ root,
+ 1,
+ input(),
+ origin,
+ f.transport,
+ f.now,
+ )
+ const { payment, sub } = await f.paid(checkout)
+ payment.status = 'cancelled'
+ sub.status = 'pending'
+ assert.equal(
+ (
+ await refreshDodoCheckout(
+ f.db,
+ root,
+ 1,
+ 1,
+ checkout.id,
+ f.transport,
+ f.now + 1000,
+ )
+ ).state,
+ 'expired',
+ )
+ assert.equal((await paymentStatus(f.db, 1, 1)).pending, null)
+ } finally {
+ await f.mf.dispose()
+ }
+})
+test('old processing and actionable payments are never canceled on checkout age alone', async () => {
+ const f = await fixture()
+ try {
+ await syncDodoProducts(f.db, root, f.transport)
+ const checkout = await createPaymentCheckout(
+ f.db,
+ root,
+ 1,
+ input(),
+ origin,
+ f.transport,
+ f.now,
+ )
+ const { payment, sub } = await f.paid(checkout)
+ sub.status = 'pending'
+ for (const state of [
+ 'processing',
+ 'requires_customer_action',
+ 'requires_capture',
+ 'partially_captured',
+ 'partially_captured_and_capturable',
+ ]) {
+ payment.status = state
+ await assert.rejects(
+ refreshDodoCheckout(
+ f.db,
+ root,
+ 1,
+ 1,
+ checkout.id,
+ f.transport,
+ f.now + 86400001,
+ ),
+ { code: 'payment_confirmation_pending' },
+ )
+ assert.equal(sub.status, 'pending')
+ assert.equal(
+ f.calls.some(
+ (c) => c.method === 'PATCH' && c.url.includes('/subscriptions/'),
+ ),
+ false,
+ )
+ assert.ok((await paymentStatus(f.db, 1, 1)).pending)
+ }
+ } finally {
+ await f.mf.dispose()
+ }
+})
+test('a deferred checkout with a failed pending subscription expires without authorizing or extending entitlements', async () => {
+ const f = await handoverFixture()
+ try {
+ const checkout = await createPaymentCheckout(
+ f.db,
+ root,
+ 1,
+ { ...input(), startMode: 'after_entitlement' },
+ origin,
+ f.transport,
+ f.now,
+ )
+ const { payment, sub, session } = await f.paid(checkout)
+ sub.trial_period_days = session.trial_period_days
+ sub.status = 'pending'
+ payment.status = 'failed'
+ payment.total_amount = 0
+ assert.equal(
+ (
+ await refreshDodoCheckout(
+ f.db,
+ root,
+ 1,
+ 1,
+ checkout.id,
+ f.transport,
+ f.now + 1000,
+ )
+ ).state,
+ 'expired',
+ )
+ assert.equal((await paymentStatus(f.db, 1, 1)).reservation, null)
+ assert.equal(
+ (
+ await f.db
+ .prepare(
+ 'SELECT expires_at FROM platform_workspace_plans WHERE workspace_id=1',
+ )
+ .first<any>()
+ ).expires_at,
+ f.originalEnd,
+ )
+ } finally {
+ await f.mf.dispose()
+ }
+})
+
+test('an expired session without a payment also releases uncertain checkouts, without discarding late payment recovery', async () => {
+ const f = await fixture()
+ try {
+ await syncDodoProducts(f.db, root, f.transport)
+ const checkout = await createPaymentCheckout(
+ f.db,
+ root,
+ 1,
+ input(),
+ origin,
+ f.transport,
+ f.now,
+ )
+ await f.db
+ .prepare(
+ "UPDATE platform_payment_checkouts SET state='uncertain' WHERE id=?",
+ )
+ .bind(checkout.id)
+ .run()
+ assert.equal(
+ (
+ await refreshDodoCheckout(
+ f.db,
+ root,
+ 1,
+ 1,
+ checkout.id,
+ f.transport,
+ f.now + 86400001,
+ )
+ ).state,
+ 'expired',
+ )
+ assert.equal((await paymentStatus(f.db, 1, 1)).pending, null)
+ const { sub } = await f.paid(checkout)
+ assert.equal(
+ (
+ await refreshDodoCheckout(
+ f.db,
+ root,
+ 1,
+ 1,
+ checkout.id,
+ f.transport,
+ f.now + 2000,
+ )
+ ).state,
+ 'completed',
+ )
+ assert.equal(sub.status, 'active')
+ } finally {
+ await f.mf.dispose()
+ }
+})
+test('unconfirmed provider cancellation and mismatched failed payments never release a checkout', async () => {
+ const f = await fixture()
+ try {
+ await syncDodoProducts(f.db, root, f.transport)
+ const checkout = await createPaymentCheckout(
+ f.db,
+ root,
+ 1,
+ input(),
+ origin,
+ f.transport,
+ f.now,
+ )
+ const { payment, sub } = await f.paid(checkout)
+ payment.status = 'failed'
+ sub.status = 'pending'
+ const noCancel: typeof fetch = async (url, init) =>
+ init?.method === 'PATCH'
+ ? Response.json({ ...sub })
+ : f.transport(url, init)
+ await assert.rejects(
+ refreshDodoCheckout(
+ f.db,
+ root,
+ 1,
+ 1,
+ checkout.id,
+ noCancel,
+ f.now + 1000,
+ ),
+ { code: 'payment_confirmation_pending' },
+ )
+ assert.ok((await paymentStatus(f.db, 1, 1)).pending)
+ payment.customer = { customer_id: 'different_customer' }
+ const calls = f.calls.length
+ await assert.rejects(
+ refreshDodoCheckout(
+ f.db,
+ root,
+ 1,
+ 1,
+ checkout.id,
+ f.transport,
+ f.now + 2000,
+ ),
+ { code: 'payment_customer_mismatch' },
+ )
+ assert.ok(!f.calls.slice(calls).some((c) => c.method === 'PATCH'))
+ assert.ok((await paymentStatus(f.db, 1, 1)).pending)
+ } finally {
+ await f.mf.dispose()
+ }
+})