Skip to content

The open alternative to Salesforce, designed for AI.

fix(billing): make direct subscription creation idempotent (#28084)

Etienneceee149081e7
diff --git a/packages/twenty-server/src/engine/core-modules/billing/services/billing-portal.workspace-service.ts b/packages/twenty-server/src/engine/core-modules/billing/services/billing-portal.workspace-service.ts
index eb0fdf9345b..fc441c56704 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/services/billing-portal.workspace-service.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/services/billing-portal.workspace-service.ts
@@ -124,6 +124,7 @@ export class BillingPortalWorkspaceService {
plan,
requirePaymentMethod,
withTrialPeriod: this.isCustomerEligibleForTrialPeriod(customer),
+ idempotencyKey: `${customer?.billingSubscriptions.length ?? 0}`,
});
await this.billingSubscriptionService.syncSubscriptionToDatabase(
diff --git a/packages/twenty-server/src/engine/core-modules/billing/stripe/services/stripe-checkout.service.ts b/packages/twenty-server/src/engine/core-modules/billing/stripe/services/stripe-checkout.service.ts
index e890ef92428..20cf2acf94c 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/stripe/services/stripe-checkout.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/stripe/services/stripe-checkout.service.ts
@@ -91,6 +91,7 @@ export class StripeCheckoutService {
plan = BillingPlanKey.PRO,
requirePaymentMethod = false,
withTrialPeriod,
+ idempotencyKey,
}: {
user: AuthContextUser;
workspace: Pick<WorkspaceEntity, 'id' | 'displayName'>;
@@ -99,6 +100,7 @@ export class StripeCheckoutService {
plan?: BillingPlanKey;
requirePaymentMethod?: boolean;
withTrialPeriod: boolean;
+ idempotencyKey: string;
}): Promise<Stripe.Subscription> {
stripeCustomerId = await this.getOrCreateStripeCustomerId({
user,
@@ -126,7 +128,9 @@ export class StripeCheckoutService {
automatic_tax: { enabled: !!requirePaymentMethod },
};
- return await this.stripe.subscriptions.create(subscriptionParams);
+ return await this.stripe.subscriptions.create(subscriptionParams, {
+ idempotencyKey: `direct-subscription-${workspace.id}-${idempotencyKey}`,
+ });
}
async createSubscriptionWithPaymentMethodCollection({