Skip to content

Commit

Permalink
fix(workingparty): Lazy initialization of stripe client
Browse files Browse the repository at this point in the history
  • Loading branch information
AleksandarDev committed Oct 16, 2024
1 parent 918bf3d commit 1166665
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 20 deletions.
10 changes: 5 additions & 5 deletions web/apps/workingparty/app/api/stripe/webhook/route.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import Stripe from 'stripe';
import { stripe } from '../../../../src/lib/stripe/config';
import { getStripe } from '../../../../src/lib/stripe/config';
import { plansCreate, plansDelete, plansGetAll, plansGetByStripePriceId, plansUpdate } from '../../../../src/lib/repository/plansRepository';
import { accountGetByStripeCustomerId, accountSubscriptionCreate, accountSubscriptionSetStatus, accountSubscriptions } from '../../../../src/lib/repository/accountsRepository';

Expand Down Expand Up @@ -30,7 +30,7 @@ async function deletePriceRecord(price: Stripe.Price) {

async function upsertPriceRecord(price: Stripe.Price) {
const product = typeof price.product === 'string'
? await stripe.products.retrieve(price.product)
? await getStripe().products.retrieve(price.product)
: price.product;
if (!product || product.deleted) {
throw new Error('Product not found');
Expand Down Expand Up @@ -95,7 +95,7 @@ async function createSubscription(stripeSubscriptionId: string, stripeCustomerId
throw new Error('Account not found');
}

const stripeSubscription = await stripe.subscriptions.retrieve(stripeSubscriptionId);
const stripeSubscription = await getStripe().subscriptions.retrieve(stripeSubscriptionId);
if (stripeSubscription.items.data.length > 1) {
throw new Error('Multiple items in subscription not supported');
}
Expand Down Expand Up @@ -123,7 +123,7 @@ async function manageSubscriptionStatusChange(stripeSubscriptionId: string, stri
throw new Error('Account not found');
}

const stripeSubscription = await stripe.subscriptions.retrieve(stripeSubscriptionId);
const stripeSubscription = await getStripe().subscriptions.retrieve(stripeSubscriptionId);
if (stripeSubscription.items.data.length > 1) {
throw new Error('Multiple items in subscription not supported');
}
Expand Down Expand Up @@ -153,7 +153,7 @@ export async function POST(req: Request) {
try {
if (!sig || !webhookSecret)
return new Response('Webhook secret not found.', { status: 400 });
event = stripe.webhooks.constructEvent(body, sig, webhookSecret);
event = getStripe().webhooks.constructEvent(body, sig, webhookSecret);
console.info(`🔔 Webhook received: ${event.type}`);
} catch (err: unknown) {
if (err instanceof Error) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { nanoid } from 'nanoid';
import { PatchOperation } from '@azure/cosmos';
import { stripe } from '../stripe/config';
import { getStripe } from '../stripe/config';
import { cosmosDataContainerAccounts, cosmosDataContainerSubscriptions, cosmosDataContainerUsage } from '../cosmosClient';
import { workersGetAll } from './workersRepository';
import { DbPlan, plansGet, plansGetAll } from './plansRepository';
Expand Down Expand Up @@ -178,7 +178,7 @@ async function accountCancelAllSubscriptions(accountId: string) {
if (!activeSubscription?.stripeSubscriptionId) continue;

try {
await stripe.subscriptions.cancel(activeSubscription.stripeSubscriptionId, {
await getStripe().subscriptions.cancel(activeSubscription.stripeSubscriptionId, {
cancellation_details: {
comment: 'Plan upgraded'
}
Expand Down
15 changes: 11 additions & 4 deletions web/apps/workingparty/src/lib/stripe/config.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,14 @@
import Stripe from 'stripe';

export const stripe = new Stripe(
process.env.STRIPE_SECRETKEY ?? '',
{
let stripe: Stripe | null = null;

export function getStripe() {
if (!stripe) {
stripe = new Stripe(
process.env.STRIPE_SECRETKEY ?? '',
{
}
);
}
);
return stripe;
}
18 changes: 9 additions & 9 deletions web/apps/workingparty/src/lib/stripe/serverStripe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,21 +5,21 @@ import { showNotification } from '@signalco/ui-notifications';
import { DbAccount, accountAssignStripeCustomer } from '../repository/accountsRepository';
import { domain } from '../../providers/env';
import { KnownPages } from '../../knownPages';
import { stripe } from './config';
import { getStripe } from './config';

const returnUrl = `https://${domain}/${KnownPages.AppSettingsAccountBilling}`;

async function ensureStripeCustomer(account: DbAccount): Promise<string> {
// Check if the user already has a Stripe customer ID
// Ensure customer still exists in Stripe and is not deleted
if (account.stripeCustomerId && account.stripeCustomerId.length > 0) {
const existingCustomerId = await stripe.customers.retrieve(account.stripeCustomerId);
const existingCustomerId = await getStripe().customers.retrieve(account.stripeCustomerId);
if (existingCustomerId && !existingCustomerId.deleted)
return existingCustomerId.id;
}

// Try to find customer by email
const customers = await stripeListAll<Stripe.Customer>(params => stripe.customers.list({
const customers = await stripeListAll<Stripe.Customer>(params => getStripe().customers.list({
email: account.email,
...params
}));
Expand All @@ -33,7 +33,7 @@ async function ensureStripeCustomer(account: DbAccount): Promise<string> {
}

// Create a new customer in Stripe
const newCustomer = await stripe.customers.create({
const newCustomer = await getStripe().customers.create({
email: account.email,
name: account.name
});
Expand Down Expand Up @@ -67,7 +67,7 @@ export async function stripeCheckout(
// Create a checkout session in Stripe
let session;
try {
session = await stripe.checkout.sessions.create(params);
session = await getStripe().checkout.sessions.create(params);
} catch (err) {
console.error(err);
throw new Error('Unable to create checkout session.');
Expand All @@ -91,7 +91,7 @@ export async function stripeCheckout(
export async function stripeCustomerBillingInfo(account: DbAccount) {
try {
const customerId = await ensureStripeCustomer(account);
const stripeCustomer = await stripe.customers.retrieve(customerId);
const stripeCustomer = await getStripe().customers.retrieve(customerId);
if (stripeCustomer.deleted)
throw new Error('Customer not found');

Expand Down Expand Up @@ -128,11 +128,11 @@ async function stripeListAll<T extends { id: string }>(fetchMethod: (params: Str
export async function stripeCustomerPaymentMethods(account: DbAccount) {
try {
const customerId = await ensureStripeCustomer(account);
const stripeCustomer = await stripe.customers.retrieve(customerId);
const stripeCustomer = await getStripe().customers.retrieve(customerId);
if (stripeCustomer.deleted)
throw new Error('Customer not found');

const paymentMethods = await stripeListAll<Stripe.PaymentMethod>(params => stripe.paymentMethods.list({
const paymentMethods = await stripeListAll<Stripe.PaymentMethod>(params => getStripe().paymentMethods.list({
customer: customerId,
...params
}));
Expand Down Expand Up @@ -161,7 +161,7 @@ export async function stripeCreatePortal(account: DbAccount) {
try {
const customer = await ensureStripeCustomer(account);
try {
const { url } = await stripe.billingPortal.sessions.create({
const { url } = await getStripe().billingPortal.sessions.create({
customer,
return_url: returnUrl
});
Expand Down

0 comments on commit 1166665

Please sign in to comment.