DEV Community

LeadHunting AI
LeadHunting AI

Posted on Originally published at leadhunting.app

How to Build a Credit Billing System with 500% Margin Using Stripe

How to Build a Credit Billing System with 500% Margin

The Business Model

At LeadHunting AI, I needed a billing system where admin uses AI tools for $0 (Google AI Studio free tier) and users pay credits for AI generation at 500%+ margin.

Credit Packs

Users purchase credit packs:

  • 25 credits for $1
  • 100 credits for $3
  • 500 credits for $10
  • 1,000 credits for $18
  • 5,000 credits for $75
  • 25,000 credits for $250

Stripe Dynamic Pricing

Instead of creating products in Stripe, I use price_data:

const session = await stripe.checkout.sessions.create({
  mode: 'payment',
  line_items: [{
    price_data: {
      currency: 'usd',
      product_data: { name: '100 AI Credits' },
      unit_amount: 300, // $3.00
    },
    quantity: 1,
  }],
  metadata: { userId, credits: 100 },
});
Enter fullscreen mode Exit fullscreen mode

No product management needed. Just dynamic pricing.

Atomic Credit Deduction

Credits are deducted BEFORE generation (pre-pay model):

  1. Check user exists and is active
  2. Check daily limit not exceeded
  3. Check sufficient balance
  4. Atomically decrement creditBalance
  5. Create Transaction record
  6. Create UsageEvent for tracking

All in one DB transaction — no race conditions.

Auto-Refund on Failure

If AI generation fails (e.g., API error), credits are auto-refunded:

try {
  const result = await generateContent();
  return result;
} catch (err) {
  await refundCredits(transactionId, err.message);
  throw err;
}
Enter fullscreen mode Exit fullscreen mode

The Math (500%+ Margin)

Category Cost User Pays Profit Markup
Text (2K tokens) $0.0006 $0.02 $0.0194 3,233%
Image (1) $0.04 $0.30 $0.26 650%
Video (8s) $2.80 $16.80 $14.00 500%
Audio (3K chars) $0.048 $0.30 $0.252 525%

Admin Cost: $0

Admin uses Google AI Studio free tier (1,500 req/day). No cost.

Try It


Originally published on leadhunting.app

How do you handle billing in your SaaS? Share below!

Top comments (0)