Logo

Legacy Usage Records

warning

Check out the new Stripe integration to implement usage-based billing with Stripe.


This documentation is for legacy Stripe usage-based billing integration that reports usage records to SubscriptionItem(s) directly.

To report usage records to Stripe legacy usage-based billing, use OpenMeter usage sync:

  1. Setup OpenMeter usage sync via webhooks
  2. Report usage to Stripe in your application

1. Setup OpenMeter webhooks

You can set up usage sync on the OpenMeter Cloud UI or via API. For Stripe integration, we recommend reporting daily for the last day usage.

To minimize usage slipping into the next billing period when the plan changes the billing cycle, you can report hourly.

See Webhooks to learn more about how to configure and consume OpenMeter webhooks.

2. Report usage to Stripe

To report usage to Stripe, we will listen to OpenMeter usage sync webhooks and report usage to Stripe. The steps are:

  • 2.1. Find Stripe subscription for subject (customer)
  • 2.2. Find Stripe subscription item for meter
  • 2.3. Report usage to Stripe
// Listening on the webhook endpoint
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  if (req.method !== "POST") {
    res.status(405).json({});
    return;
  }
  const idempotencyKey = req.headers["svix-id"];
  const msg = (await buffer(req)).toString();
 
  // See webhooks docs about how to verify signatures
  if (msg.type === "report.meter") {
    await reportusageToStripe(idempotencyKey, msg);
    return res.status({});
  }
 
  res.status(400).json({ message: "Unknown event type" });
  return;
}
 
function reportusageToStripe(idempotencyKey, msg) {
  const { usage, meter, query } = msg;
 
  // Find stripe subscription ID for subject (customer)
  // usually a databse call in your application
  const stripeSubscriptionId = getSubscriptionIdForSubject(query.subject)
 
  // Find stripe subscription item for meter
  const subscriptionItems = await stripe.subscriptionItems.list({
    subscription: stripeSubscriptionId
  });
 
  for (const { value, windowEnd } in msg.usage) {
    const subscriptionItem = subscriptionItems.find(({ price }) =>
      // retreive stripe price id for meter (usually from config)
      price.id === getPriceIdForMeter(meter.slug)
    )
 
    // Report usage to Stripe
    await stripe.subscriptionItems.createUsageRecord(
      subscriptionItem.id,
      {
        quantity: value,
        timestamp: windowend,
        action: 'set'
      },
      {
        idempotencyKey,
      }
    );
  }
}

To read more about how to implement the legacy Stripe Usage-Based Pricing, check out our blog posts: