# Use Limitry with Stripe

> Let a customer's Stripe plan set their limits, sell credits with Stripe Checkout, and bill usage through Stripe meters.

Stripe takes the payments and Limitry does the counting. This guide covers the three ways the two meet:

1. A customer’s plan decides their limits.
2. Customers buy credits with Stripe Checkout, and a refund takes them back.
3. You bill for usage, and Stripe’s meters get each unit exactly once.

The examples use Node with the `stripe` package and the [Limitry SDK](/docs/typescript/), and a team as the subject. Your webhook handler checks Stripe’s signature first, as Stripe’s docs describe.

## Before you start: the webhook endpoint

In Stripe, open **Workbench → Webhooks** and click **Create an event destination**. Choose the **Snapshot** payload, because these handlers read the event’s `data.object`. Then add your endpoint’s URL, and copy its signing secret for the handler.

## Before you start: two things every handler does

**Pick the environment from the event.** Stripe’s test mode and live mode match Limitry’s test and live. Keep a Limitry key for each, and choose by the event’s `livemode`:

* TypeScript

  ```ts
  import { createClient } from "@limitry/sdk";

  const limitry = {
    live: createClient({ apiKey: process.env.LIMITRY_LIVE_KEY! }),
    test: createClient({ apiKey: process.env.LIMITRY_TEST_KEY! }),
  };
  const apiFor = (event: Stripe.Event) =>
    event.livemode ? limitry.live : limitry.test;
  ```

* Python

  ```python
  import os

  import stripe
  from limitry import Limitry

  limitry = {
      "live": Limitry(api_key=os.environ["LIMITRY_LIVE_KEY"]),
      "test": Limitry(api_key=os.environ["LIMITRY_TEST_KEY"]),
  }

  def api_for(event) -> Limitry:
      return limitry["live"] if event.livemode else limitry["test"]
  ```

**Expect the same event twice, and events out of order.** Stripe redelivers events for up to three days and doesn’t promise their order. Each section below says how its handler stays correct either way.

## 1. The plan decides the limits

To give a bigger plan more, give each plan its own subject kind, such as `team-free` and `team-pro`, with its own limits. To give one team more than its plan allows, add a limit for that team alone. It replaces the plan’s limit that has the same action and window.

Then store each team’s plan, and send that kind in every check.

* TypeScript

  ```ts
  await limitry.live.guard(
    {
      subject: { kind: `team-${team.plan}`, id: team.id },
      action: "report",
    },
    () => buildReport(params),
  );
  ```

* Python

  ```python
  with limitry["live"].guard(
      subject={"kind": f"team-{team.plan}", "id": team.id}, action="report"
  ):
      report = build_report(params)
  ```

Keep the plan up to date from the subscription events. Don’t trust the order they arrive in: fetch the subscription again and store what it says now. A late or repeated event then does no harm.

* TypeScript

  ```ts
  const PLAN_BY_PRICE: Record<string, string> = {
    pro_monthly: "pro",
    pro_annual: "pro",
  };

  async function onSubscriptionEvent(event: Stripe.Event) {
    const { id } = event.data.object as Stripe.Subscription;
    const subscription = await stripe.subscriptions.retrieve(id);
    const team = await teams.byStripeCustomer(subscription.customer as string);

    const paying = ["active", "trialing", "past_due"].includes(
      subscription.status,
    );
    const lookupKey = subscription.items.data[0]?.price.lookup_key ?? "";
    await teams.setPlan(
      team.id,
      paying ? (PLAN_BY_PRICE[lookupKey] ?? "free") : "free",
    );
  }
  // customer.subscription.created, .updated and .deleted
  ```

* Python

  ```python
  PLAN_BY_PRICE = {"pro_monthly": "pro", "pro_annual": "pro"}

  def on_subscription_event(event) -> None:
      subscription = stripe.Subscription.retrieve(event.data.object.id)
      team = teams.by_stripe_customer(subscription.customer)

      paying = subscription.status in ("active", "trialing", "past_due")
      lookup_key = subscription["items"].data[0].price.lookup_key or ""
      teams.set_plan(team.id, PLAN_BY_PRICE.get(lookup_key, "free") if paying else "free")

  # customer.subscription.created, .updated and .deleted
  ```

What this does in each case:

* **Upgrade or downgrade:** the next check uses the new plan’s limits.
* **Trial:** a `trialing` subscription counts as the plan.
* **Failed payment:** Stripe retries while the subscription is `past_due`, and the team keeps its plan. To cut them off sooner, leave `past_due` out of the list.
* **Cancellation:** a `canceled` or `unpaid` subscription drops the team to `free`.

Each plan’s kind keeps its own count. A team that upgrades mid-month starts the Pro window at zero. A team that moves back to Free finds its Free count where it left it.

