Skip to main content

Problem

You want to show customers their remaining credits, subscription plan, and prompt them to add funds when their balance is low.

Solution

Use connections.getSubscription() to fetch the full credit breakdown, then render it in your UI.
import { Lava } from '@lavapayments/nodejs';

const lava = new Lava();

async function getBalanceDisplay(connectionId: string) {
  const result = await lava.connections.getSubscription(connectionId);

  if (!result.subscription) {
    return { status: 'no_subscription', credits: null, plan: null };
  }

  const { credits, plan, pending_change } = result.subscription;
  const total = parseFloat(credits.total_remaining);
  const LOW_BALANCE_THRESHOLD = 2.0; // $2.00

  return {
    status: total <= 0 ? 'empty' : total < LOW_BALANCE_THRESHOLD ? 'low' : 'ok',
    credits: {
      total: total.toFixed(2),
      fromPlan: parseFloat(credits.cycle_remaining).toFixed(2),
      fromBundles: parseFloat(credits.bundle_remaining).toFixed(2),
    },
    plan: {
      name: plan.name,
      price: `$${plan.period_amount}/${plan.billing_interval}`,
      included: `$${plan.included_credit}`,
      rollover: plan.rollover_type,
    },
    pendingChange: pending_change
      ? {
          type: pending_change.type,
          effectiveAt: pending_change.effective_at,
          newPlan: pending_change.name ?? null,
        }
      : null,
  };
}

API Route

app.get('/api/balance', async (req, res) => {
  const balance = await getBalanceDisplay(req.user.connectionId);

  if (balance.status === 'empty') {
    return res.status(402).json({
      ...balance,
      message: 'No credits remaining. Please add funds to continue.',
    });
  }

  res.json(balance);
});

Pre-Request Check

Gate AI requests on credit availability:
async function ensureCredits(connectionId: string) {
  const conn = await lava.connections.retrieve(connectionId);

  if (!conn.has_lava_credit_balance) {
    throw new Error('No credit balance — prompt user to add funds');
  }

  return conn;
}

Next Steps