import Stripe from 'stripe';
import { db } from '../db';
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, {
apiVersion: '2024-06-20',
});
const AUTO_RELOAD_THRESHOLD_CENTS = 200; // Trigger reload when balance drops below $2.00
const RELOAD_AMOUNT_CENTS = 1000; // Reload $10.00 in a single swipe to bypass $0.30 tax
/**
* Deducts AI token generation cost from internal user wallet.
* Triggers background auto-reload when remaining balance falls below threshold.
*/
export async function deductUsageAndAutoReload(userId: string, costCents: number) {
return await db.$transaction(async (tx) => {
// 1. Fetch current wallet balance
const wallet = await tx.wallet.findUnique({ where: { userId } });
if (!wallet || wallet.balanceCents < costCents) {
throw new Error('Insufficient wallet balance');
}
// 2. Debit internal counter (zero Stripe fees for internal database decrement!)
const updatedWallet = await tx.wallet.update({
where: { userId },
data: { balanceCents: { decrement: costCents } },
});
// 3. Check if auto-reload trigger condition is met
if (updatedWallet.balanceCents <= AUTO_RELOAD_THRESHOLD_CENTS && !wallet.isReloading) {
await tx.wallet.update({ where: { userId }, data: { isReloading: true } });
try {
// Charge user's saved payment method off-session
const paymentIntent = await stripe.paymentIntents.create({
amount: RELOAD_AMOUNT_CENTS,
currency: 'usd',
customer: wallet.stripeCustomerId,
payment_method: wallet.defaultPaymentMethodId,
off_session: true,
confirm: true,
description: 'Automated AI Credits Wallet Auto-Reload ($10.00)',
metadata: { userId, type: 'auto_reload' },
});
if (paymentIntent.status === 'succeeded') {
await tx.wallet.update({
where: { userId },
data: {
balanceCents: { increment: RELOAD_AMOUNT_CENTS },
isReloading: false,
},
});
}
} catch (err) {
console.error('Auto-reload charge failed:', err);
await tx.wallet.update({ where: { userId }, data: { isReloading: false } });
}
}
return updatedWallet.balanceCents;
});
}
import stripe
import os
stripe.api_key = os.getenv("STRIPE_SECRET_KEY")
def record_ai_token_usage_event(customer_id: str, tokens_consumed: int, meter_event_name: str = "ai_generation_tokens"):
"""
Emits raw usage events to Stripe Billing Meters without charging the credit card immediately.
Stripe accumulates events and triggers an invoice ONLY when threshold reaches $10.00.
"""
response = stripe.billing.MeterEvent.create(
event_name=meter_event_name,
payload={
"stripe_customer_id": customer_id,
"value": str(tokens_consumed),
}
)
return response
def setup_threshold_billing_subscription(customer_id: str, meter_price_id: str):
"""
Creates a subscription with an aggressive billing threshold of $10.00.
Prevents hundreds of micro-transactions from racking up $0.30 fixed swipe penalties.
"""
subscription = stripe.Subscription.create(
customer=customer_id,
items=[{"price": meter_price_id}],
billing_thresholds={
"amount_gte": 1000, # 1,000 cents = $10.00 threshold
"reset_billing_cycle_anchor": False,
},
payment_behavior="default_incomplete",
payment_settings={"save_default_payment_method": "on_subscription"},
)
return subscription
To: [email protected]
Subject: Request for Micropayments Pricing Schedule (Account: acct_YOUR_ACCOUNT_ID)
Hello Stripe Merchant Support,
I am writing to formally request the activation of Stripe's Micropayments pricing tier (5.0% + $0.10 per transaction) for our account: acct_YOUR_ACCOUNT_ID.
Business Model Overview:
- Company Name: [Your SaaS Name]
- Website: https://[yourdomain.com]
- Product: Developer API / Generative AI Micro-Credit Top-ups
- Average Transaction Value (AOV): $1.00 – $3.50 USD
- Current Monthly Processing Volume: $5,000 – $20,000 USD
- Monthly Transaction Count: 3,000 – 10,000 individual purchases
Under the standard 2.9% + $0.30 schedule, our effective payment processing fee drag exceeds 33.0% of gross revenue, which severely depresses our operational margins on low-ticket credit packages.
We have audited our chargeback and dispute history (current dispute rate: < 0.25%) and verified that the 5% + $0.10 schedule aligns with our low-ticket product mechanics.
Could you please confirm if our merchant account qualifies and enable the micropayments fee tier for USD transactions?
Thank you for your assistance.
Best regards,
[Your Name / Founder / CTO]