File tree Expand file tree Collapse file tree 2 files changed +41
-0
lines changed
src/trpc/routers/billing-router Expand file tree Collapse file tree 2 files changed +41
-0
lines changed Original file line number Diff line number Diff line change
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
+ } ) ;
Original file line number Diff line number Diff line change @@ -2,9 +2,11 @@ import { createTRPCRouter } from "@/trpc/api/trpc";
2
2
import { checkoutProcedure } from "./procedures/checkout" ;
3
3
import { getProductsProcedure } from "./procedures/get-products" ;
4
4
import { getSubscriptionProcedure } from "./procedures/get-subscription" ;
5
+ import { stripePortalProcedure } from "./procedures/stripe-portal" ;
5
6
6
7
export const billingRouter = createTRPCRouter ( {
7
8
getProducts : getProductsProcedure ,
8
9
getSubscription : getSubscriptionProcedure ,
9
10
checkout : checkoutProcedure ,
11
+ stripePortal : stripePortalProcedure ,
10
12
} ) ;
You can’t perform that action at this time.
0 commit comments