What You’ll Build
In this quickstart, you’ll set up a complete monetization flow for your AI service. By the end, you’ll have:- A Stripe Connect account configured for payouts
- A product with custom pricing rules
- A functioning checkout flow to onboard customers
- Customer wallet connections for billing
- Forward tokens generated for API authentication
- Revenue tracking visible in your dashboard
Prerequisites: You need a Lava merchant account and have completed the Build Quickstart. This tutorial builds on that foundation to add customer billing.
Step 1: Connect Your Stripe Account
Before you can earn revenue, Lava needs a way to pay you. We use Stripe Connect Express for secure, automated payouts.Start Stripe Onboarding
- Open your dashboard at lavapayments.com/dashboard
- Navigate to Monetize > Billing in the sidebar
- Click “Connect Stripe Account”
- Complete the Stripe onboarding form:
- Business details (name, type, address)
- Bank account for payouts
- Tax information (EIN or SSN)
- Submit and wait for approval (usually instant)
Verify Connection
After completing onboarding, you’ll see:- Payout Schedule: When you’ll receive funds (typically daily or weekly)
- Account Status: “Active” when ready to accept payments
- Balance: Current pending payout amount
Stripe handles all compliance, tax reporting, and payment processing. Lava never holds your funds—payouts go directly to your bank account on the schedule you configure.
Step 2: Create Your First Product
Products define how you charge customers. Let’s create a product with tiered pricing to reward high-volume usage.Via Dashboard (Recommended for First Product)
- Navigate to Monetize > Products
- Click “New Product”
- Configure your pricing:
- Name: “AI Chat API - Standard”
- Description: “Production API access with tiered pricing”
- Fixed Fee:
$0.05per 1K tokens (predictable pricing) - Percentage Markup: Leave at
0%for now - Billing Basis: “Input + Output Tokens”
- Tier 1: 0-1M tokens at
$0.05per 1K tokens - Tier 2: 1M-10M tokens at
$0.03per 1K tokens - Tier 3: 10M+ tokens at
$0.01per 1K tokens
- Base Costs: “Wallet Pays” (users cover provider costs)
- Merchant Fees: “Wallet Pays” (users cover your markup)
- When balance is low: “Block Requests” (safe default)
- Click “Create Product”
- Copy the Product Secret (looks like
prod_xxxxxxxxxxxxx)
Via API (For Programmatic Setup)
What’s a product secret? It’s a unique identifier that gets included in forward tokens to apply specific pricing rules. You can create multiple products for different pricing tiers (e.g., “Hobby”, “Pro”, “Enterprise”).
Step 3: Install the Checkout Component
Lava provides a React component that handles wallet creation, phone verification, and payment—all in one embedded flow.Installation
Component Overview
The<LavaCheckout> component provides:
- Phone verification via SMS OTP (Twilio)
- Wallet creation for new users OR linking existing wallets
- Stripe payment integration for adding funds
- Connection creation linking the wallet to your merchant account
- Success callback with connection credentials for API calls
Step 4: Create a Checkout Session (Backend)
Before embedding the checkout component, you need to create a session on your backend. This ensures security and lets you configure checkout behavior.Next.js API Route Example
Express.js Example
Session secrets are single-use and expire after 30 minutes. Create a new session for each checkout attempt. Sessions are stored in Redis for fast access during the checkout flow.
Step 5: Embed the Checkout Component (Frontend)
Now embed the checkout component in your React application.Basic Integration
With Custom Styling
Step 6: Handle Checkout Completion
When a user completes checkout, you need to capture the connection details to generate forward tokens for API authentication.Frontend Callback (Immediate)
TheonSuccess callback receives connection data immediately after payment:
Webhook Handler (Reliable Backup)
Set up a webhook handler to capture checkout events reliably (handles network failures, closed tabs, etc.):Webhook Configuration
- Navigate to Monetize > Webhooks in the dashboard
- Click “Create Webhook”
- Enter your webhook URL:
https://yourdomain.com/api/webhooks/lava - Select events:
checkout.completed,connection.wallet.balance.updated - Copy the webhook secret and add to your
.env:
Step 7: Generate Forward Tokens
Now that you have a connection, generate forward tokens for your customers to use in API calls.Using the SDK (Recommended)
Manual Generation (Advanced)
If you’re not using Node.js, you can generate tokens manually:Distributing Tokens to Customers
Once generated, customers use forward tokens in their API calls:Security best practice: Never expose your secret key to customers. Only distribute forward tokens, which are scoped to specific connections and products. Customers cannot access other connections or modify pricing with a forward token.
Step 8: Track Revenue in Your Dashboard
Monitor your revenue, usage, and customer activity in real-time.Revenue Dashboard
Navigate to Monetize > Revenue to see: Overview Metrics:- Total Revenue: Lifetime earnings from all customers
- Active Connections: Number of customers currently using your service
- This Month’s Revenue: Current billing period earnings
- Average Revenue Per User (ARPU)
- By Connection: See which customers generate the most revenue
- By Product: Compare performance of different pricing tiers
- By Time Period: Daily, weekly, monthly trends
Usage Analytics
Navigate to Monetize > Usage for detailed insights: Metrics Available:- Request Volume: Total API calls per connection
- Token Usage: Input/output token consumption
- Cost Breakdown: Base costs, fees, service charges
- Model Distribution: Which AI models customers use most
- Filter by date range, connection, product, or metadata
- Export to CSV for external analysis
- Create custom views for reporting
Connection Management
Navigate to Monetize > Connections to:- View All Connections: See every customer wallet linked to your merchant account
- Connection Status: “ok” (funded), “limited” (low balance), “disabled” (blocked)
- Balance Information: Current wallet balance per connection
- Usage History: Request logs and costs for each connection
- Reference IDs: Track customers using your internal user IDs
Validation Checklist
Before going to production, verify everything works:- Stripe Connected: Payout account active and verified
- Product Created: Pricing configured and product secret saved
- Checkout Works: Test user can complete phone verification and payment
- Webhook Configured: Endpoint receiving
checkout.completedevents - Forward Tokens Generated: SDK correctly creates tokens from connection secrets
- API Requests Working: Test request with forward token succeeds
- Revenue Tracking: Dashboard shows usage and costs accurately
- Balance Deduction: Wallet balance decreases after requests
Troubleshooting
Stripe Connect onboarding fails
Stripe Connect onboarding fails
Possible causes:
- Incomplete business information
- Bank account verification failed
- Tax ID (EIN/SSN) mismatch
- Check your email for Stripe verification requests
- Complete any pending requirements in the Stripe dashboard
- Verify your bank account details are correct
- Contact Stripe support if issues persist
Checkout component not displaying
Checkout component not displaying
Possible causes:
- Session secret expired (30-minute limit)
- Invalid session secret format
- Missing
@lavapayments/checkoutpackage
- Verify the package is installed:
npm list @lavapayments/checkout - Check that
sessionSecretis valid and not expired - Create a new session if it’s been longer than 30 minutes
- Inspect browser console for errors
- Session secret starts with
cs_prefix - Backend API returns valid JSON with
sessionSecretfield - React component is mounted in a client component (
'use client'directive)
Webhook not receiving events
Webhook not receiving events
Possible causes:Retry logic: Lava automatically retries failed webhooks with exponential backoff (up to 3 attempts). Check the dashboard for retry logs.
- Incorrect webhook URL configuration
- Firewall blocking Lava’s servers
- Webhook secret mismatch in signature verification
- Verify URL is publicly accessible (use webhook.site to test)
- Check webhook logs in Monetize > Webhooks dashboard
- Ensure
LAVA_WEBHOOK_SECRETmatches the secret in dashboard - Test locally using
ngrokor similar tunneling tool
Forward token authentication fails (401)
Forward token authentication fails (401)
Possible causes:Common mistake: Forgetting to include the product secret when you have multiple products configured.
- Incorrectly generated token (wrong format)
- Expired or revoked secret key
- Connection secret invalid or deleted
- Verify token format:
base64(secretKey.connectionSecret.productSecret) - Check that secret key is active in Build > Secrets
- Verify connection exists in Monetize > Connections
- Regenerate token using SDK to ensure correct encoding
Customer balance not updating after payment
Customer balance not updating after payment
Possible causes:
- Stripe payment succeeded but webhook not processed
- Database race condition with concurrent requests
- Balance transfer settlement delay
- Check Stripe dashboard for successful payment
- Verify
checkout.completedwebhook was received and processed - Look for errors in webhook handler logs
- Check balance manually in Monetize > Connections
Product pricing not applying correctly
Product pricing not applying correctly
Possible causes:
- Product secret not included in forward token
- Tiered pricing configuration incorrect
- Billing basis mismatch (input-output vs output-only)
- Verify forward token includes product secret as third component
- Check product configuration in dashboard (Monetize > Products)
- Review request logs for correct usage calculation
- Test with simple fixed fee before adding tiers
- Check dashboard request logs to see calculated cost
- Compare against expected calculation:
tokens × tier_rate - Verify
billingBasismatches your expectations (input+output vs output-only)
output-only but expecting to charge for prompts. Change to input-output to charge for both.What’s Next?
Congratulations! You’ve set up a complete monetization flow. Here are recommended next steps:Pricing Configuration Guide
Learn advanced pricing strategies: A/B testing, enterprise contracts, and custom tiers
Checkout Integration Guide
Advanced checkout customization: branding, metadata, subscription vs topup modes
Financial Model
Understand transfers, settlements, and how money flows through the system
Webhooks Guide
Handle all webhook events: balance updates, connection changes, usage notifications
How Lava Monetize Works
Understanding the monetization flow helps you troubleshoot and optimize:- Customer Checkout: User verifies phone, adds payment, creates wallet
- Connection Created: Wallet is linked to your merchant account
- Forward Token Generated: You create token from connection + product secrets
- API Requests: Customer makes AI requests with forward token
- Usage Metered: Lava tracks tokens, calculates costs based on your product pricing
- Balance Deducted: Customer wallet charged immediately (prepaid model)
- Revenue Tracked: Your merchant earnings accumulate in real-time
- Payouts: Stripe transfers funds to your bank on configured schedule
- Base Cost: AI provider’s charge (e.g., OpenAI)
- Merchant Fee: Your configured markup
- Service Charge: Lava’s 1.9% platform fee
- Transfer created as “under-settled”
- When customer adds funds, oldest transfers settled first
- Merchant earnings only count settled amounts
- Active Balance: Current spendable amount
- Autopay: Auto-top-up when balance falls below threshold
- Connection Status: “ok” (funded), “limited” (low balance), “disabled” (blocked)
Lava adds less than 20ms of latency through edge computing and Redis caching. Streaming responses work seamlessly, with usage tracked after completion.
Support
Need help with monetization setup? We’re here to assist:- Documentation: lavapayments.com/docs
- Support: [email protected]
- Dashboard: Check Monetize > Revenue for detailed analytics
- Community: Join our Discord for peer support and updates