From 8955eb7a097ded42ffb0470961054b4383d94aff Mon Sep 17 00:00:00 2001 From: Simon Larsen Date: Thu, 2 Mar 2023 14:15:10 +0000 Subject: [PATCH] fix plan change bug --- CommonServer/Services/BillingService.ts | 62 +++++++++++++------------ 1 file changed, 32 insertions(+), 30 deletions(-) diff --git a/CommonServer/Services/BillingService.ts b/CommonServer/Services/BillingService.ts index 63a709f671..6ff7ddfa71 100644 --- a/CommonServer/Services/BillingService.ts +++ b/CommonServer/Services/BillingService.ts @@ -84,7 +84,8 @@ export class BillingService { plan: SubscriptionPlan, quantity: number, isYearly: boolean, - trial: boolean | Date | undefined + trial: boolean | Date | undefined, + defaultPaymentMethodId?: string | undefined ): Promise<{ id: string; trialEndsAt: Date | null; @@ -95,15 +96,7 @@ export class BillingService { ); } - const paymentMethods = await this.getPaymentMethods(customerId); - - if ( - paymentMethods.length === 0 - ) { - throw new BadDataException( - 'No payment methods added. Please add your card to this project to change your plan' - ); - } + let trialDate: Date | null = null; @@ -115,23 +108,30 @@ export class BillingService { trialDate = trial; } + const subscriptionParams: Stripe.SubscriptionCreateParams = { + customer: customerId, + + items: [ + { + price: isYearly + ? plan.getYearlyPlanId() + : plan.getMonthlyPlanId(), + quantity: quantity, + }, + ], + trial_end: + trialDate && plan.getTrialPeriod() > 0 + ? OneUptimeDate.toUnixTimestamp(trialDate) + : 'now', + }; + + if(defaultPaymentMethodId){ + subscriptionParams.default_payment_method = defaultPaymentMethodId; + } + + const subscription: Stripe.Response = - await this.stripe.subscriptions.create({ - customer: customerId, - default_payment_method: paymentMethods[0]?.id || '', - items: [ - { - price: isYearly - ? plan.getYearlyPlanId() - : plan.getMonthlyPlanId(), - quantity: quantity, - }, - ], - trial_end: - trialDate && plan.getTrialPeriod() > 0 - ? OneUptimeDate.toUnixTimestamp(trialDate) - : 'now', - }); + await this.stripe.subscriptions.create(subscriptionParams); return { id: subscription.id, @@ -191,11 +191,12 @@ export class BillingService { if (!subscription) { throw new BadDataException('Subscription not found'); - } + } + + const paymentMethods: Array = await this.getPaymentMethods(subscription.customer.toString()); if ( - (await this.getPaymentMethods(subscription.customer.toString())) - .length === 0 + paymentMethods.length === 0 ) { throw new BadDataException( 'No payment methods added. Please add your card to this project to change your plan' @@ -216,7 +217,8 @@ export class BillingService { newPlan, quantity, isYearly, - endTrialAt + endTrialAt, + paymentMethods[0]?.id ); return {