Skip to content

Commit 8d73002

Browse files
authored
fix(billing): answer stripe's refusals to end a trial early with a conflict (#10530)
* fix(billing): answer stripe's refusals to end a trial early with a conflict A declined card already maps to a conflict, but Stripe can also refuse the first charge itself, such as an amount past the card currency's limit or a subscription past its daily invoice limit. Those surfaced as server errors; they now return a clear conflict, keep the trial running, and log Stripe's type and code. * fix(billing): match only stripe's confirmed charge refusals when ending a trial
1 parent 33cf82d commit 8d73002

2 files changed

Lines changed: 85 additions & 0 deletions

File tree

‎apps/sim/lib/billing/application/pro-trial.ts‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { createLogger } from '@sim/logger'
12
import Stripe from 'stripe'
23
import { getHighestPriorityPersonalSubscription } from '@/lib/billing/core/plan'
34
import { requireStripeClient } from '@/lib/billing/stripe-client'
@@ -7,6 +8,25 @@ import { OrchestrationError } from '@/lib/core/orchestration/types'
78
import type { UserAccountOperation } from '@/lib/users/application/operations'
89
import { authorizeAccountPreferences } from '@/lib/users/application/preferences-authorization'
910

11+
const logger = createLogger('ProTrial')
12+
13+
/**
14+
* Stripe invalid-request codes that refuse the first charge itself rather than reporting a fault
15+
* in the request: an amount past the card currency's maximum, or a subscription past Stripe's
16+
* per-subscription invoice limit.
17+
*/
18+
const STRIPE_CHARGE_REFUSAL_CODES: ReadonlySet<string> = new Set(['amount_too_large', 'rate_limit'])
19+
20+
/** Whether Stripe refused to charge now, which leaves the trial running and is worth a retry later. */
21+
function isStripeChargeRefusal(error: unknown): error is Stripe.errors.StripeError {
22+
if (error instanceof Stripe.errors.StripeRateLimitError) return true
23+
return (
24+
error instanceof Stripe.errors.StripeInvalidRequestError &&
25+
error.code !== undefined &&
26+
STRIPE_CHARGE_REFUSAL_CODES.has(error.code)
27+
)
28+
}
29+
1030
/** Session-only: ending a trial charges the account's own card, so no delegation may do it. */
1131
function defineProTrialOperation<const Id extends string>(id: Id) {
1232
const operation = {
@@ -64,6 +84,19 @@ export const endProTrial: OperationUseCase<
6484
'Your card could not be charged. Update your payment method, then try again.'
6585
)
6686
}
87+
if (isStripeChargeRefusal(error)) {
88+
logger.warn('Stripe refused to end a trial early', {
89+
stripeSubscriptionId: subscription.stripeSubscriptionId,
90+
type: error.type,
91+
code: error.code,
92+
error: error.message,
93+
})
94+
throw new OrchestrationError(
95+
'conflict',
96+
"We couldn't end your trial early right now. Your trial keeps running, so you can try again later or let it end on its own.",
97+
{ cause: error }
98+
)
99+
}
67100
throw error
68101
}
69102
return { success: true }

‎apps/sim/lib/billing/free-plan.integration.ts‎

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -451,6 +451,58 @@ describe('endProTrial', () => {
451451
)
452452
})
453453

454+
it.each([
455+
{
456+
label: 'a charge past the card currency limit',
457+
refusal: new Stripe.errors.StripeInvalidRequestError({
458+
type: 'invalid_request_error',
459+
code: 'amount_too_large',
460+
message: 'Amount must be no more than the currency maximum.',
461+
}),
462+
},
463+
{
464+
label: "a subscription past Stripe's daily invoice limit",
465+
refusal: new Stripe.errors.StripeInvalidRequestError({
466+
type: 'invalid_request_error',
467+
code: 'rate_limit',
468+
message: 'You have exceeded the daily invoice limit for this subscription.',
469+
}),
470+
},
471+
{
472+
label: 'a Stripe rate limit',
473+
refusal: new Stripe.errors.StripeRateLimitError({
474+
type: 'rate_limit_error',
475+
message: 'Too many requests hit the API too quickly.',
476+
}),
477+
},
478+
])('reports $label as a payer error and keeps the trial', async ({ refusal }) => {
479+
const userId = await createUser()
480+
await addSubscription(userId, 'trialing')
481+
stripeStub.subscriptions.update.mockRejectedValueOnce(refusal)
482+
483+
await expect(
484+
endProTrial.execute({ principal: asSession(userId), input: {} })
485+
).rejects.toMatchObject({
486+
code: 'conflict',
487+
message: expect.stringContaining('trial keeps running'),
488+
})
489+
})
490+
491+
it('still fails on a Stripe request fault that is not a refusal', async () => {
492+
const userId = await createUser()
493+
await addSubscription(userId, 'trialing')
494+
const fault = new Stripe.errors.StripeInvalidRequestError({
495+
type: 'invalid_request_error',
496+
code: 'resource_missing',
497+
message: 'No such subscription.',
498+
})
499+
stripeStub.subscriptions.update.mockRejectedValueOnce(fault)
500+
501+
await expect(endProTrial.execute({ principal: asSession(userId), input: {} })).rejects.toBe(
502+
fault
503+
)
504+
})
505+
454506
it('refuses an account whose plan is already paid', async () => {
455507
const userId = await createUser()
456508
await addSubscription(userId, 'active')

0 commit comments

Comments
 (0)