Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
feat: Stripe customer update fixes
Richie McIlroy670b630101f7
diff --git a/apps/web/actions/organization/manage-billing.ts b/apps/web/actions/organization/manage-billing.tsindex 4b559349a..73c132bc0 100644--- a/apps/web/actions/organization/manage-billing.ts+++ b/apps/web/actions/organization/manage-billing.ts@@ -6,6 +6,7 @@ import { users } from "@cap/database/schema";import { serverEnv } from "@cap/env";import { stripe } from "@cap/utils";import { eq } from "drizzle-orm";+import type Stripe from "stripe";export async function manageBilling() {const user = await getCurrentUser();@@ -16,13 +17,30 @@ export async function manageBilling() {}if (!user.stripeCustomerId) {- const customer = await stripe().customers.create({+ const existingCustomers = await stripe().customers.list({email: user.email,- metadata: {- userId: user.id,- },+ limit: 1,});+ let customer: Stripe.Customer;+ if (existingCustomers.data.length > 0 && existingCustomers.data[0]) {+ customer = existingCustomers.data[0];++ customer = await stripe().customers.update(customer.id, {+ metadata: {+ ...customer.metadata,+ userId: user.id,+ },+ });+ } else {+ customer = await stripe().customers.create({+ email: user.email,+ metadata: {+ userId: user.id,+ },+ });+ }+await db().update(users).set({diff --git a/apps/web/app/api/desktop/[...route]/root.ts b/apps/web/app/api/desktop/[...route]/root.tsindex 8e0f53bd8..2b87779bc 100644--- a/apps/web/app/api/desktop/[...route]/root.ts+++ b/apps/web/app/api/desktop/[...route]/root.ts@@ -7,6 +7,7 @@ import { zValidator } from "@hono/zod-validator";import { eq } from "drizzle-orm";import { Hono } from "hono";import { PostHog } from "posthog-node";+import type Stripe from "stripe";import { z } from "zod";import { withAuth } from "../../utils";@@ -72,7 +73,6 @@ app.get("/org-custom-domain", async (c) => {.leftJoin(organizations, eq(users.activeOrganizationId, organizations.id)).where(eq(users.id, user.id));- // Ensure custom domain has https:// prefixlet customDomain = result?.customDomain ?? null;if (customDomain &&@@ -151,19 +151,43 @@ app.post(let customerId = user.stripeCustomerId;if (user.stripeCustomerId === null) {- console.log("[POST] Creating new Stripe customer");- const customer = await stripe().customers.create({+ console.log(+ "[POST] Checking for existing Stripe customer for email:",+ user.email,+ );++ const existingCustomers = await stripe().customers.list({email: user.email,- metadata: { userId: user.id },+ limit: 1,});+ let customer: Stripe.Customer;+ if (existingCustomers.data.length > 0 && existingCustomers.data[0]) {+ customer = existingCustomers.data[0];+ console.log("[POST] Found existing Stripe customer:", customer.id);++ customer = await stripe().customers.update(customer.id, {+ metadata: {+ ...customer.metadata,+ userId: user.id,+ },+ });+ console.log("[POST] Updated existing customer metadata with userId");+ } else {+ console.log("[POST] Creating new Stripe customer");+ customer = await stripe().customers.create({+ email: user.email,+ metadata: { userId: user.id },+ });+ console.log("[POST] Created Stripe customer:", customer.id);+ }+await db().update(users).set({ stripeCustomerId: customer.id }).where(eq(users.id, user.id));customerId = customer.id;- console.log("[POST] Created Stripe customer:", customerId);}console.log("[POST] Creating checkout session");diff --git a/apps/web/app/api/settings/billing/manage/route.ts b/apps/web/app/api/settings/billing/manage/route.tsindex 2f2baf786..6726df976 100644--- a/apps/web/app/api/settings/billing/manage/route.ts+++ b/apps/web/app/api/settings/billing/manage/route.ts@@ -5,6 +5,7 @@ import { serverEnv } from "@cap/env";import { stripe } from "@cap/utils";import { eq } from "drizzle-orm";import { type NextRequest, NextResponse } from "next/server";+import type Stripe from "stripe";export async function POST(request: NextRequest) {const user = await getCurrentUser();@@ -17,13 +18,30 @@ export async function POST(request: NextRequest) {}if (!user.stripeCustomerId) {- const customer = await stripe().customers.create({+ const existingCustomers = await stripe().customers.list({email: user.email,- metadata: {- userId: user.id,- },+ limit: 1,});+ let customer: Stripe.Customer;+ if (existingCustomers.data.length > 0 && existingCustomers.data[0]) {+ customer = existingCustomers.data[0];++ customer = await stripe().customers.update(customer.id, {+ metadata: {+ ...customer.metadata,+ userId: user.id,+ },+ });+ } else {+ customer = await stripe().customers.create({+ email: user.email,+ metadata: {+ userId: user.id,+ },+ });+ }+await db().update(users).set({diff --git a/apps/web/app/api/settings/billing/subscribe/route.ts b/apps/web/app/api/settings/billing/subscribe/route.tsindex 20a1a2c7b..50a90e489 100644--- a/apps/web/app/api/settings/billing/subscribe/route.ts+++ b/apps/web/app/api/settings/billing/subscribe/route.ts@@ -6,16 +6,13 @@ import { stripe, userIsPro } from "@cap/utils";import { eq } from "drizzle-orm";import type { NextRequest } from "next/server";import { PostHog } from "posthog-node";+import type Stripe from "stripe";export async function POST(request: NextRequest) {- console.log("Starting subscription process");const user = await getCurrentUser();let customerId = user?.stripeCustomerId;const { priceId, quantity } = await request.json();- console.log("Received request with priceId:", priceId);- console.log("Current user:", user?.id);-if (!priceId) {console.error("Price ID not found");return Response.json({ error: true }, { status: 400 });@@ -33,15 +30,29 @@ export async function POST(request: NextRequest) {try {if (!user.stripeCustomerId) {- console.log("Creating new Stripe customer for user:", user.id);- const customer = await stripe().customers.create({+ const existingCustomers = await stripe().customers.list({email: user.email,- metadata: {- userId: user.id,- },+ limit: 1,});- console.log("Created Stripe customer:", customer.id);+ let customer: Stripe.Customer;+ if (existingCustomers.data.length > 0 && existingCustomers.data[0]) {+ customer = existingCustomers.data[0];++ customer = await stripe().customers.update(customer.id, {+ metadata: {+ ...customer.metadata,+ userId: user.id,+ },+ });+ } else {+ customer = await stripe().customers.create({+ email: user.email,+ metadata: {+ userId: user.id,+ },+ });+ }await db().update(users)@@ -49,12 +60,8 @@ export async function POST(request: NextRequest) {stripeCustomerId: customer.id,}).where(eq(users.id, user.id));-- console.log("Updated user with Stripe customer ID");customerId = customer.id;}-- console.log("Creating checkout session for customer:", customerId);const checkoutSession = await stripe().checkout.sessions.create({customer: customerId as string,line_items: [{ price: priceId, quantity: quantity }],@@ -66,8 +73,6 @@ export async function POST(request: NextRequest) {});if (checkoutSession.url) {- console.log("Successfully created checkout session");-try {const ph = new PostHog(buildEnv.NEXT_PUBLIC_POSTHOG_KEY || "", {host: buildEnv.NEXT_PUBLIC_POSTHOG_HOST || "",diff --git a/packages/database/auth/drizzle-adapter.ts b/packages/database/auth/drizzle-adapter.tsindex 3d1b6902d..14d61270a 100644--- a/packages/database/auth/drizzle-adapter.ts+++ b/packages/database/auth/drizzle-adapter.ts@@ -2,6 +2,7 @@ import { STRIPE_AVAILABLE, stripe } from "@cap/utils";import { and, eq } from "drizzle-orm";import type { PlanetScaleDatabase } from "drizzle-orm/planetscale-serverless";import type { Adapter } from "next-auth/adapters";+import type Stripe from "stripe";import { nanoId } from "../helpers";import { accounts, sessions, users, verificationTokens } from "../schema";@@ -25,17 +26,57 @@ export function DrizzleAdapter(db: PlanetScaleDatabase): Adapter {if (!row) throw new Error("User not found");if (STRIPE_AVAILABLE()) {- const customer = await stripe().customers.create({+ const existingCustomers = await stripe().customers.list({email: userData.email,- metadata: {- userId: nanoId(),- },+ limit: 1,+ });++ let customer: Stripe.Customer;+ if (existingCustomers.data.length > 0 && existingCustomers.data[0]) {+ customer = existingCustomers.data[0];++ customer = await stripe().customers.update(customer.id, {+ metadata: {+ ...customer.metadata,+ userId: row.id,+ },+ });+ } else {+ customer = await stripe().customers.create({+ email: userData.email,+ metadata: {+ userId: row.id,+ },+ });+ }++ const subscriptions = await stripe().subscriptions.list({+ customer: customer.id,+ status: "active",+ limit: 100,});+ const inviteQuota = subscriptions.data.reduce((total, sub) => {+ return (+ total ++ sub.items.data.reduce(+ (subTotal, item) => subTotal + (item.quantity || 1),+ 0,+ )+ );+ }, 0);++ const mostRecentSubscription = subscriptions.data[0];+await db.update(users).set({stripeCustomerId: customer.id,+ ...(mostRecentSubscription && {+ stripeSubscriptionId: mostRecentSubscription.id,+ stripeSubscriptionStatus: mostRecentSubscription.status,+ inviteQuota: inviteQuota || 1,+ }),}).where(eq(users.id, row.id));}@@ -58,7 +99,6 @@ export function DrizzleAdapter(db: PlanetScaleDatabase): Adapter {.where(eq(users.email, email)).limit(1).catch((e) => {- console.log(e);throw e;});const row = rows[0];@@ -182,29 +222,23 @@ export function DrizzleAdapter(db: PlanetScaleDatabase): Adapter {await db.delete(sessions).where(eq(sessions.sessionToken, sessionToken));},async createVerificationToken(verificationToken) {- // First, check if a token for the given identifier already existsconst existingTokens = await db.select().from(verificationTokens).where(eq(verificationTokens.identifier, verificationToken.identifier)).limit(1);- // If a token already exists, you can return the existing token- // or handle it based on your business logicif (existingTokens.length > 0) {- // For example, updating the existing token:await db.update(verificationTokens).set({token: verificationToken.token,expires: verificationToken.expires,- // you may update other fields as necessary}).where(eq(verificationTokens.identifier, verificationToken.identifier),);- // Return the updated tokenreturn await db.select().from(verificationTokens)@@ -215,14 +249,12 @@ export function DrizzleAdapter(db: PlanetScaleDatabase): Adapter {.then((rows) => rows[0]);}- // If the token does not exist, proceed to create a new oneawait db.insert(verificationTokens).values({expires: verificationToken.expires,identifier: verificationToken.identifier,token: verificationToken.token,});- // Retrieve and return the newly created tokenconst rows = await db.select().from(verificationTokens)