The Billing & Payments module (billing) sells credits: users buy them through Stripe or Dodo Payments, and your features spend them.
Credits
Every user has two counters on the User model:
| Field | Meaning |
|---|---|
creditsTotal | Credits granted or bought. New users start with 20 (the schema default) |
creditsUsed | Credits spent |
Remaining credits = creditsTotal - creditsUsed. The sidebar user menu shows a progress bar, and Settings → Plans & Billing shows the balance, a purchase slider and the transaction history.
Buying credits
- The user picks an amount between 50 and 1,000 in steps of 50.
billing.createCheckoutSession({ credits })creates a checkout with the configured gateway. Credits must be a multiple of 50; one unit = 50 credits.- The user pays on the gateway's page and returns to
/?payment=success. - The gateway calls your webhook, which records a
Transactionand adds the credits.
"use client";
import { useMutation } from "@tanstack/react-query";
import { useTRPC } from "@/trpc/client";
const trpc = useTRPC();
const checkout = useMutation(trpc.billing.createCheckoutSession.mutationOptions());
const { checkoutUrl } = await checkout.mutateAsync({ credits: 100 });
if (checkoutUrl) window.location.href = checkoutUrl;
Setting your price
The price lives in two places. Change both:
- What the user sees:
packages/ui/src/components/payments/CreditsPurchase.tsxshows $1.00 per 50 credits. - What is charged:
- Stripe:
unit_amountincreateCheckoutSessioninapps/web/trpc/routers/billingProcedures.ts, in cents for the whole order. The shipped value isquantity * 50, an example price of $0.50 per 50 credits. - Dodo: the price of the product in
DODO_CREDITS_PRODUCT_ID, multiplied by the quantity.
- Stripe:
CREDITS_PER_UNIT (50) in the same router sets the unit size.
Spending credits
Check and deduct on the server before doing the work:
import { TRPCError } from "@trpc/server";
import { z } from "zod";
import db from "@workspace/database/client";
import { createTRPCRouter, protectedProcedure } from "@/trpc/init";
const REPORT_COST = 5;
export const reportsRouter = createTRPCRouter({
generate: protectedProcedure
.input(z.object({ topic: z.string().min(1) }))
.mutation(async ({ ctx, input }) => {
const userId = ctx.session.user.id;
await db.$transaction(async (tx) => {
const user = await tx.user.findUniqueOrThrow({
where: { id: userId },
select: { creditsTotal: true, creditsUsed: true },
});
if (user.creditsTotal - user.creditsUsed < REPORT_COST) {
throw new TRPCError({ code: "FORBIDDEN", message: "Not enough credits" });
}
await tx.user.update({
where: { id: userId },
data: { creditsUsed: { increment: REPORT_COST } },
});
});
return generateReport(input.topic);
}),
});
If the work can fail after charging, refund with creditsUsed: { decrement: REPORT_COST }. The AI Platform module charges after the model responds, based on tokens used: see AI Platform.
Transactions
billing.getTransactions lists the user's payments, newest first. Each Transaction stores the gateway event, a unique checkoutSessionId, amount, currency and a receipt or invoice URL.
Procedures
| Procedure | Type | Purpose |
|---|---|---|
billing.createCheckoutSession | mutation | Start a checkout for N credits |
billing.createNewCustomer | mutation | Create a customer at the gateway |
billing.getCreditsBalance | query | creditsTotal and creditsUsed |
billing.getTransactions | query | Payment history |
All require a signed-in, non-guest user.
Subscriptions
The module sells one-time credit packs. For subscriptions, use your gateway's subscription products and handle their events in the webhook. The Dodo handler already has an onSubscriptionActive hook where that logic goes. Store the plan on the user (the access field — TRIAL, PRO, ENTERPRISE, UNLIMITED — is there for this) and check it in your procedures.
Gateway setup and webhooks are on Payment Gateways.
