Set up usage-based billing with meters, plans, and checkout from code
This guide shows how to create a complete billing flow programmatically: define pricing, create a plan, embed checkout, and route billable traffic per customer.
import { useLavaCheckout } from '@lavapayments/checkout';const { open } = useLavaCheckout({ onSuccess: ({ customerId }) => { // Save customerId — this is the billing relationship with your customer }});// Call with the token from your backendopen(checkoutSessionToken);
The checkout overlay handles phone verification, payment method collection, and subscription creation. When complete, onSuccess fires with the customerId.
Checkout sessions expire after 60 minutes. Create a new session for each checkout attempt.
The checkout_session_token is an opaque token — do not try to construct URLs from it. Always use the SDK to open checkout.
Once a customer has completed checkout, generate forward tokens scoped to their customer ID and meter. Every request made with this token is tracked and billed against their subscription:
// Get the customer (from your database, or list them)const { data: customers } = await lava.customers.list();const customer = customers[0];// Generate a forward token for this customerconst forwardToken = lava.generateForwardToken({ customer_id: customer.customer_id, meter_slug: meter.meter_slug,});// Use it exactly like in the Route Traffic guideconst response = await fetch(lava.providers.openai + '/chat/completions', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${forwardToken}` }, body: JSON.stringify({ model: 'gpt-4o-mini', messages: [{ role: 'user', content: 'Hello!' }] })});