Skip to content

Commit

Permalink
Zomars/cal 798 issue with billing portal (#1392)
Browse files Browse the repository at this point in the history
* Uses stripeCustomerId from used metadata in billing portal

* Uses stripeCustomerId from used metadata in billing portal

# Conflicts:
#	ee/pages/api/integrations/stripepayment/portal.ts
  • Loading branch information
zomars committed Dec 30, 2021
1 parent 4be4a01 commit 445faa4
Showing 1 changed file with 17 additions and 12 deletions.
29 changes: 17 additions & 12 deletions ee/pages/api/integrations/stripepayment/portal.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { Prisma } from "@prisma/client";
import type { NextApiRequest, NextApiResponse } from "next";

import stripe from "@ee/lib/stripe/server";
Expand All @@ -23,6 +24,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
select: {
email: true,
name: true,
metadata: true,
},
});

Expand All @@ -31,26 +33,29 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
message: "User email not found",
});

/**
* TODO: We need to find a better way to get our users customer id from Stripe,
* since the email is not an unique field in Stripe and we don't save them
* in our DB as of now.
**/
const customersReponse = await stripe.customers.list({
email: user?.email || "",
limit: 1,
});
let customerId = "";

const [customer] = customersReponse.data;
if (user?.metadata && typeof user.metadata === "object" && "stripeCustomerId" in user.metadata) {
customerId = (user?.metadata as Prisma.JsonObject).stripeCustomerId as string;
} else {
/* We fallback to finding the customer by email (which is not optimal) */
const customersReponse = await stripe.customers.list({
email: user.email,
limit: 1,
});
if (customersReponse.data[0]?.id) {
customerId = customersReponse.data[0].id;
}
}

if (!customer?.id)
if (!customerId)
return res.status(404).json({
message: "Stripe customer id not found",
});

const return_url = `${process.env.BASE_URL}/settings/billing`;
const stripeSession = await stripe.billingPortal.sessions.create({
customer: customer.id,
customer: customerId,
return_url,
});

Expand Down

1 comment on commit 445faa4

@vercel
Copy link

@vercel vercel bot commented on 445faa4 Dec 30, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.