Credit System
The credits system is not the default payment system for NextAI, but can easly changed.
Instead of checking if the user has the right subscription tier.
if (!user || user.publicMetadata.subscriptionTier as number < 1) {
return Response.json('Unauthorized!', { status: 401 });
}
We simply deduct credits from the users account.
if (!user || !deductCredits(userId, amount)) {
return Response.json('Unauthorized!', { status: 401 });
}
deductCredits returns true when the action succeeded (when the user still has enough credits) or false when the action failed. This means that action has already been done and must not be called again.
How It Works
The credit system allows users to purchase credits that can be spent on AI interactions. Here's how it works:
- Users purchase credit bundles through Stripe
- Credits are added to their account balance
- Credits are deducted when using AI features
Implementation
The credit system is implemented in app/(payments)/api/stripe/checkout/credits/route.ts
:
// Example of creating a checkout session for credits
const session = await stripe.checkout.sessions.create({
line_items: [{
price_data: {
currency: 'usd',
product_data: {
name: `${creditName} Bundle`,
description: `Bundle of ${quantity} ${creditName}`,
},
unit_amount: unitAmount,
},
quantity: quantity,
}],
mode: "payment",
success_url: `${process.env.NEXT_PUBLIC_URL}/success?session_id={CHECKOUT_SESSION_ID}`,
cancel_url: `${process.env.NEXT_PUBLIC_URL}/cancel`,
});
Customizing Credit Pricing
You can adjust the credit price by modifying the CREDIT_PRICE_USD
environment variable. The default price is $0.10 per credit.
Checkout
So when you want to fetch a checkout session for buying credits you just need to fetch (/api/stripe/checkout/credits
).
Example:
// Client-side: Initiating checkout
async function handleCheckout() {
const response = await fetch('/api/stripe/checkout/credits', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ quantity: 100 })
});
const { url } = await response.json();
window.location.href = url;
}