### Reset on the billing date

Stripe bills from the day a subscription starts, not on the 1st. To reset a team’s allowance on its billing day, give the plan’s limits `start: "billing_date"` (see [When limits reset](/docs/resets/)), and set the team’s billing date from the subscription in the same handler:

* TypeScript

  ```ts
  async function setBillingDate(
    event: Stripe.Event,
    subscription: Stripe.Subscription,
    team: { id: string; plan: string },
  ) {
    // Stripe's billing_cycle_anchor is in seconds.
    await apiFor(event).subjects.update(`team-${team.plan}`, team.id, {
      billingAnchorAt: new Date(
        subscription.billing_cycle_anchor * 1000,
      ).toISOString(),
    });
  }
  ```

* Python

  ```python
  from datetime import datetime, timezone

  def set_billing_date(event, subscription, team) -> None:
      # Stripe's billing_cycle_anchor is in seconds.
      anchor = datetime.fromtimestamp(subscription.billing_cycle_anchor, tz=timezone.utc)
      api_for(event).subjects.update(
          f"team-{team.plan}", team.id, billing_anchor_at=anchor.isoformat()
      )
  ```

An annual plan’s monthly allowance then resets on the same day every month, and a new subscription starts a new period. Without a billing date, a team’s first check sets it.

To match a Stripe customer to a team, store the customer id on the team when you create the customer. Put the team’s id in the customer’s `metadata` too, so you can find it from either side.

Stripe’s own Entitlements say which features a plan includes. Limitry says how much of them a team can use. You can use both: decide the subject kind from the team’s entitlements instead of the price.

## 2. Credits from Stripe Checkout

Make a balance, a limit with the window `total`, as in [Sell prepaid credits](/docs/guides/prepaid-credits/). When you create the Checkout Session, record what it sells:

* TypeScript

  ```ts
  const session = await stripe.checkout.sessions.create({
    mode: "payment",
    line_items: [{ price: "price_credits_5000", quantity: 1 }],
    client_reference_id: team.id,
    metadata: { credits: "5000" },
    success_url: "https://example.com/billing?paid=1",
  });
  ```

* Python

  ```python
  session = stripe.checkout.Session.create(
      mode="payment",
      line_items=[{"price": "price_credits_5000", "quantity": 1}],
      client_reference_id=team.id,
      metadata={"credits": "5000"},
      success_url="https://example.com/billing?paid=1",
  )
  ```

When the payment succeeds, add the credits. The session’s id is the idempotency key, so a repeated event adds nothing:

* TypeScript

  ```ts
  async function onCheckoutPaid(event: Stripe.Event) {
    const session = event.data.object as Stripe.Checkout.Session;
    if (session.payment_status !== "paid") return; // a delayed method: wait
    const credits = Number(session.metadata?.credits);

    await purchases.record({
      paymentIntent: session.payment_intent as string,
      teamId: session.client_reference_id!,
      credits,
      amountPaid: session.amount_total!,
    });
    await apiFor(event).limits.credits.create(
      BALANCE_ID,
      {
        subject: { kind: "team", id: session.client_reference_id! },
        amount: credits,
        note: `Checkout ${session.id}`,
      },
      { idempotencyKey: session.id },
    );
  }
  // checkout.session.completed, and checkout.session.async_payment_succeeded
  // for payment methods that settle later
  ```

* Python

  ```python
  def on_checkout_paid(event) -> None:
      session = event.data.object
      if session.payment_status != "paid":
          return  # a delayed method: wait
      credits = int(session.metadata["credits"])

      purchases.record(
          payment_intent=session.payment_intent,
          team_id=session.client_reference_id,
          credits=credits,
          amount_paid=session.amount_total,
      )
      api_for(event).limits.credits.create(
          BALANCE_ID,
          subject={"kind": "team", "id": session.client_reference_id},
          amount=credits,
          note=f"Checkout {session.id}",
          idempotency_key=session.id,
      )

  # checkout.session.completed, and checkout.session.async_payment_succeeded
  # for payment methods that settle later
  ```

### A refund takes credits back

A negative amount takes credits back. For a partial refund, take back the same share of the credits:

* TypeScript

  ```ts
  async function onRefund(event: Stripe.Event) {
    const refund = event.data.object as Stripe.Refund;
    const purchase = await purchases.byPaymentIntent(
      refund.payment_intent as string,
    );
    const credits = Math.round(
      (purchase.credits * refund.amount) / purchase.amountPaid,
    );

    await apiFor(event).limits.credits.create(
      BALANCE_ID,
      {
        subject: { kind: "team", id: purchase.teamId },
        amount: -credits,
        note: `Refund ${refund.id}`,
      },
      { idempotencyKey: refund.id },
    );
  }
  // refund.created
  ```

