> ## Documentation Index
> Fetch the complete documentation index at: https://docs.integrateledger.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Checkout and attach

> Start any plan or sell a credit pack with one call. Free plans start at once, paid ones charge a saved card or open Stripe Checkout, and grants land the moment Stripe confirms payment.

`attach` is the one call that starts a plan or sells a [credit pack](https://docs.integrateledger.com/pricing/credit-packs.md), so your upgrade button is a single line of code. A free plan starts at once. Anything paid goes through Stripe: Checkout for a new card, or an instant charge on the card the customer already saved. Ledger grants a paid purchase the moment Stripe's signed webhook confirms the money arrived, so customers get exactly what they paid for.

```mermaid theme={"system"}
%%{init: {"theme": "base", "themeVariables": {"fontFamily": "IBM Plex Sans, sans-serif", "fontSize": "14px", "primaryColor": "#f7f6f3", "primaryBorderColor": "#c4bfb5", "primaryTextColor": "#1a1816", "lineColor": "#6b655c", "clusterBkg": "#ffffff", "clusterBorder": "#dbd7cf", "edgeLabelBackground": "#ffffff"}}}%%
sequenceDiagram
    participant App as Your backend
    participant L as Ledger
    participant S as Stripe
    actor C as Customer
    App->>L: attach(customerId, planId)
    L->>S: Create Checkout Session
    L-->>App: checkoutUrl (status pending_checkout)
    App->>C: Redirect to checkoutUrl
    C->>S: Pays on Checkout
    S-->>C: Redirect to your success URL
    S->>L: invoice.paid (signed webhook)
    Note over L: Plan active, grants written
    App->>L: getCustomer(customerId)
    L-->>App: currentPlan, features, availableCredits
```

## What attach does

| You attach | The customer has | Result |
| - | - | - |
| A free plan | No plan, or this free plan already | Active at once: `{ "subscriptionId": 41, "status": "active" }` |
| A paid plan | No saved card | Pending: `{ "checkoutUrl": "https://checkout.stripe.com/…", "subscriptionId": 42 }` |
| A paid plan | A saved card in Stripe | Charged at once: `{ "subscriptionId": 42, "status": "active" }`, or `402 payment_failed` if declined |
| A [pay-as-you-go](https://docs.integrateledger.com/pricing/pay-as-you-go.md) plan (\$0 with overage) | Either | As a paid plan. Checkout collects a card for a \$0 subscription; a saved card starts it directly |
| A [lifetime plan](#lifetime-plans) | Either | As a paid plan, but paid once, with no subscription |
| A paid plan with a [trial](https://docs.integrateledger.com/pricing/trials.md) | Either | A card trial as a paid plan, charging \$0 now. A no-card trial starts at once: `{ "subscriptionId": 43, "status": "trialing", "trialEndsAt": "…" }` |
| A credit pack | Either | Always Checkout: `{ "checkoutUrl": "…", "addOnPurchaseId": 7 }` |
| A [recurring add-on](https://docs.integrateledger.com/pricing/add-ons.md), with an `Idempotency-Key` | A paid plan and a saved card | A prorated charge on the plan's bill: `{ "itemChangeId": 31, "status": "applied", "paymentUrl": null, "item": { … } }` |
| A paid plan in [another group](https://docs.integrateledger.com/pricing/plan-groups.md), with an `Idempotency-Key` | A paid plan at the same interval | As an add-on: a prorated charge on the same bill, answered with `itemChangeId` |
| A free plan in another group | A plan in another group | Active at once, on a free bill of its own |
| A plan with `entityId` ([entity plans](https://docs.integrateledger.com/pricing/entity-plans.md)) | A plan, and for a paid entity plan a paid bill at its interval | A paid plan as an add-on, on the customer's bill; a free one applied at once with `itemChangeId: null` |

A *saved card* is the default payment method on the customer's Stripe customer. When Ledger charges it, the response comes after Stripe has confirmed the invoice, so the plan's grants are already there. A declined card leaves nothing behind, so the customer can attach again. A card that needs 3-D Secure gets a `checkoutUrl` for the same subscription, and the customer authenticates on Checkout.

A customer holds one base plan per [group](https://docs.integrateledger.com/pricing/plan-groups.md), and moves between plans in a group without a gap:

* On a **free plan**, attach the paid plan. The free plan keeps working until the paid plan's payment lands, then it ends; free plans in other groups keep running. A failed or abandoned Checkout leaves the free plan as it was.
* On a **paid plan** (anything with a Stripe subscription, pay as you go included), move them with an [upgrade or downgrade](https://docs.integrateledger.com/billing/upgrades-and-downgrades.md).
* On a **lifetime plan**, see [below](#lifetime-plans).
* For **another product line**, attach a plan in its group beside the first. A paid one joins the customer's bill.
* For a **workspace or user** inside the customer, attach with `entityId`. See [Plans per workspace or user](https://docs.integrateledger.com/pricing/entity-plans.md).

## Set where Checkout returns

In **Settings › Checkout**, set a **success URL** and a **cancel URL**: the pages in your app that Stripe sends the customer back to. Until you set them, Sandbox returns the customer to the Ledger dashboard, so you can try Checkout from day one.

To send the customer back to the page they came from, pass `successUrl` (and `cancelUrl`, if it differs) to `attach`. They replace the saved URLs for that Checkout; one sent alone serves for both. Sandbox also takes `http://localhost` while you build. Stripe replaces `{CHECKOUT_SESSION_ID}` in them with the session's ID.

## Attach and redirect

Resolve the `customerId` on your server from the signed-in user, never from a value the browser sends.

```typescript TypeScript theme={"system"}
const result = await billing.attach({
	customerId,
	planId: "pro", // or addOnId: "credits_500"
	successUrl: "https://app.example.com/billing?checkout=success", // optional
});

if ("checkoutUrl" in result) {
	return res.redirect(303, result.checkoutUrl);
}
// status "active": a free plan, or Ledger charged the saved card.
```

```python Python theme={"system"}
result = billing.attach(
    customer_id=customer_id,
    plan_id="pro",  # or add_on_id="credits_500"
    success_url="https://app.example.com/billing?checkout=success",  # optional
)

if "checkoutUrl" in result:
    return redirect(result["checkoutUrl"], code=303)
# status "active": a free plan, or Ledger charged the saved card.
```

```bash cURL theme={"system"}
curl https://api.integrateledger.com/v1/billing/attach \
  -H "Authorization: Bearer $LEDGER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"customerId": "user_123", "planId": "pro", "successUrl": "https://app.example.com/billing?checkout=success"}'
```

```json Response theme={"system"}
{
  "checkoutUrl": "https://checkout.stripe.com/c/pay/cs_test_a1B2c3",
  "subscriptionId": 42
}
```

Calling `attach` again for the same plan or pack while its Checkout is open returns the same `checkoutUrl`, so a double click is safe. Attaching a different pack expires the unpaid pack Checkout and opens a new one, so the customer always pays for the pack they chose last. Stripe expires an unpaid Checkout after 24 hours; the next attach opens a new one.

## Attach with a promotion code

Send one of your [promotion codes](https://docs.integrateledger.com/billing/discounts.md) as `promotionCode`: Checkout opens with the discount on, or a saved card is charged the discounted price. To let the customer type a code in Checkout instead, send `allowPromotionCodes: true`.

```typescript TypeScript theme={"system"}
const result = await billing.attach({
	customerId,
	planId: "pro",
	promotionCode: "LAUNCH20",
});
```

```python Python theme={"system"}
result = billing.attach(
    customer_id=customer_id,
    plan_id="pro",
    promotion_code="LAUNCH20",
)
```

```bash cURL theme={"system"}
curl https://api.integrateledger.com/v1/billing/attach \
  -H "Authorization: Bearer $LEDGER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"customerId": "user_123", "planId": "pro", "promotionCode": "LAUNCH20"}'
```

The plan still grants its full credits and allowances, and an abandoned Checkout gives the code's use back.

## Attach a specific version

Attach starts the plan's active [version](https://docs.integrateledger.com/billing/plan-versions.md). Pass `planVersion`, a number or a label, to start another one: a legacy version for a customer promised an older price, in Sandbox and Live, or the plan's draft in Sandbox, to try it before you promote it.

```typescript TypeScript theme={"system"}
const result = await billing.attach({
	customerId,
	planId: "pro",
	planVersion: 1, // or a label: "2026-q4"
});
```

```python Python theme={"system"}
result = billing.attach(
    customer_id=customer_id,
    plan_id="pro",
    plan_version=1,  # or a label: "2026-q4"
)
```

```bash cURL theme={"system"}
curl https://api.integrateledger.com/v1/billing/attach \
  -H "Authorization: Bearer $LEDGER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"customerId": "user_123", "planId": "pro", "planVersion": 1}'
```

The customer pays that version's Stripe Price and gets its grants, at every renewal.

## When grants land

| Purchase | Granted when |
| - | - |
| Free plan | At once, in the attach response. |
| Paid plan through Checkout | Stripe's signed `invoice.paid` webhook for the first invoice. |
| Paid plan on a saved card | Before the attach response returns. |
| Lifetime plan | Stripe's signed `checkout.session.completed` (Checkout) or `invoice.paid` (saved card). |
| Credit pack | Stripe's signed `checkout.session.completed`. Stripe also sends an invoice for the pack, such as "Top-up – 500 credits"; it never grants the credits a second time. |
| A renewal | When Stripe creates the renewal invoice. See [Renewals and lifecycle](https://docs.integrateledger.com/billing/renewals-and-lifecycle.md#renewals). |

A plan's grants are its credits, its metered allowances for the period, and its held limits and boolean features, which apply from the same moment. Ledger checks the plan's line on the invoice at your full price before tax and discounts, so [tax](https://docs.integrateledger.com/billing/tax.md) and [coupons](https://docs.integrateledger.com/billing/renewals-and-lifecycle.md#coupons) never shrink a grant.

The redirect to your success URL happens at about the same time as the webhook, but it proves nothing: anyone can open that URL. When the customer lands there, read them again from your backend:

* While [`listCustomerSubscriptions`](https://docs.integrateledger.com/api-reference/customers/subscriptions) has an item with `status: "pending_checkout"`, show "Confirming your payment" and reload in a moment. The grants arrive with the payment.
* Read the subscriptions list, which shows every pending plan. For a customer's first plan, `currentPlan.status` is `pending_checkout` while Checkout is open. A customer moving up from a free plan keeps the free plan as `currentPlan` until the payment lands, and the pending plan appears in the subscriptions list.

## Per-seat plans

A plan with a [seat price](https://docs.integrateledger.com/pricing/per-seat.md) starts at the seats the customer already holds. Attach reads the customer's held count and puts it on the first Checkout or invoice beside the plan's own price.

> **Team:** $49 a month with 3 seats included, then $10 a seat.

A team on your Free plan, which counts seats without pricing them, holds 12 seats and attaches Team:

```typescript TypeScript theme={"system"}
const result = await billing.attach({ customerId: team.id, planId: "team" });
```

```python Python theme={"system"}
result = billing.attach(customer_id=team.id, plan_id="team")
```

```bash cURL theme={"system"}
curl https://api.integrateledger.com/v1/billing/attach \
  -H "Authorization: Bearer $LEDGER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"customerId": "team_42", "planId": "team"}'
```

The first Checkout, or the invoice on a saved card, charges:

| Line | Quantity | Amount |
| - | - | - |
| Team | 1 | \$49.00 |
| Seats, included | 3 | \$0.00 |
| Seats | 9 | \$90.00 |
| **Total** | | **\$139.00** |

The 12 seats stay held through the move, so every member keeps working. Later adds and removes are prorated from the moment they're tracked. A customer who holds no seats at attach pays the plan's price alone, and their first seat is added to the subscription when it's tracked.

## Lifetime plans

A [lifetime plan](https://docs.integrateledger.com/pricing/lifetime.md) is paid once. Attach it like any paid plan: with a saved card, Ledger charges it at once on one invoice and returns `{ "status": "active" }`; without one, Checkout takes a single payment at the plan's one-time Stripe Price. Either way the customer gets a paid invoice, and nothing renews.

If the saved card is declined, attach answers `402 payment_failed` and Ledger voids the invoice it tried to charge, so nothing is left open to pay later. If the card needs 3-D Secure, Ledger voids that invoice and returns a Checkout URL instead, where the customer authenticates while paying. Attaching again after the customer fixes the card charges one new invoice.

A lifetime plan is the customer's plan for good:

* To sell more credits on top of it, sell a [credit pack](https://docs.integrateledger.com/pricing/credit-packs.md).
* To move the customer onto a recurring plan, attach it with `replaceLifetime: true`. The lifetime plan keeps working until the new plan is paid for, then ends with its remaining credits, with no refund.

```typescript TypeScript theme={"system"}
const result = await billing.attach({
	customerId,
	planId: "pro",
	replaceLifetime: true,
});
```

```python Python theme={"system"}
result = billing.attach(
    customer_id=customer_id,
    plan_id="pro",
    replace_lifetime=True,
)
```

```bash cURL theme={"system"}
curl https://api.integrateledger.com/v1/billing/attach \
  -H "Authorization: Bearer $LEDGER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"customerId": "user_123", "planId": "pro", "replaceLifetime": true}'
```

## Test it

In Sandbox, pay with [Stripe test cards](https://docs.stripe.com/testing), any future expiry and any CVC:

| Card | Result |
| - | - |
| `4242 4242 4242 4242` | Succeeds. |
| `4000 0025 0000 3155` | Asks for authentication, then succeeds. |
| `4000 0000 0000 9995` | Declined. The plan stays `pending_checkout`. |

To see renewals without waiting a month, [simulate time](https://docs.integrateledger.com/test/simulate-time.md).

## Errors from attach

| Status | `error` | What to do |
| - | - | - |
| `402` | `payment_failed` | The saved card was declined. Nothing was created; the customer can attach again. |
| `409` | `subscription_exists` | The customer (or entity) already has a paid plan in this plan's group, or a pending Checkout for another plan. [Upgrade or downgrade](https://docs.integrateledger.com/billing/upgrades-and-downgrades.md) instead, or let the Checkout finish or expire. |
| `409` | `plan_interval_differs` | A paid plan in another group, while the customer's paid bill is at another interval. Attach a plan at the bill's interval. |
| `409` | `entity_plan_needs_paid_bill`, `entity_plan_needs_bill` | An entity plan before the customer has a bill for it to ride on. Attach the customer's own plan first. |
| `409` | `entity_plan_shares_base_price` | An entity plan on the customer's own plan's Stripe Price. Give entities a plan of their own. |
| `400` | `entity_plan_must_recur` | A lifetime plan attached to an entity. Attach a monthly or yearly plan. |
| `404` | `entity_not_found` | No entity with this `entityId`. Create it first. |
| `409` | `lifetime_plan_active` | The customer holds a lifetime plan. Attach a recurring plan with `replaceLifetime: true`. |
| `409` | `plan_already_attached` | The customer already bought this lifetime plan. |
| `409` | `purchase_pending` | A different pack's Checkout is being paid. Try again once it completes. |
| `409` | `stripe_customer_balance` | The customer has a balance in Stripe that would pay part of the first invoice. Clear it in Stripe, then attach again. |
| `409` | `plan_not_free` | The plan became paid while a free-plan attach ran. Attach again. |
| `409` | `checkout_unavailable` | The saved Checkout can't be reopened. Attach again later. |
| `400` | `checkout_urls_not_configured` | Send `successUrl` with the attach, or set the URLs in **Settings › Checkout**. |
| `400` | `invalid_request` | A field is wrong; `issues` names it. A `successUrl` or `cancelUrl` must be `https` (Live also refuses `localhost`). |
| `404` | `customer_not_found`, `plan_not_found`, `add_on_not_found` | It doesn't exist in this key's environment, or the plan or pack is archived. |
| `404` | `plan_version_not_found` | The plan has no version with this `planVersion`. |
| `409` | `draft_sandbox_only` | `planVersion` named the draft, which attaches in Sandbox only. Promote it first. |
| `404`, `409`, `422` | `promotion_code_*`, `reward_not_synced` | The `promotionCode` can't be used for this customer or plan. See [Discounts and promotion codes](https://docs.integrateledger.com/billing/discounts.md#errors). |
| `502` | `stripe_webhook_unhealthy`, `stripe_checkout_failed`, `stripe_not_configured` | Check **Settings › Stripe**, then retry the same attach; it can't open a second Checkout. |
| `503` | `live_charges_disabled` | Live isn't activated, or was turned off. See the [Production checklist](https://docs.integrateledger.com/integrate/production-checklist.md). |

## When something goes wrong

| Symptom | Cause | What to do |
| - | - | - |
| Status stays `pending_checkout` after paying | The webhook hasn't reached Ledger | Check **Settings › Stripe** shows the webhook as **Receiving**. Ledger waits for the signed event. |
| `502 stripe_webhook_unhealthy` | The endpoint is missing, disabled or misconfigured in Stripe | Choose **Check again** in **Settings › Stripe**, or reconnect Stripe. |
| The customer paid but got nothing | Ledger refused the invoice, for example because part of it was paid from a Stripe customer balance | Grant it with a [balance adjustment](https://docs.integrateledger.com/customers/balance-adjustments.md) that names the invoice, or refund it in Stripe. |

[Errors](https://docs.integrateledger.com/errors.md) lists every code.

## Rules

* A customer on a paid plan changes plan within its group with an upgrade or downgrade; attach answers `409 subscription_exists`.
* A paid plan in another group, and a paid entity plan, join the customer's bill of the same interval and need an `Idempotency-Key` (`409 plan_interval_differs`, `409 entity_plan_needs_paid_bill`).
* A lifetime plan is bought once (`409 plan_already_attached`), and only a recurring plan with `replaceLifetime: true` replaces it (`409 lifetime_plan_active`).
* Success and cancel URLs are public `https` URLs, in Sandbox too; Sandbox also takes `http://localhost` on an attach.
* Live needs saved success and cancel URLs, or a `successUrl` on every attach (`400 checkout_urls_not_configured`).
* A customer has one open pack Checkout at a time.
* Send `promotionCode` or `allowPromotionCodes`, not both.
* A `promotionCode` covers the plan it's attached with (`422 promotion_code_not_for_plan`).
* A draft attaches in Sandbox; promote it to sell it in Live (`409 draft_sandbox_only`).

> [!NOTE]
>
> **Other ways.** Without an SDK, use [`POST /v1/billing/attach`](https://docs.integrateledger.com/api-reference/billing/attach). [Build a billing page](https://docs.integrateledger.com/customers/billing-page.md) puts attach behind your plan and pack buttons.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.