---
title: "Open checkout and the portal"
description: "Start the provider's hosted checkout for a plan or a pack, send a billing manager to the customer portal, and choose on the server what a checkout may sell, with which trial and discount."
canonical_url: "https://nuxt-backend.dev/docs/build/billing/subscriptions/checkout"
---
# Open checkout and the portal

> Start the provider's hosted checkout for a plan or a pack, send a billing manager to the customer portal, and choose on the server what a checkout may sell, with which trial and discount.

Version: nuxt-backend 0.6.x · Tab: Build · Kind: how-to · Status: stable

Every page: [llms.txt](https://nuxt-backend.dev/llms.txt) · Skill for coding agents: [nuxt-backend](https://nuxt-backend.dev/.well-known/skills/nuxt-backend/SKILL.md)

Commands use npm; use your project's package manager.

- [Try it live in the playground](https://nuxt-backend.dev/playground/pricing)
- [API reference](https://nuxt-backend.dev/docs/reference/api/use-billing)
- [Source](https://github.com/qruto/nuxt-backend/blob/main/src/runtime/vue/composables/use-billing.ts)

You take the first payment through Polar's hosted checkout, and send billing managers to its customer portal for the payment method and invoices.

- **Polar does natively:** the checkout page, card and wallet payments, tax, discount codes, trials, currency detection from the customer's IP, and the customer portal (checked on 2026-10-25).
- **The package adds:** `useBilling()` to open both, and a server that decides everything the browser must not: which products may be sold, where the buyer returns, which trial and discount apply.

The entity a checkout pays for resolves on the server, the active workspace by default. Only the workspace's owner and admins check out or open the portal, never an administrator impersonating them: `canManage` says whether the caller may ([Who may buy for a workspace](https://nuxt-backend.dev/docs/build/billing/setup#who-may-buy-for-a-workspace)). Changing, cancelling or pausing a running plan is on [Manage subscriptions](https://nuxt-backend.dev/docs/build/billing/subscriptions).

```vue [app/pages/upgrade.vue]
<script setup lang="ts">
const { products, checkout, portal, canManage } = useBilling()

// Opens the checkout in a new tab, or in this one with `redirect: true`
const subscribe = () => checkout(products.value!.pro!.id)

// The customer portal: payment methods, invoices, the subscription
const manage = () => portal({ returnUrl: window.location.href })
</script>

<template>
  <div v-if="canManage">
    <button type="button" @click="subscribe">Upgrade to Pro</button>
    <button type="button" @click="manage">Manage billing</button>
  </div>
</template>
```

A credit pack's checkout is the same call, or `useCredits().topUp()` ([Sell credits and top-ups](https://nuxt-backend.dev/docs/build/billing/credits)). Both actions reject with the refusal on failure, as [Composable conventions](https://nuxt-backend.dev/docs/reference/nuxt/conventions) describe: `isPending` is `true` while one runs, and `error` keeps the failure until the next one starts.

## Checkout options

`checkout(productIds, options)` accepts these options:

- **Which subscription and how to pay**: `subscriptionId`, `currency` (one the catalog prices the product in, as `usePricing().currencies` lists them), `locale`.
- **Where to return**: `successUrl` (the current URL by default) and `redirect`.
- **The checkout form**: `prefill`, `customFields`, `requireBillingAddress` and `allowDiscountCodes`.
- **Your own data**: `metadata`.
- **Offers**: a campaign's `discountCode` and `utm`, or a public [promotion](https://nuxt-backend.dev/docs/build/growth/offers) of the catalog by its key, `discount`.
- **The soft opt-in**: `emailOptOut`, where your page shows the soft opt-in's "Don't email me" box: `true` when it was ticked, `false` when it was left. `useBilling().softOptIn` says whether a topic of `setupEmail` takes the soft opt-in, and so whether to show the box. Omit it where no box shows: the paid order then joins no topic ([The soft opt-in at checkout](https://nuxt-backend.dev/docs/build/email/preferences#the-soft-opt-in-at-checkout)).

## Back from checkout

The server sends every plan and pack checkout back with its id. `generateCheckoutLink` and `billing.checkout` append `checkout_return` with the provider's `{CHECKOUT_ID}` placeholder to the `successUrl`, before any `#fragment`, so `/settings#plan` comes back as `/settings?checkout_return=…#plan`. Every caller gets it: `<BillingCheckoutLink>`, `<PricingTable>`, `useBilling().checkout` and `useCredits().topUp`. So does a gift's claim that finishes on the provider's checkout, since it grants the recipient credits, and a gift's purchase, which the return settles where no webhook arrives.

The parameter is the package's own. A `successUrl` that already carries your own `checkout_id={CHECKOUT_ID}`, the name the provider suggests, keeps it: the provider fills in both, and the module touches only `checkout_return`. A `successUrl` that already carries `checkout_return` is left as it is.

On the page the customer lands on, the module's client plugin takes `checkout_return` off the address at once, together with the `customer_session_token` the provider appends beside it, and refreshes the entitlements from the provider once (`syncEntitlements`). That token is a key to the customer's billing portal, so it has no place in an address that gets bookmarked, shared or logged; a checkout of your own, without `checkout_return`, keeps it. The new plan reads back before its webhooks arrive, which matters on a local deployment the provider's webhooks can't reach. The refresh carries the checkout's id: a gift bought in that checkout is read from the provider and settled first, paid and delivered as its `order.paid` would, so a gift bought on a local deployment reaches its recipient too. The webhook and the return settle it once between them, whichever comes first. While the refresh runs, `useBilling().isFinishingCheckout` is `true`, and the billing section of `<WorkspaceSettings>` and `<PricingTable>` say "Finishing your purchase…" (the `finishingPurchase` label) and are `aria-busy`. A page of your own can show the same:

```vue [app/pages/welcome.vue]
<script setup lang="ts">
const { isFinishingCheckout, plan } = useBilling()
</script>

<template>
  <p v-if="isFinishingCheckout" role="status">Finishing your purchase…</p>
  <p v-else-if="plan">You are on {{ plan }}.</p>
</template>
```

A return refreshes once per checkout, and only for a signed-in person. A refresh that fails changes nothing, since the `subscription.*` and `order.paid` webhooks refresh the cache all the same. Call `syncEntitlements` (`useCredits().refresh()`) yourself to pull at any other moment.

## What the server decides

The browser picks which of your products to buy, and the server checks the rest before the provider hears of it. A refusal is `invalid_input` naming the field it refuses, except where a rule below says otherwise (see [Errors](https://nuxt-backend.dev/docs/reference/backend/errors)):

- **Products.** `productIds` must be products of your catalog: the plans and packs `billing sync` wrote into `billing.generated.ts`, or `setupBilling({ products })`. A plan change (`changePlan`) is held to the same list, and must switch to a recurring plan, never a credit pack. An app with no catalog yet sells nothing: that is `not_ready` with reason `no_catalog`, and `npx nuxt-backend billing sync` fixes it.
- **Where the buyer lands.** `successUrl`, the embedding page's `origin` and the portal's `returnUrl` must be on `SITE_URL`'s origin. List any other origin the app is served from in `setupBilling({ trustedOrigins })`, each with its scheme (`https://app.example.com`). An entry without a scheme trusts nothing, and the deployment log says so. On a deployment whose `BACKEND_ENVIRONMENT` is `development`, a local origin passes too: `http` or `https` on `localhost`, `127.0.0.1` or `[::1]` on any port, or any `.localhost` name over `https` (`https://app.localhost`, what a local HTTPS proxy serves). The list is billing's own, not auth's `trustedOrigins`: those can be a function of the request, and a checkout has no request to ask.
- **Metadata.** Your own keys pass, up to 20 of them, with string values. The keys the package writes and reads back are refused in any letter case: `userId` (the billing entity a webhook resolves), `giftId` and `phase` (the gift a paid order buys or claims), the keys earlier releases wrote (`gift`, `recipientEmail`, `purchaserUserId`, `giftRecipient`), `openedBy` and `emailOptOut` (who opened the checkout, and the soft opt-in's box), `referralId` (a referral reward's own checkout, which the referral program does not count), and the `utm_` prefix.
- **The discount.** One per checkout: a code the customer types, a campaign's `discountCode`, or a public [promotion](https://nuxt-backend.dev/docs/build/growth/offers) by its key (`discount`), for a product it applies to. A promotion only the server applies, or a discount by id, is refused from a client. So is a promotion the provider no longer redeems (`invalid_input`, `discount`). With none named, `setupBilling({ checkoutDiscount })` may pick one for a plan.
- **The trial.** A plan's trial is its own, set by the catalog's `trial`. A client that sends `trialInterval` or `trialIntervalCount` is refused. One trial runs per owner: when the workspace's owner already had one on any workspace they own, the checkout starts without a trial (see [One customer per billing entity](https://nuxt-backend.dev/docs/build/billing/setup#one-customer-per-billing-entity)).
- **The customer.** The checkout belongs to the billing entity's own customer, by its id, and is never matched by email. The package creates that customer as the entity is made when the catalog has a free plan (its start subscribes the customer), else on the first checkout.
- **The free plan is upgraded in place.** A plan's checkout for an entity on the [free plan](https://nuxt-backend.dev/docs/build/billing/catalog#the-free-plan) names its free subscription, so the provider moves that subscription to the plan, with the plan's trial still offered. The free plan itself is never checked out: its product is refused as `invalid_input` with reason `free_plan`.
- **A currency the catalog prices.** `currency` picks the provider's native price in it. A currency the catalog prices none of the checkout's products in is refused as `invalid_input` (`currency`).
- **One plan.** A checkout for a plan with no `subscriptionId` is refused as `forbidden` (reason `already_subscribed`) while the entity holds a subscription other than the free plan: active, trialing, past due or paused. The free plan is then not upgraded either, so a free plan that started late never lets a second paid plan in: switch plans with `changePlan` instead. Packs stay on sale, and `setupBilling({ multipleSubscriptions: true })` lifts the rule. `<PricingTable>` offers no first subscription or trial while it cannot tell whether the entity has one.
- **A subscription to upgrade.** `subscriptionId` must be one of the billing entity's own: a client may name only its own, and the server names the free subscription itself when the client names none. Any other is `forbidden` with reason `not_owner`, as for every subscription action.
- **Billing is launched.** On a production deployment with no `BILLING_ACCESS_TOKEN` or no production catalog, every checkout, plan switch and gift purchase is refused as `unavailable` (reason `not_launched`), and the pricing page reads "Plans open soon" ([Before billing launches](https://nuxt-backend.dev/docs/build/billing/setup#before-billing-launches)).
- **Purchases are open.** While an administrator has the [`pause_checkout`](https://nuxt-backend.dev/docs/ship/operate/flags#kill-switches) kill switch on, every checkout, plan switch and gift purchase is refused as `unavailable` (reason `checkout_paused`). The refusal comes after the caller is checked and before the provider is asked. Running plans, cancellations, the portal and gift claims keep working.

### Local prices and consent proof

Two more things happen to every checkout:

- **The visitor's own currency.** Polar picks the currency, and pre-fills the billing country for tax, from the IP address that creates the checkout. A checkout created on the server shows Polar the deployment's address, not the customer's. `useBilling().checkout` reads the visitor's IP from the app's own `/api/backend/visitor-ip` route and sends it as `customerIpAddress`, which `generateCheckoutLink` forwards as Polar's `customer_ip_address`, so a visitor in France pays in euros where the catalog prices them. One that is no IP address is refused as `invalid_input` (`customerIpAddress`). Nothing is stored: the address goes to Polar with the checkout and nowhere else.
- **Proof of the auto-renew consent.** California asks a seller to keep proof that the customer agreed to a renewing subscription, for three years. `setupBilling` records it as a renewing checkout is made: the plan, the price and interval shown, the [terms](https://nuxt-backend.dev/docs/ship/compliance/privacy) version the person agreed to, and who. The subscription the checkout starts confirms it with its time. The record is deleted three years after, and one whose checkout started nothing after two days. How it meets an erasure request before then is on [Follow subscription law](https://nuxt-backend.dev/docs/ship/compliance/subscriptions), which is not legal advice.

A checkout someone opens and leaves sends Polar's `checkout.expired`. With `setupBilling({ lifecycle: { abandonedCheckout: true } })`, the package records `billing.checkout_abandoned` once, with the person who opened it, which the `checkoutAbandoned` lifecycle email starts from, for someone who agreed to hear from you ([Send lifecycle emails](https://nuxt-backend.dev/docs/build/growth/engage/lifecycle-emails)).

### A different trial or discount, from the server

Server code can choose what a client can't, through `billing.checkout`:

- a trial of 1 to 30 days, counted in days or weeks (`{ interval: 'day', count: 30 }`, `{ interval: 'week', count: 4 }`), or `trial: false` to remove the plan's own. Months are refused: the provider counts a month as a calendar month, up to 31 days;
- a discount of the catalog by its key (`discount`), one without a code included;
- any discount by id (`discountId`).

Decide who qualifies in your own action, then call it:

```ts [backend/partners.ts]
import { v } from 'convex/values'
import { backendError } from 'nuxt-backend/functions'
import { action } from './_generated/server'
import { billing } from './billing'

export const partnerCheckout = action({
  args: { productId: v.string(), origin: v.string(), successUrl: v.string() },
  handler: async (ctx, { productId, ...urls }) => {
    if (!(await cameThroughPartner(ctx))) throw backendError('forbidden', { reason: 'permission' })
    return billing.checkout(ctx, { productIds: [productId], ...urls, trial: { interval: 'day', count: 30 } })
  },
})
```

`billing.checkout` runs every check above too, and resolves with `{ url }` for the page to open. `cameThroughPartner` is your own code.

## The portal

`portal({ returnUrl })` opens the provider's customer portal for the billing entity: the payment method, the invoices, and the plan where the provider organization lets customers change it. It opens as the caller's own member of the workspace's customer, so it shows who is signed in. Only a billing manager opens it, in person: an impersonating administrator is refused. `returnUrl` must be on the site, like a checkout's `successUrl`. [The billing portal](https://nuxt-backend.dev/docs/build/billing/setup#the-billing-portal) says who may open it.

## Campaign links

A campaign link carries a discount code and its UTM parameters. Pass them on, and the server applies the code and stores the attribution on the order or subscription as `utm_source`, `utm_medium`, `utm_campaign`, `utm_term` and `utm_content` metadata, the way the provider's own checkout links store it. `useCampaign()` reads both from the address, and `<PricingTable>` passes them on by itself ([Share campaign links](https://nuxt-backend.dev/docs/build/growth/offers/campaign-links)):

```ts
const { checkoutOptions } = useCampaign()

await checkout(products.value!.pro!.id, checkoutOptions.value)
```

Each attribution value is trimmed and cut to 100 characters, and empty ones are dropped, so an edited link shortens instead of failing. The provider checks the code like one the customer typed. A code it does not accept (unknown, expired, used up, not for this product) refuses the checkout as `invalid_input` with `field: 'discountCode'`. A code also turns `allowDiscountCodes` on for that checkout.

Each refused code counts against the billing entity. After ten in an hour, a checkout with a code is `rate_limited` (`limit: 'discountCode'`, with `retryAfter`) until the hour is up, and one without a code still goes through. The count is the package's own, kept whether or not you pass a `rateLimiter`, so nobody can use checkout to try codes one after another. A code counts from before the provider checks it, so parallel checkouts can't try more between them. An accepted code, or one a failed checkout never got to try, is not counted.

## Without code

`<BillingCheckoutLink>` and `<BillingPortalLink>` render the same two actions as links, bound to `generateCheckoutLink` and `generateCustomerPortalUrl`:

```vue [app/pages/plans.vue]
<template>
  <BillingCheckoutLink :product-ids="[productId]" @error="error = getBackendError($event)">Upgrade</BillingCheckoutLink>
  <BillingPortalLink return-url="/app/billing">Manage billing</BillingPortalLink>
</template>
```

Each creates its provider session when clicked, never when it renders, so the server checks every input then and a page view opens nothing. `<BillingCheckoutLink>` takes `product-ids`, `subscription-id`, `metadata`, `locale`, `discount-code`, `utm` and `success-url` (the current page by default); `<BillingPortalLink>` takes `return-url`. Both open in the same tab; `:redirect="false"` opens a new tab instead, which a browser may block, since the tab opens only once the session exists. Both mark themselves `aria-busy` while the session is created, pass `{ pending }` to their default slot, and emit a refusal as `error`. While a topic takes the soft opt-in, `<BillingCheckoutLink>` shows its notice and box after the link, the two in one `data-billing="checkout-group"` span, as `<PricingTable>` does under its buttons, and passes `emailOptOut` itself.

## What happens when…

<table>
<thead>
  <tr>
    <th>
      Refusal
    </th>
    
    <th>
      When
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        invalid_input
      </code>
      
       naming the field
    </td>
    
    <td>
      A product outside the catalog, a return address off the site, a reserved metadata key, a trial from a client, a currency the catalog doesn't price, or a code Polar refuses (<a href="#what-the-server-decides">
        What the server decides
      </a>
      
      )
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        invalid_input
      </code>
      
      , reason <code>
        retired
      </code>
      
       or <code>
        free_plan
      </code>
    </td>
    
    <td>
      A retired plan or the free plan
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        not_ready
      </code>
      
      , reason <code>
        no_catalog
      </code>
    </td>
    
    <td>
      No catalog for this environment yet
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        forbidden
      </code>
      
      , reason <code>
        already_subscribed
      </code>
    </td>
    
    <td>
      A second plan while the entity holds one; use <code>
        changePlan
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        forbidden
      </code>
      
      , reason <code>
        not_billing_manager
      </code>
      
      , <code>
        impersonating
      </code>
      
       or <code>
        not_owner
      </code>
    </td>
    
    <td>
      The caller may not buy for this entity, or names a subscription that isn't theirs
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        rate_limited
      </code>
      
      , limit <code>
        discountCode
      </code>
    </td>
    
    <td>
      Ten refused codes in an hour
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        unavailable
      </code>
      
      , reason <code>
        checkout_paused
      </code>
    </td>
    
    <td>
      The <a href="https://nuxt-backend.dev/docs/ship/operate/flags#kill-switches">
        <code>
          pause_checkout
        </code>
      </a>
      
       kill switch is on
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        unavailable
      </code>
      
      , reason <code>
        not_launched
      </code>
    </td>
    
    <td>
      Billing is not launched on this production deployment yet (<a href="https://nuxt-backend.dev/docs/build/billing/setup#before-billing-launches">
        Before billing launches
      </a>
      
      )
    </td>
  </tr>
</tbody>
</table>

[Errors](https://nuxt-backend.dev/docs/reference/backend/errors#invalid_input) lists each code's fields.

## Limits

- **Hosted only.** The checkout and the portal are Polar's pages. Embedding Polar's checkout needs each embedding host on Polar's allowlist, enforced since 2026-08-17.
- **One discount per checkout.** Polar applies one, from a code, a campaign or a promotion.
- **Trials up to 30 days from the server**, counted in days or weeks. A plan's own trial comes from the catalog.
- **No card on file without a checkout.** A first subscription always goes through Polar's checkout; a resume or a plan change reuses the card.

## Test it

`createBackendMock` records each call, so a test checks what a button sends without a provider:

```ts [test/app/upgrade.test.ts]
import { mountSuspended } from '@nuxt/test-utils/runtime'
import { createBackendMock, resetBackendMock } from 'nuxt-backend/test-utils'
import { afterEach, expect, test } from 'vitest'
import { BillingPortalLink } from '#components'

afterEach(() => resetBackendMock())

test('the portal link asks for a portal session when clicked, not before', async () => {
  const backend = createBackendMock({ user: { name: 'Ada' } })
  backend.stub('billing:generateCustomerPortalUrl', () => ({ url: 'https://sandbox.polar.sh/portal' }))
  const link = await mountSuspended(BillingPortalLink, { props: { returnUrl: '/settings' } })
  expect(backend.callsTo('billing:generateCustomerPortalUrl')).toEqual([])
  await link.trigger('click')
  expect(backend.callsTo('billing:generateCustomerPortalUrl')).toHaveLength(1)
})
```

End to end, pay on Polar's sandbox with the test card `4242 4242 4242 4242` ([Run end-to-end tests](https://nuxt-backend.dev/docs/develop/testing/e2e)).

## Related

- [Polar](https://nuxt-backend.dev/docs/services/polar): the sandbox, the portal settings and the test card.
- [Manage subscriptions](https://nuxt-backend.dev/docs/build/billing/subscriptions): change, cancel, pause and resume the plan once it runs.
- [Run a promotion](https://nuxt-backend.dev/docs/build/growth/offers): the catalog discounts a checkout applies by key.
- [Share campaign links](https://nuxt-backend.dev/docs/build/growth/offers/campaign-links): a link that carries a code and UTM attribution into checkout.
- [`<BillingCheckoutLink>`](https://nuxt-backend.dev/docs/reference/components/billing#billingcheckoutlink) and [`<BillingPortalLink>`](https://nuxt-backend.dev/docs/reference/components/billing#billingportallink): their props, slots and events.


## Sitemap

See the full [sitemap](https://nuxt-backend.dev/sitemap.md) for all pages.