* Python

  ```python
  def on_refund(event) -> None:
      refund = event.data.object
      purchase = purchases.by_payment_intent(refund.payment_intent)
      credits = round(purchase.credits * refund.amount / purchase.amount_paid)

      api_for(event).limits.credits.create(
          BALANCE_ID,
          subject={"kind": "team", "id": purchase.team_id},
          amount=-credits,
          note=f"Refund {refund.id}",
          idempotency_key=refund.id,
      )

  # refund.created
  ```

A chargeback works the same way: on `charge.dispute.created`, take back the credits for `dispute.amount`, with the dispute’s id as the key. If you win the dispute (`charge.dispute.closed` with the status `won`), add them again with a new key.

If the team already spent the credits, the balance goes below zero. Their checks are then refused until they buy more.

### Repeats after a day

Limitry never forgets a credit’s idempotency key. A checkout or refund event that Stripe redelivers days later adds or takes back nothing. Other writes keep their key for 24 hours, but Stripe can redeliver an event for up to three days. Record the session, refund or dispute ids you’ve handled in your database, and skip an event whose id you’ve seen.

## 3. Bill usage through Stripe meters

When you charge per unit, Limitry has already counted every unit at the check. Send that count to a Stripe meter instead of counting a second time in your own code.

Once an hour, for each team, read the hours that have finished, and send each one as a meter event:

* TypeScript

  ```ts
  const HOUR = 3_600_000;

  async function sendUsage(team: Team) {
    // Hours are final about a minute after they end; wait five.
    const until = Math.floor((Date.now() - 5 * 60_000) / HOUR) * HOUR;
    const from = team.usageSentUntil; // where the last run stopped
    if (from >= until) return;

    const series = await limitry.live.usage.query({
      limitId: METERED_LIMIT_ID,
      subject: `team:${team.id}`,
      granularity: "hour",
      from: new Date(from).toISOString(),
      to: new Date(until - 1).toISOString(),
    });
    let carry = team.usageCarry; // units given back in an earlier hour
    for (const point of series.points) {
      const value = point.used + carry;
      carry = Math.min(0, value);
      if (value <= 0) continue;
      await stripe.billing.meterEvents.create({
        event_name: "reports",
        payload: {
          stripe_customer_id: team.stripeCustomerId,
          value: String(value),
        },
        identifier: `${team.id}:${point.start}`,
        timestamp: Math.floor(Date.parse(point.start) / 1000),
      });
    }
    await teams.saveUsageCursor(team.id, { sentUntil: until, carry });
  }
  ```

* Python

  ```python
  import time
  from datetime import datetime, timezone

  HOUR = 3600

  def iso(seconds: float) -> str:
      return datetime.fromtimestamp(seconds, tz=timezone.utc).isoformat()

  def send_usage(team) -> None:
      # Hours are final about a minute after they end; wait five.
      until = int((time.time() - 5 * 60) // HOUR * HOUR)
      start = team.usage_sent_until  # where the last run stopped
      if start >= until:
          return

      series = limitry["live"].usage.query(
          limit_id=METERED_LIMIT_ID,
          subject=f"team:{team.id}",
          granularity="hour",
          from_=iso(start),
          to=iso(until - 1),
      )
      carry = team.usage_carry  # units given back in an earlier hour
      for point in series.points:
          value = point.used + carry
          carry = min(0, value)
          if value <= 0:
              continue
          stripe.billing.MeterEvent.create(
              event_name="reports",
              payload={"stripe_customer_id": team.stripe_customer_id, "value": str(value)},
              identifier=f"{team.id}:{point.start}",
              timestamp=int(datetime.fromisoformat(point.start.replace("Z", "+00:00")).timestamp()),
          )
      teams.save_usage_cursor(team.id, sent_until=until, carry=carry)
  ```

Why this counts each unit once:

* **Each hour goes once.** The job stores where it stopped and starts there next time. If it fails part way, the next run sends those hours again, and Stripe drops a repeated `identifier`.
* **A finished hour doesn’t change.** Limitry records a reservation’s final cost in the hour it settles, never in an earlier hour.
* **Given-back units aren’t lost.** `used` is net: an hour in which reservations released more than they took can come out below zero. The job carries that into the next hour it sends, because a meter event can’t be negative.

Send from the live key only, so test checks never reach a live invoice. To try the job in Stripe’s test mode, run it once with your test key against a test customer.

Related: [Sell prepaid credits](/docs/guides/prepaid-credits/), [Test and live](/docs/test-and-live/), [Idempotency](/docs/idempotency/), [Usage and reports](/docs/usage/).
