Skip to content

The open alternative to Salesforce, designed for AI.

Improve Stripe checkout to avoid redirecting to page (#13690)

Félix Malfait37a0f2726e6b
diff --git a/packages/twenty-server/src/engine/core-modules/billing/billing.resolver.ts b/packages/twenty-server/src/engine/core-modules/billing/billing.resolver.ts
index 0e1583ac71e..ae81cfcf122 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/billing.resolver.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/billing.resolver.ts
@@ -109,15 +109,30 @@ export class BillingResolver {
interval: recurringInterval,
},
);
- const checkoutSessionURL =
- await this.billingPortalWorkspaceService.computeCheckoutSessionURL({
- ...checkoutSessionParams,
- billingPricesPerPlan,
- });
- return {
- url: checkoutSessionURL,
- };
+ // For 7-day trials (no payment method required), create subscription directly
+ // For 30-day trials (payment method required), use checkout session flow
+ if (!requirePaymentMethod) {
+ const successUrl =
+ await this.billingPortalWorkspaceService.createDirectSubscription({
+ ...checkoutSessionParams,
+ billingPricesPerPlan,
+ });
+
+ return {
+ url: successUrl,
+ };
+ } else {
+ const checkoutSessionURL =
+ await this.billingPortalWorkspaceService.computeCheckoutSessionURL({
+ ...checkoutSessionParams,
+ billingPricesPerPlan,
+ });
+
+ return {
+ url: checkoutSessionURL,
+ };
+ }
}
@Mutation(() => BillingUpdateOutput)
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 ec52d41c107..08fafcd2a7d 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
@@ -8,19 +8,24 @@ import { Repository } from 'typeorm';
import type Stripe from 'stripe';
+import { transformStripeSubscriptionEventToDatabaseCustomer } from 'src/engine/core-modules/billing-webhook/utils/transform-stripe-subscription-event-to-database-customer.util';
+import { transformStripeSubscriptionEventToDatabaseSubscriptionItem } from 'src/engine/core-modules/billing-webhook/utils/transform-stripe-subscription-event-to-database-subscription-item.util';
+import { transformStripeSubscriptionEventToDatabaseSubscription } from 'src/engine/core-modules/billing-webhook/utils/transform-stripe-subscription-event-to-database-subscription.util';
import {
BillingException,
BillingExceptionCode,
} from 'src/engine/core-modules/billing/billing.exception';
import { BillingCustomer } from 'src/engine/core-modules/billing/entities/billing-customer.entity';
+import { BillingSubscriptionItem } from 'src/engine/core-modules/billing/entities/billing-subscription-item.entity';
import { BillingSubscription } from 'src/engine/core-modules/billing/entities/billing-subscription.entity';
+import { BillingSubscriptionService } from 'src/engine/core-modules/billing/services/billing-subscription.service';
import { StripeBillingPortalService } from 'src/engine/core-modules/billing/stripe/services/stripe-billing-portal.service';
import { StripeCheckoutService } from 'src/engine/core-modules/billing/stripe/services/stripe-checkout.service';
import { type BillingGetPricesPerPlanResult } from 'src/engine/core-modules/billing/types/billing-get-prices-per-plan-result.type';
import { type BillingPortalCheckoutSessionParameters } from 'src/engine/core-modules/billing/types/billing-portal-checkout-session-parameters.type';
import { DomainManagerService } from 'src/engine/core-modules/domain-manager/services/domain-manager.service';
import { UserWorkspace } from 'src/engine/core-modules/user-workspace/user-workspace.entity';
-import { type Workspace } from 'src/engine/core-modules/workspace/workspace.entity';
+import { Workspace } from 'src/engine/core-modules/workspace/workspace.entity';
import { assert } from 'src/utils/assert';
@Injectable()
@@ -30,8 +35,11 @@ export class BillingPortalWorkspaceService {
private readonly stripeCheckoutService: StripeCheckoutService,
private readonly stripeBillingPortalService: StripeBillingPortalService,
private readonly domainManagerService: DomainManagerService,
+ private readonly billingSubscriptionService: BillingSubscriptionService,
@InjectRepository(BillingSubscription, 'core')
private readonly billingSubscriptionRepository: Repository<BillingSubscription>,
+ @InjectRepository(BillingSubscriptionItem, 'core')
+ private readonly billingSubscriptionItemRepository: Repository<BillingSubscriptionItem>,
@InjectRepository(BillingCustomer, 'core')
private readonly billingCustomerRepository: Repository<BillingCustomer>,
@InjectRepository(UserWorkspace, 'core')
@@ -46,6 +54,73 @@ export class BillingPortalWorkspaceService {
plan,
requirePaymentMethod,
}: BillingPortalCheckoutSessionParameters): Promise<string> {
+ const { successUrl, cancelUrl, customer, stripeSubscriptionLineItems } =
+ await this.prepareSubscriptionParameters({
+ workspace,
+ billingPricesPerPlan,
+ successUrlPath,
+ });
+
+ const checkoutSession =
+ await this.stripeCheckoutService.createCheckoutSession({
+ user,
+ workspaceId: workspace.id,
+ stripeSubscriptionLineItems,
+ successUrl,
+ cancelUrl,
+ stripeCustomerId: customer?.stripeCustomerId,
+ plan,
+ requirePaymentMethod,
+ withTrialPeriod:
+ !isDefined(customer) || customer.billingSubscriptions.length === 0,
+ });
+
+ assert(checkoutSession.url, 'Error: missing checkout.session.url');
+
+ return checkoutSession.url;
+ }
+
+ async createDirectSubscription({
+ user,
+ workspace,
+ billingPricesPerPlan,
+ successUrlPath,
+ plan,
+ requirePaymentMethod,
+ }: BillingPortalCheckoutSessionParameters): Promise<string> {
+ const { successUrl, customer, stripeSubscriptionLineItems } =
+ await this.prepareSubscriptionParameters({
+ workspace,
+ billingPricesPerPlan,
+ successUrlPath,
+ });
+
+ const subscription =
+ await this.stripeCheckoutService.createDirectSubscription({
+ user,
+ workspaceId: workspace.id,
+ stripeSubscriptionLineItems,
+ stripeCustomerId: customer?.stripeCustomerId,
+ plan,
+ requirePaymentMethod,
+ withTrialPeriod:
+ !isDefined(customer) || customer.billingSubscriptions.length === 0,
+ });
+
+ await this.syncSubscriptionToDatabase(workspace.id, subscription);
+
+ return successUrl;
+ }
+
+ private async prepareSubscriptionParameters({
+ workspace,
+ billingPricesPerPlan,
+ successUrlPath,
+ }: {
+ workspace: Workspace;
+ billingPricesPerPlan?: BillingGetPricesPerPlanResult;
+ successUrlPath?: string;
+ }) {
const frontBaseUrl = this.domainManagerService.buildWorkspaceURL({
workspace,
});
@@ -70,23 +145,73 @@ export class BillingPortalWorkspaceService {
billingPricesPerPlan,
});
- const checkoutSession =
- await this.stripeCheckoutService.createCheckoutSession({
- user,
- workspaceId: workspace.id,
- stripeSubscriptionLineItems,
- successUrl,
- cancelUrl,
- stripeCustomerId: customer?.stripeCustomerId,
- plan,
- requirePaymentMethod,
- withTrialPeriod:
- !isDefined(customer) || customer.billingSubscriptions.length === 0,
- });
+ return {
+ successUrl,
+ cancelUrl,
+ quantity,
+ customer,
+ stripeSubscriptionLineItems,
+ };
+ }
- assert(checkoutSession.url, 'Error: missing checkout.session.url');
+ private async syncSubscriptionToDatabase(
+ workspaceId: string,
+ subscription: Stripe.Subscription,
+ ) {
+ await this.billingCustomerRepository.upsert(
+ transformStripeSubscriptionEventToDatabaseCustomer(workspaceId, {
+ object: subscription,
+ }),
+ {
+ conflictPaths: ['workspaceId'],
+ skipUpdateIfNoValuesChanged: true,
+ },
+ );
- return checkoutSession.url;
+ await this.billingSubscriptionRepository.upsert(
+ transformStripeSubscriptionEventToDatabaseSubscription(workspaceId, {
+ object: subscription,
+ }),
+ {
+ conflictPaths: ['stripeSubscriptionId'],
+ skipUpdateIfNoValuesChanged: true,
+ },
+ );
+
+ const billingSubscriptions = await this.billingSubscriptionRepository.find({
+ where: { workspaceId },
+ });
+
+ const createdBillingSubscription = billingSubscriptions.find(
+ (sub) => sub.stripeSubscriptionId === subscription.id,
+ );
+
+ if (!createdBillingSubscription) {
+ throw new BillingException(
+ 'Billing subscription not found after creation',
+ BillingExceptionCode.BILLING_SUBSCRIPTION_NOT_FOUND,
+ );
+ }
+ await this.billingSubscriptionItemRepository.upsert(
+ transformStripeSubscriptionEventToDatabaseSubscriptionItem(
+ createdBillingSubscription.id,
+ {
+ object: subscription,
+ },
+ ),
+ {
+ conflictPaths: ['stripeSubscriptionItemId'],
+ skipUpdateIfNoValuesChanged: true,
+ },
+ );
+
+ await this.billingSubscriptionService.setBillingThresholdsAndTrialPeriodWorkflowCredits(
+ createdBillingSubscription.id,
+ );
+
+ this.logger.log(
+ `Subscription synced to database: ${subscription.id} for workspace: ${workspaceId}`,
+ );
}
async computeBillingPortalSessionURLOrThrow(
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 d213c12c1f3..a1be9839697 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
@@ -1,15 +1,13 @@
/* @license Enterprise */
import { Injectable, Logger } from '@nestjs/common';
-import { InjectRepository } from '@nestjs/typeorm';
import { isDefined } from 'twenty-shared/utils';
-import { Repository } from 'typeorm';
import type Stripe from 'stripe';
-import { BillingCustomer } from 'src/engine/core-modules/billing/entities/billing-customer.entity';
import { BillingPlanKey } from 'src/engine/core-modules/billing/enums/billing-plan-key.enum';
+import { StripeCustomerService } from 'src/engine/core-modules/billing/stripe/services/stripe-customer.service';
import { StripeSDKService } from 'src/engine/core-modules/billing/stripe/stripe-sdk/services/stripe-sdk.service';
import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
import { type User } from 'src/engine/core-modules/user/user.entity';
@@ -22,8 +20,7 @@ export class StripeCheckoutService {
constructor(
private readonly twentyConfigService: TwentyConfigService,
private readonly stripeSDKService: StripeSDKService,
- @InjectRepository(BillingCustomer, 'core')
- private readonly billingCustomerRepository: Repository<BillingCustomer>,
+ private readonly stripeCustomerService: StripeCustomerService,
) {
if (!this.twentyConfigService.get('IS_BILLING_ENABLED')) {
return;
@@ -55,19 +52,13 @@ export class StripeCheckoutService {
withTrialPeriod: boolean;
}): Promise<Stripe.Checkout.Session> {
if (!isDefined(stripeCustomerId)) {
- const customer = await this.stripe.customers.create({
- email: user.email,
- metadata: {
+ const stripeCustomer =
+ await this.stripeCustomerService.createStripeCustomer(
+ user.email,
workspaceId,
- },
- });
+ );
- await this.billingCustomerRepository.save({
- stripeCustomerId: customer.id,
- workspaceId,
- });
-
- stripeCustomerId = customer.id;
+ stripeCustomerId = stripeCustomer.id;
}
return await this.stripe.checkout.sessions.create({
@@ -78,20 +69,10 @@ export class StripeCheckoutService {
workspaceId,
plan,
},
- ...(withTrialPeriod
- ? {
- trial_period_days: this.twentyConfigService.get(
- requirePaymentMethod
- ? 'BILLING_FREE_TRIAL_WITH_CREDIT_CARD_DURATION_IN_DAYS'
- : 'BILLING_FREE_TRIAL_WITHOUT_CREDIT_CARD_DURATION_IN_DAYS',
- ),
- trial_settings: {
- end_behavior: {
- missing_payment_method: 'create_invoice',
- },
- },
- }
- : {}),
+ ...this.getStripeSubscriptionTrialPeriodConfig(
+ withTrialPeriod,
+ requirePaymentMethod,
+ ),
},
automatic_tax: { enabled: !!requirePaymentMethod },
tax_id_collection: { enabled: !!requirePaymentMethod },
@@ -104,4 +85,75 @@ export class StripeCheckoutService {
: 'if_required',
});
}
+
+ async createDirectSubscription({
+ user,
+ workspaceId,
+ stripeSubscriptionLineItems,
+ stripeCustomerId,
+ plan = BillingPlanKey.PRO,
+ requirePaymentMethod = false,
+ withTrialPeriod,
+ }: {
+ user: User;
+ workspaceId: string;
+ stripeSubscriptionLineItems: Stripe.Checkout.SessionCreateParams.LineItem[];
+ stripeCustomerId?: string;
+ plan?: BillingPlanKey;
+ requirePaymentMethod?: boolean;
+ withTrialPeriod: boolean;
+ }): Promise<Stripe.Subscription> {
+ if (!isDefined(stripeCustomerId)) {
+ const stripeCustomer =
+ await this.stripeCustomerService.createStripeCustomer(
+ user.email,
+ workspaceId,
+ );
+
+ stripeCustomerId = stripeCustomer.id;
+ }
+
+ // Convert checkout session line items to subscription items format
+ const subscriptionItems: Stripe.SubscriptionCreateParams.Item[] =
+ stripeSubscriptionLineItems.map((lineItem) => ({
+ price: lineItem.price as string,
+ quantity: lineItem.quantity,
+ }));
+
+ const subscriptionParams: Stripe.SubscriptionCreateParams = {
+ customer: stripeCustomerId,
+ items: subscriptionItems,
+ metadata: {
+ workspaceId,
+ plan,
+ },
+ ...this.getStripeSubscriptionTrialPeriodConfig(
+ withTrialPeriod,
+ requirePaymentMethod,
+ ),
+ automatic_tax: { enabled: !!requirePaymentMethod },
+ };
+
+ return await this.stripe.subscriptions.create(subscriptionParams);
+ }
+
+ private getStripeSubscriptionTrialPeriodConfig(
+ withTrialPeriod: boolean,
+ requirePaymentMethod: boolean,
+ ) {
+ return withTrialPeriod
+ ? {
+ trial_period_days: this.twentyConfigService.get(
+ requirePaymentMethod
+ ? 'BILLING_FREE_TRIAL_WITH_CREDIT_CARD_DURATION_IN_DAYS'
+ : 'BILLING_FREE_TRIAL_WITHOUT_CREDIT_CARD_DURATION_IN_DAYS',
+ ),
+ trial_settings: {
+ end_behavior: {
+ missing_payment_method: 'create_invoice' as const,
+ },
+ },
+ }
+ : {};
+ }
}
diff --git a/packages/twenty-server/src/engine/core-modules/billing/stripe/services/stripe-customer.service.ts b/packages/twenty-server/src/engine/core-modules/billing/stripe/services/stripe-customer.service.ts
index 1b1ba102fe4..0ef3f1c7297 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/stripe/services/stripe-customer.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/stripe/services/stripe-customer.service.ts
@@ -1,9 +1,13 @@
/* @license Enterprise */
import { Injectable, Logger } from '@nestjs/common';
+import { InjectRepository } from '@nestjs/typeorm';
+
+import { Repository } from 'typeorm';
import type Stripe from 'stripe';
+import { BillingCustomer } from 'src/engine/core-modules/billing/entities/billing-customer.entity';
import { StripeSDKService } from 'src/engine/core-modules/billing/stripe/stripe-sdk/services/stripe-sdk.service';
import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
@@ -15,6 +19,8 @@ export class StripeCustomerService {
constructor(
private readonly twentyConfigService: TwentyConfigService,
private readonly stripeSDKService: StripeSDKService,
+ @InjectRepository(BillingCustomer, 'core')
+ private readonly billingCustomerRepository: Repository<BillingCustomer>,
) {
if (!this.twentyConfigService.get('IS_BILLING_ENABLED')) {
return;
@@ -39,4 +45,20 @@ export class StripeCustomerService {
return paymentMethods.length > 0;
}
+
+ async createStripeCustomer(userEmail: string, workspaceId: string) {
+ const customer = await this.stripe.customers.create({
+ email: userEmail,
+ metadata: {
+ workspaceId,
+ },
+ });
+
+ await this.billingCustomerRepository.save({
+ stripeCustomerId: customer.id,
+ workspaceId,
+ });
+
+ return customer;
+ }
}