Skip to content

Commit 8e8f78a

Browse files
committed
feat: add stripe portal
1 parent 2f42ac5 commit 8e8f78a

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
import { env } from "@/env";
2+
import { invariant } from "@/lib/error";
3+
import { checkMembership } from "@/server/auth";
4+
import { createOrRetrieveCustomer, stripe } from "@/server/stripe";
5+
import { withAuth } from "@/trpc/api/trpc";
6+
7+
export const stripePortalProcedure = withAuth.mutation(async ({ ctx }) => {
8+
const { db, session } = ctx;
9+
10+
const { url } = await db.$transaction(async (tx) => {
11+
const { companyId } = await checkMembership({ session, tx });
12+
13+
let customer: string;
14+
try {
15+
customer = await createOrRetrieveCustomer({
16+
tx,
17+
companyId,
18+
email: "",
19+
});
20+
} catch (_error) {
21+
throw new Error("Unable to access customer record.");
22+
}
23+
24+
invariant(customer, "Could not get customer.");
25+
26+
try {
27+
const { url } = await stripe.billingPortal.sessions.create({
28+
customer,
29+
return_url: `${env.NEXT_PUBLIC_BASE_URL}/${session.user.companyPublicId}/settings/billing`,
30+
});
31+
32+
return { url };
33+
} catch (_error) {
34+
throw new Error("Could not create billing portal.");
35+
}
36+
});
37+
38+
return { url };
39+
});

src/trpc/routers/billing-router/router.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,11 @@ import { createTRPCRouter } from "@/trpc/api/trpc";
22
import { checkoutProcedure } from "./procedures/checkout";
33
import { getProductsProcedure } from "./procedures/get-products";
44
import { getSubscriptionProcedure } from "./procedures/get-subscription";
5+
import { stripePortalProcedure } from "./procedures/stripe-portal";
56

67
export const billingRouter = createTRPCRouter({
78
getProducts: getProductsProcedure,
89
getSubscription: getSubscriptionProcedure,
910
checkout: checkoutProcedure,
11+
stripePortal: stripePortalProcedure,
1012
});

0 commit comments

Comments
 (0)