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

# Adopt an existing subscription

> Records a subscription that already exists at your gateway and has never existed here, in the environment your key names. The migration path for arriving with customers who are already paying — and the reason it belongs on a key rather than only in the panel is that **your backend is the only system that holds the map** from a gateway payer to one of your accounts.

It is the same act as the panel's, with the same refusals. See the guide for the order to do things in: connect the gateway, import the catalogue, give the plans their features, make sure the teams exist, then run this over your list.

## What it does

Reads the subscription from the gateway and writes it down against the customer you name — status, period, trial, scheduled cancellation and line. Nothing is charged, nothing is created at the gateway, and nothing about the subscription changes: what changes is that this system now holds it. From then on webhooks find it, the nightly reconciliation re-reads it, and entitlements resolve through its plan.

## Naming the customer

By `customer_external_id` — your own id for the team — or by `customer_id`. Send exactly one. The customer has to exist; this does not create one, and `POST /v1/customers` is the call that does.

## Running it over a list

Two layers answer two different retries. The surface's `Idempotency-Key` **replays** the same response for a repeated request, which is what a client's backoff needs. And adopting the same subscription for the same customer again answers **200** with the row and writes nothing, which is what a batch re-run a week later needs. Adopting it for a *different* customer is refused: that is the one repeat that means somebody made a mistake.

A **201** means a row now exists that did not.

## What it refuses to guess

There is no un-adopt — a subscription is never deleted here, and its gateway reference is only ever written into an empty column — so anything that would have to be assumed is refused: a price that is not mapped into this environment's catalogue (there is no plan to record it against), a subscription the gateway holds several priced lines for (which line names the plan is a question no gateway answers), one this environment already mirrors, and one the gateway says a different payer holds.

That last check runs **only on evidence**. No gateway customer id is stored here, so this customer's payer reference is discovered by reading a subscription they already hold — and a customer you are about to migrate usually has none. Silence is not a mismatch.



## OpenAPI

````yaml /api-reference/openapi.json post /v1/subscriptions/link
openapi: 3.1.0
info:
  title: UserKit API
  version: 1.0.0
  description: >-
    The HTTP surface of UserKit.


    Two planes share one API. The **staff plane** is what a human uses in the
    panel: users, organizations, roles, members, keys. The **customer plane** is
    what a developer's own product uses: contacts, identities, the federated
    boot and the two proofs of an address.


    Every error answers the same envelope — `{"error": {"code", "message"}}`.
    The `code` is a stable contract to branch on; the `message` is for a person
    and may change.
servers:
  - url: '{baseUrl}'
    description: The API host.
    variables:
      baseUrl:
        default: https://api.userkit.dev
        description: Base URL of the API, no trailing slash.
security:
  - sessionToken: []
tags:
  - name: Gamification
    description: >-
      Points, levels and badges: the acts your product wants repeated, written
      down as rules, and what each of your own users has accumulated by doing
      them. A rule pays when the fact it names lands — there is no endpoint your
      users can call that moves a balance, and there is not going to be one.
  - name: Authentication
    description: >-
      Public sign-up, sign-in, two-factor and password recovery for staff
      accounts.
  - name: Session
    description: >-
      The active session: who the caller is, which organization they are in, and
      signing out.
  - name: Account
    description: The caller's own account — profile, password, sessions, avatar.
  - name: Two-factor
    description: >-
      TOTP setup, activation and recovery codes. Returns 501 when two-factor is
      unavailable on the server.
  - name: Organizations
    description: The organizations a user belongs to, and the active one.
  - name: Environments
    description: >-
      The live and test environments seeded with every organization, and their
      identity settings.
  - name: Members
    description: Memberships and invitations.
  - name: Roles
    description: Roles and the permission catalogue they draw from.
  - name: Audit log
    description: >-
      What staff did inside an organization. Append-only, and read behind its
      own permission.
  - name: API keys
    description: Secret keys (`uk_sk_…`) and publishable keys (`uk_pk_…`).
  - name: Contacts (staff session)
    description: >-
      The staff view of the customer plane, opened by a staff session. Reads
      take `?environment=` as an explicit view parameter.
  - name: Contacts (API key)
    description: >-
      The machine surface, authenticated by an API key. The environment is the
      key's environment and cannot be named by the caller.
  - name: Customer plane
    description: >-
      Called from the developer's own pages with a publishable key: boot, the
      two proofs of an address (magic link, email code), and the contact's own
      session.
  - name: Customer teams
    description: >-
      A customer is a team. Its roster, its invitations and the roles held
      inside it, administered by the contact's own session. `owner` and `member`
      always exist; the rest of the vocabulary is the organization's own — see
      Customer roles. The active customer travels in `X-Customer-Id`.
  - name: Customer roles
    description: >-
      The vocabulary of roles inside your customers, defined per environment. A
      customer used to be two shapes — the person who administers it and
      everybody else — which is what `owner` and `member` are, and they are
      still seeded into every environment and cannot be deleted. Beyond them you
      define your own: a school has a director, a secretary, a teacher and a
      student, and none of that fits a boolean.


      A role carries permissions from **two vocabularies in one list**.
      Permissions beginning with `$` are UserKit's own and are the only ones we
      evaluate — `$team.manage` administers the roster, `$billing.manage` the
      money, `$keys.manage` the team's API keys. Everything else is yours: we
      store it, we hand it back on the contact's session and in the
      `customer_permissions` claim of their JWT, and we never read it. That is
      the point — your backend gates `grades:write` offline, and adding a role
      never means editing your gate.


      Reading is `customers:read`, writing `customers:write`.
  - name: Webhooks
    description: >-
      Outbound webhooks: endpoints, the published event catalogue, the delivery
      log, replay and test sends. Never gated by a plan — webhooks are a
      developer primitive.
  - name: Catalogue
    description: >-
      The plans, prices and features **you** sell to your own customers. Per
      environment, a price per currency, and `recurring` or `one_time`. Distinct
      from the plan you are on with UserKit, which is `GET
      /v1/organization/entitlements`.
  - name: Subscriptions
    description: >-
      What one of **your** customers is paying you, mirrored from the gateway
      that charges them. The gateway is the truth about money — it holds the
      schedule, runs the retries and decides what a proration is worth — so
      these routes ask it to change something and answer with what it then said.
      `provider_synced_at` is how stale the copy admits to being.
  - name: Provider webhooks
    description: >-
      Where a payment provider delivers to. Not a surface you call — it is a URL
      you paste into the provider's dashboard, which is why it sits outside
      `/v1`: a version bump must never mean editing a setting in somebody else's
      product. Signed with the secret of the connection named in the path, and
      safe to retry.
  - name: Entitlements
    description: >-
      What one of **your** customers may do, resolved: the plan their
      subscription carries, plus the overrides you promised them on top. This is
      the read your own gate calls, so it is cached and answers in one round
      trip. It is a different question from `GET /v1/organization/entitlements`,
      which is the plan **you** are on with UserKit — two catalogues, same word,
      different money.
  - name: Credits
    description: >-
      How much of a `credit` feature one of **your** customers still holds. The
      balance is an append-only ledger folded on demand — grants arrive from
      paid invoices, usage spends against it (`POST /v1/usage`, fail closed),
      unused credits expire oldest-first, and a support correction is a new
      signed line rather than an edit. Whether a balance may go below zero, and
      how far, is the plan's `overdraft_limit`.
  - name: Customer API keys
    description: >-
      Keys **your customers** issue (`uk_ck_live_…` / `uk_ck_test_…`) so your
      own metered surface can be called per key. An owner of a customer team
      mints them from their session; your backend treats the string as data and
      resolves it with `POST /v1/customer-keys/verify` (or passes it as
      `customer_key` to `POST /v1/usage`). A customer key never authenticates
      against this API.
  - name: Customer webhooks
    description: >-
      Webhook endpoints **your customers** register from the portal, hearing the
      events *you* tracked about their team — `POST /v1/track` lines carrying
      their `customer_id`, delivered under your own event names. Administered
      under `$webhooks.manage` (the seeded `owner` role holds it), signed and
      retried exactly like your own endpoints, and gated by your plan:
      registering answers `webhooks_not_available` on a plan without the
      capability, and a downgrade stops deliveries without deleting anything.
  - name: Pricing
    description: >-
      The public read of what you sell: live plans and prices, addressed by
      publishable key, cacheable like JWKS. What a `<PricingTable/>` renders,
      and the offer the customer's own checkout sells from.
  - name: Customer billing
    description: >-
      The customer's **own** view of what their team pays, from their session:
      the subscription, the invoices, and the self-serve acts — checkout, plan
      change, cancel, resume, the gateway's portal. Reads are for every member;
      the money acts are owner-only, because spending the team's money is
      administering the team.
  - name: Support
    description: >-
      The support inbox. A conversation is opened by **your customer** — from
      the chat widget, or by an inbound email — and staff receive it: there is
      deliberately no staff-side create. Conversations live in an environment
      (their subject is a contact); tags and saved replies are the
      organization's own vocabulary and take no environment. `support:read` and
      `support:write` gate the staff surface, and every seeded role holds both —
      the support agent is the archetypal member seat.
  - name: Help center
    description: >-
      The articles you publish so a conversation does not have to happen.
      Organization-scoped — the product does not differ between live and test
      the way its contacts do — and versioned append-only: saving creates the
      next version, publishing points the public page at one of them, and
      restoring is publishing an old one. The editor rides the support
      permissions; the published side is public, addressed by your publishable
      key, and cacheable.
  - name: Segments
    description: >-
      Audiences, defined declaratively over contact attributes, plan, events and
      activity. One definition compiles into two evaluators that must agree — a
      query over the environment and an in-process match for one contact — so
      the count on a screen and the decision made about one person come from the
      same sentence. Reading is `customers:read` (a segment is a filtered list
      of contacts); writing is `segments:manage`, because one definition decides
      who is mailed, surveyed and shown an unreleased feature at once.
  - name: Feature flags
    description: >-
      Release switches the tenant's own product reads. A flag is aimed at a
      **segment** and never at a filter of its own, so the audience a rollout
      uses is the audience a survey and a changelog post can use. Two reads
      serve it: `POST /v1/boot` decides every flag for the person in the round
      trip the session already cost, and `GET /v1/flags/{publishable_key}` is a
      public, cacheable document that carries only the switch — polled on a
      fifteen-second clock and applied over whatever the page booted with. Staff
      CRUD is `flags:manage`.
  - name: Onboarding
    description: >-
      Checklists the widget renders for your own users, and the funnel behind
      them. A step is satisfied by a **fact having happened** or by an
      **entitlement being held** — there is no endpoint that marks one done, by
      construction, because a checklist whose completion is a button is a
      measure of who pressed the button. Event steps are written by a bus
      consumer and are what the funnel counts; entitlement steps are decided on
      the read against the team the request names, and nothing is stored for
      them. Staff CRUD and the funnel are `engagement:manage`, the permission
      the changelog and surveys share.
  - name: Surveys
    description: >-
      NPS and one-question surveys, asked in-app. A survey is aimed at a
      **segment** or at everybody, fires on a trigger (a fact you named,
      entering that audience, or N days after somebody signed up) and is held
      back by a **per-contact cooldown** — the window is per person rather than
      per survey, which is what makes "nobody is surveyed twice a week" true
      across every survey you run. Delivery is in-app: `GET
      /v1/contact/surveys/pending` is what the widget reads and `POST
      /v1/contact/surveys/{id}/response` is the answer, which announces
      `survey.response_recorded` to your webhooks. Staff CRUD and the results
      are `engagement:manage`, the permission onboarding and the changelog
      share.
  - name: Changelog
    description: >-
      What you shipped, said once. A post is written as a draft, aimed at a
      **segment** or at everybody, and published by an act of its own —
      publishing is what puts it in a cacheable public document and announces
      `changelog_post.published` to your webhooks, so it is a call you make on
      purpose rather than a field on an edit. Two reads serve it: `GET
      /v1/changelog/{publishable_key}` is the public release page and carries
      the posts aimed at nobody in particular; `GET /v1/contact/changelog` is
      the same list for one signed-in person, with the targeting honoured and
      their read state on it. Staff CRUD is `engagement:manage`, the permission
      onboarding and surveys share.
  - name: Banners
    description: >-
      Messages you put on your own users' screens — a strip at the top of the
      dashboard, a notice in the billing settings, a picture you designed. A
      banner names a **slot**, which is a place your own developer left room for
      with `<Banner slot="dashboard-top" />`; nothing is injected into your
      layout, because the only place a third party may draw is one the page
      owner declared. It is aimed at a **segment** or at everybody, bounded by
      an optional window, and only **one banner per slot** is ever returned —
      highest priority wins, decided in the database so every client gets the
      same answer. Two kinds: `text` (title, body, icon, tone, button), drawn by
      the widget in your palette, and `image`, a picture you made and optionally
      a link. `GET /v1/contact/banners` is what the widget reads and `POST
      /v1/contact/banners/{id}/dismiss` is the close button. Staff CRUD is
      `engagement:manage`, the permission onboarding, the changelog and surveys
      share.
  - name: Legal
    description: >-
      The terms your own customers agree to — terms of service, a privacy
      policy, a code of conduct — and the record of who agreed to which words. A
      **document** is a name, an address (`slug`) and a rule about whether
      agreeing is required; a **version** is the text, and it is frozen the
      moment it is published, because an acceptance that pointed at an editable
      body would prove nothing. Publishing may be dated ahead, which is what a
      thirty-day notice is: the version before it stays in force until then. A
      new version asks everybody again only when it says `requires_reacceptance`
      — a corrected typo does not, a new arbitration clause does. `GET
      /v1/legal/{publishable_key}` is public and cacheable, because a sign-up
      form has to render the link before there is any session. `required`
      refuses nothing — there is no sign-up door of UserKit's for it to refuse
      at — and is reported as `blocking` wherever outstanding agreements are
      read; what an outstanding agreement does is your product's decision. It
      never refuses an ordinary API call, and `POST /v1/contact/token` in
      particular — publishing new terms must mean "everybody is asked", never
      "everybody is logged out". Staff CRUD is `legal:manage`.
  - name: Feedback
    description: >-
      A feedback board and a public roadmap. Your users ask for things, vote on
      each other's requests and read what you answered; you triage, merge the
      duplicates and move a post to `planned`, `shipped` or `declined`. The part
      a separate feedback tool cannot do is the ranking: `GET
      /v1/organization/feedback?currency=BRL` weights every post by the
      **revenue of the distinct customers behind its voters**, so a team of five
      is worth its revenue once rather than five votes. That number exists on
      the staff read and nowhere else — the public board says how many people
      asked, never who pays. Reading is `feedback:read` (owner, admin **and**
      member, because triage is support work); answering is `feedback:write`.
  - name: Notifications
    description: >-
      Consent for the mail this platform sends your own users, and the
      unsubscribe link that changes it.


      Three categories — `marketing`, `product_news` and `surveys` — and every
      one of them is something a person can switch off. **Transactional mail is
      not one of them, and there is no value that names it.** A receipt, a
      dunning notice, a verification link and a password reset keep arriving
      after somebody unsubscribes from everything, because the absence of the
      category is what guarantees no screen and no bulk update can produce a
      person who cannot reset their own password.


      Consent is honoured at the **send funnel** rather than by whoever composes
      the message, in the same statement that records the delivery — so a
      message this person switched off is a message that is never composed, not
      one that is filtered afterwards. Every non-transactional message carries
      the unsubscribe link in its footer and the `List-Unsubscribe` /
      `List-Unsubscribe-Post` header pair on its envelope; no transactional
      message carries either.
  - name: Messaging
    description: >-
      The message templates outbound campaigns send: a subject, a body, a
      channel and the **category** the recipient can switch off.


      The subject and the body are Go `text/template`, compiled **when you
      save** — a template naming a field the message context does not carry is
      refused with the field named, never stored to fail per recipient in a job
      at three in the morning. The context is closed on purpose: `Contact`,
      `Customer`, `Plan` and `Entitlements`, and nothing else. Whatever a
      template can reach is reachable by whoever can write one.


      The category lives on the template rather than on whatever sends it,
      because a category is a statement about what a message *says*, and the
      template is the only object here that knows what it says. A campaign
      inherits it. `messaging:manage` covers the whole surface, reads included —
      an unsent price change is not something a wider permission should be able
      to read.
  - name: Campaigns
    description: >-
      The object that reaches out: an audience, a trigger, a sequence and a cap.


      The audience is always a **segment** — there is no filter of a campaign's
      own, because an audience defined twice can be previewed one way and mailed
      another. The words are a **message template**, and the campaign inherits
      the template's category rather than choosing one. The trigger is one of
      four: a one-shot to whoever is in the audience now, a fact of a named
      type, entering the audience, or N days from a timestamp on the contact.


      Two limits hold at once and they are different promises.
      `frequency_cap_days` is how long **this** campaign waits before reaching
      the same person again; a 24-hour cooldown across **every** campaign of the
      environment sits behind it, so somebody who trips three rules in one hour
      receives one message. Neither applies to the later steps of a sequence
      already begun — a cooldown that broke a sequence in half would be a setup
      that works in test and truncates in production.


      A contact who has switched the template's category off is recorded as
      **suppressed with the reason**, which is what lets support answer "why
      didn't they get it". Writing a campaign is free; **arming** one is what a
      plan gates.
  - name: In-app notifications
    description: >-
      The message that lands inside your product rather than in an inbox: "your
      export is ready", "the invoice failed", "someone mentioned you".


      Your backend posts one over `uk_sk_…` and the person reads it from their
      own session. It is **transactional by construction** — the request carries
      no category and there is no field that could carry one, so an in-app
      notification is not something anybody can unsubscribe from, in the same
      way a receipt is not. That is not a policy this endpoint applies; it is
      the only value the write can produce.


      The write inherits the machine surface's two promises by living on it: an
      `Idempotency-Key` replays the first response rather than telling somebody
      the same thing twice, and the per-key rate limit counts the call. The
      recipient is named by `contact_id` or by your own `external_id` — one of
      the two, never both, because a request naming two people is a request we
      would have to guess about.
  - name: MCP
    description: >-
      One endpoint an AI agent's client connects to, so "how many people signed
      up this week" is answered where the question is asked. Authenticated with
      an API key, which is also what fixes the environment — no tool takes one
      as an argument. Every tool is a READ: nothing here creates, changes or
      deletes anything, and nothing answers with a credential or with the staff
      audit log. Outside `/v1` because the URL lives in a configuration file
      rather than in your code.
  - name: Analytics
    description: >-
      The staff read of what happened inside your product: the event explorer,
      daily counts, saved queries and funnels. Everything here sits behind
      `analytics:read` — owner and admin by default, because Phase 4's
      dashboards put revenue on the same screens as event counts. The write path
      is `POST /v1/events` and the platform's own auth facts; no staff session
      reaches it.
  - name: Alerts
    description: >-
      Where your organization's bad news gets delivered: Slack, Discord or
      email. Everything else here is pull — you open a screen and the number is
      there — and this is the push half, for the five facts nobody opens a
      screen to discover: the contact meter at 80% and 100%, an environment out
      of its email allowance, a webhook endpoint turned off after sustained
      failure, a payment gateway that stopped answering, and a customer's
      payment being declined.


      The five are **fixed**. There is no rule to configure and no threshold to
      set — what fires is decided by the code that publishes each fact, and a
      second place to re-decide it would be a place that disagrees. What you
      configure is the destination.


      The destination is stored encrypted and is never read back: a Slack
      incoming webhook is a credential, and whoever holds it writes into that
      channel. Responses carry `destination_hint` — the host for a chat hook,
      the address for an email. Gated by `alerts:manage`, which only `owner`
      holds by default.
  - name: Referrals
    description: >-
      Your own users bringing you other users, and what you owe them for it. A
      code carries its terms (a share in basis points, or a flat bounty),
      `?ref=CODE` is captured by the SDK as first-touch attribution and recorded
      at the referred person's first identification, and a paid invoice appends
      a commission line. First touch is immutable — whoever referred somebody
      referred them, and a later link cannot take the commission — and a refund
      appends a negative line rather than erasing the positive one. Payouts are
      manual: this surface says what is owed and nothing here transfers money.
paths:
  /v1/subscriptions/link:
    post:
      tags:
        - Subscriptions
      summary: Adopt an existing subscription
      description: >-
        Records a subscription that already exists at your gateway and has never
        existed here, in the environment your key names. The migration path for
        arriving with customers who are already paying — and the reason it
        belongs on a key rather than only in the panel is that **your backend is
        the only system that holds the map** from a gateway payer to one of your
        accounts.


        It is the same act as the panel's, with the same refusals. See the guide
        for the order to do things in: connect the gateway, import the
        catalogue, give the plans their features, make sure the teams exist,
        then run this over your list.


        ## What it does


        Reads the subscription from the gateway and writes it down against the
        customer you name — status, period, trial, scheduled cancellation and
        line. Nothing is charged, nothing is created at the gateway, and nothing
        about the subscription changes: what changes is that this system now
        holds it. From then on webhooks find it, the nightly reconciliation
        re-reads it, and entitlements resolve through its plan.


        ## Naming the customer


        By `customer_external_id` — your own id for the team — or by
        `customer_id`. Send exactly one. The customer has to exist; this does
        not create one, and `POST /v1/customers` is the call that does.


        ## Running it over a list


        Two layers answer two different retries. The surface's `Idempotency-Key`
        **replays** the same response for a repeated request, which is what a
        client's backoff needs. And adopting the same subscription for the same
        customer again answers **200** with the row and writes nothing, which is
        what a batch re-run a week later needs. Adopting it for a *different*
        customer is refused: that is the one repeat that means somebody made a
        mistake.


        A **201** means a row now exists that did not.


        ## What it refuses to guess


        There is no un-adopt — a subscription is never deleted here, and its
        gateway reference is only ever written into an empty column — so
        anything that would have to be assumed is refused: a price that is not
        mapped into this environment's catalogue (there is no plan to record it
        against), a subscription the gateway holds several priced lines for
        (which line names the plan is a question no gateway answers), one this
        environment already mirrors, and one the gateway says a different payer
        holds.


        That last check runs **only on evidence**. No gateway customer id is
        stored here, so this customer's payer reference is discovered by reading
        a subscription they already hold — and a customer you are about to
        migrate usually has none. Silence is not a mismatch.
      operationId: linkSubscriptionWithKey
      parameters:
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - provider_subscription_id
              properties:
                provider_subscription_id:
                  type: string
                  description: >-
                    The gateway's own id for the subscription to adopt, such as
                    a Stripe `sub_…`.
                customer_external_id:
                  type: string
                  description: >-
                    Your own id for the team that is paying. Mutually exclusive
                    with `customer_id`.
                customer_id:
                  type: string
                  format: uuid
                  description: >-
                    The same, addressed by our id. Mutually exclusive with
                    `customer_external_id`.
                provider:
                  type: string
                  enum:
                    - stripe
                  description: >-
                    Which gateway holds it. Only needed when the environment has
                    more than one connected.
            example:
              customer_external_id: acme-inc
              provider_subscription_id: sub_1P9x…
      responses:
        '200':
          description: >-
            It was already adopted for this customer, and the row is returned
            unchanged. Nothing was written.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Subscription'
        '201':
          description: >-
            Adopted. The subscription as the gateway just reported it, with its
            line.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Subscription'
        '400':
          description: >-
            `invalid_request` — no `provider_subscription_id`, neither way of
            naming the customer, or both at once; or `provider_required` when
            the environment has more than one gateway connected and none was
            named.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '404':
          description: >-
            `not_found` — no such customer in this key's environment, or no
            customer carrying that external id.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '409':
          description: >-
            `price_not_mapped_to_provider` (the response carries
            `unmapped_provider_price_id`, which is the price to import),
            `subscription_has_extra_items`, `subscription_already_linked`,
            `customer_mismatch`, `provider_not_connected`,
            `provider_account_unknown`, `provider_object_missing`, or
            `environment_mode_mismatch`. Each names a different repair — see the
            panel route's description for what each one means.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '429':
          $ref: '#/components/responses/RateLimited'
        '501':
          description: >-
            `billing_provider_unavailable` or `provider_unavailable` — this
            server cannot hold a gateway credential, or has no adapter for that
            gateway.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '503':
          description: >-
            `provider_unreachable` — the gateway could not be reached, so its
            answer could not be read and nothing was written. Retry.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
      security:
        - apiKey: []
components:
  parameters:
    IdempotencyKey:
      name: Idempotency-Key
      in: header
      required: false
      schema:
        type: string
        maxLength: 255
      description: >-
        A key you choose — a UUID, or your own identifier for the operation —
        that makes this write safe to retry. Send the same key again and you get
        the same response back: the same status, the same body, and
        `Idempotent-Replay: true`. The handler does not run a second time.


        The key is scoped to your API key and the route, so keys never collide
        between environments or tenants. It is remembered for 24 hours. Reusing
        it for a different request is refused (`422`), and a second request
        arriving while the first is still running is refused too (`409`) — retry
        that one in a moment.


        A request that failed with a `5xx` or was rate limited leaves the key
        spendable: retry it with the same key.
  schemas:
    Subscription:
      type: object
      description: >-
        What one of your customers is paying, **mirrored** from the gateway.


        That word decides how to read every field below. The gateway is the
        source of truth about money; this is a local copy kept so an entitlement
        can be answered without a network call, joined to the rest of your data,
        and read while the gateway is unreachable. `provider_synced_at` is when
        the copy was last confirmed — `null` means never, which is what a
        checkout that was started and not completed looks like.
      properties:
        id:
          type: string
          format: uuid
        customer_id:
          type: string
          format: uuid
          description: >-
            Who is billed. A subscription always hangs off a customer, including
            when that customer is a team of one.
        plan_id:
          type: string
          format: uuid
          description: >-
            What they are subscribed to, as opposed to how it is billed — which
            is `items`. Entitlements are computed from the plan's features, so
            this always has exactly one answer.
        status:
          type: string
          enum:
            - incomplete
            - trialing
            - active
            - past_due
            - paused
            - canceled
            - unknown
          description: >-
            In **our** vocabulary, never a gateway's spelling, so this does not
            change when you change gateway.


            `incomplete` is created and not yet paid — no access. `past_due` is
            paid before and a payment has failed; whether that keeps access is a
            grace-period decision and not this field's. `unknown` means the
            adapter did not recognise what the gateway said: it is a reason to
            look, never a reason to charge anybody or to cut them off, and it
            deliberately does not read as `active` or as `canceled`.
        current_period_start:
          type:
            - string
            - 'null'
          format: date-time
          description: >-
            The period paid for. Null together with the end, never one alone: an
            `incomplete` subscription has no period, and a made-up one is a date
            an entitlement expires on that nothing happens at.
        current_period_end:
          type:
            - string
            - 'null'
          format: date-time
        cancel_at_period_end:
          type: boolean
          description: >-
            A cancellation that has been **scheduled** and has not happened. The
            subscription is still active until `current_period_end`, which is
            why this is its own field rather than a status.
        canceled_at:
          type:
            - string
            - 'null'
          format: date-time
          description: When it actually stopped. Null while it has not.
        trial_ends_at:
          type:
            - string
            - 'null'
          format: date-time
          description: >-
            Null when there is no trial — which is a different fact from a trial
            that ended, and only one of them should make a screen say a trial
            expired.
        provider:
          type: string
          enum:
            - stripe
          description: >-
            Which gateway holds this subscription. Exactly one: that is who is
            charging the card.
        provider_account_id:
          type: string
          description: >-
            The merchant account, as the gateway names it. Empty until a health
            check has asked who the keys belong to.
        provider_subscription_id:
          type: string
          description: >-
            The gateway's own id. **Empty** for a checkout that was started and
            never completed — a row that exists here and nowhere else, and the
            one state in which no act on this subscription is possible.
        provider_synced_at:
          type:
            - string
            - 'null'
          format: date-time
          description: >-
            When this copy was last re-read from the gateway, as opposed to when
            the row was last written. Null means never confirmed. A mirror that
            cannot say how stale it is would be claiming to be the source.
        created_at:
          type: string
          format: date-time
        updated_at:
          type: string
          format: date-time
        items:
          type: array
          items:
            $ref: '#/components/schemas/SubscriptionItem'
          description: The lines. Present on a single subscription, absent from the list.
        capabilities:
          $ref: '#/components/schemas/BillingProviderCapabilities'
        mirror_refreshed:
          type: boolean
          description: >-
            Present only on the answer to an **act**. `true` means the gateway
            was re-read afterwards and everything above is what it said. `false`
            means the act happened and the copy above is not (or not entirely)
            the gateway's answer — either the re-read did not get through, or it
            did and part of it could not be written down. `mirror_stale_reason`
            says which. Treat it as a reason to read again, never as a sign the
            act failed.
        mirror_stale_reason:
          type:
            - string
            - 'null'
          enum:
            - provider_reread_failed
            - price_not_mapped_to_provider
            - subscription_has_extra_lines
            - null
          description: >-
            Present whenever `mirror_refreshed` is, and **null** when it is
            `true` — an absent field would leave you inferring that nothing is
            wrong.


            `provider_reread_failed` — the gateway was not reachable after it
            accepted the act. Nothing above was updated; read again.


            `price_not_mapped_to_provider` — the gateway named a price that is
            not mapped onto any price in this catalogue for this environment, so
            `plan_id` was left as it was while everything else was applied. This
            one matters: entitlements are computed from the plan, so until you
            map the price (see `unmapped_provider_price_id`) the customer keeps
            the plan they were on. Prices created in the gateway's own dashboard
            are the usual cause.


            `subscription_has_extra_lines` — the gateway holds more priced lines
            than one, so which of them names the plan is not decidable and both
            `plan_id` and `items` were left as they were.
        unmapped_provider_price_id:
          type:
            - string
            - 'null'
          description: >-
            The gateway's own price id to map, when `mirror_stale_reason` is
            `price_not_mapped_to_provider`. Null otherwise.
    Error:
      type: object
      description: Every error in this API answers this envelope.
      properties:
        error:
          type: object
          properties:
            code:
              type: string
              description: Stable. Branch on this.
            message:
              type: string
              description: For a person. May change.
          required:
            - code
            - message
      required:
        - error
      example:
        error:
          code: forbidden
          message: your role does not allow this action
    SubscriptionItem:
      type: object
      description: >-
        One line of a subscription: a price and a quantity. There is exactly one
        today — a subscription is billed on one price, and a second line for the
        same price is a quantity rather than a row.
      properties:
        id:
          type: string
          format: uuid
        quantity:
          type: integer
          format: int64
          description: >-
            Seats, units, licences. Never 0: a line for none of something is not
            a line.
        price:
          type: object
          description: >-
            The price this line points at, as it was agreed. A price is
            immutable, so this still says exactly what the customer consented to
            pay — including when the offer has since been withdrawn.
          properties:
            id:
              type: string
              format: uuid
            plan_id:
              type: string
              format: uuid
            kind:
              type: string
              enum:
                - recurring
                - one_time
            currency:
              type: string
              description: >-
                ISO 4217, always beside the amount: an amount with no currency
                is not a price.
            amount_minor:
              type: integer
              format: int64
              description: >-
                An integer in the currency's minor unit. `1000` is R$10.00 in
                BRL and ¥1000 in JPY.
            tax_behavior:
              type: string
              enum:
                - inclusive
                - exclusive
            archived:
              type: boolean
              description: >-
                Whether the offer has been withdrawn. `true` is normal on a
                subscription sold before a reprice, and it changes nothing about
                what is charged.
    BillingProviderCapabilities:
      type: object
      description: >-
        What a gateway can do **beyond the minimum every gateway can do**. Every
        flag defaults to false, so a provider that declares nothing is treated
        as the weakest one — silence is never a claim. Read it to stop offering
        an act that would be refused.


        **Every flag below is always present.** The object is emitted whole or
        not at all: absent means this server has no adapter loaded for the
        gateway, and it never means "some flags were left out". A reader must
        therefore distinguish `false` from missing rather than testing for
        falsiness — a key that is not here is not a gateway that cannot do
        something, it is a question nobody asked.
      required:
        - scheduled_plan_change
        - proration
        - cancel_at_period_end
        - hosted_portal
        - tax_calculation
        - resume_subscription
        - list_invoices
        - list_catalogue
        - publish_catalogue
        - manage_coupons
        - pause_subscription
        - discount_subscription
        - refund_payment
      properties:
        scheduled_plan_change:
          type: boolean
          description: >-
            A plan change that takes effect at the end of the current period
            rather than now. Without it, asking for one is refused rather than
            applied immediately — which would be a charge the customer did not
            agree to.
        proration:
          type: boolean
          description: >-
            Money already paid can be credited or charged pro rata on a
            mid-period change. Without it, the new price applies from the next
            period.
        cancel_at_period_end:
          type: boolean
          description: >-
            A cancellation that is a schedule rather than an act. Without it,
            cancelling is immediate.
        hosted_portal:
          type: boolean
          description: >-
            The gateway hosts a page where the customer manages their own
            subscription.
        tax_calculation:
          type: boolean
          description: >-
            The gateway computes tax. UserKit never calculates it — the
            catalogue stores whether a price includes tax and nothing more.
        resume_subscription:
          type: boolean
          description: A scheduled cancellation can be undone.
        list_invoices:
          type: boolean
          description: The gateway has an invoice history to read.
        list_catalogue:
          type: boolean
          description: >-
            The gateway's own catalogue can be read, so an existing one can be
            imported instead of retyped. False where the gateway has a price and
            no catalogue above it.
        publish_catalogue:
          type: boolean
          description: >-
            The other direction of the same seam: a price priced HERE can be
            created at the gateway, for the tenant who built their catalogue
            before connecting anything. False where the gateway takes a price
            named in the request and has no catalogue object to create in
            advance — there, the repair is to create the price in the gateway's
            own dashboard and import it.
        manage_coupons:
          type: boolean
          description: >-
            The gateway holds a discount object of its own, so a checkout may
            carry a coupon or open a promotion-code field. False where the
            discount would have to be a cheaper price.
        pause_subscription:
          type: boolean
          description: >-
            Billing can be stopped for a fixed number of months and started
            again by the gateway itself. There is no unpause here on purpose:
            the gateway holds the date, because a system holding the only copy
            of when somebody's product comes back is a promise an outage can
            break. False withholds the pause save offer rather than showing one
            that cannot be carried out.
        discount_subscription:
          type: boolean
          description: >-
            A discount can be attached to a subscription that is already
            running, which is not the same as carrying one on a checkout. A
            gateway with `manage_coupons` and not this can only discount a new
            checkout, so the discount save offer needs both.
        refund_payment:
          type: boolean
          description: >-
            Money can be handed back through the API. False answers **501** on
            the refund route, because there the act is performed in the
            gateway's own dashboard — and it is the flag whose absence matters
            most, since a refund performed twice is the one act in the product
            that cannot be undone from this side.
  responses:
    Unauthorized:
      description: >-
        `unauthorized` — missing, malformed, expired or revoked credential, and
        nothing else: it says the credential is gone, so a client is right to
        discard it and sign in again. A well-formed credential from the wrong
        family says so: "this endpoint expects a staff session token, not an
        organization API key". A LIVE staff session aimed at an organization it
        is not a member of is `not_a_member` (403), never this.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
    RateLimited:
      description: >-
        `rate_limited` — too many requests. `Retry-After` carries the window in
        seconds.


        The counters are shared across instances. When that store cannot be
        reached each instance counts on its own instead: the limits get looser,
        never absent.
      headers:
        Retry-After:
          schema:
            type: integer
          description: Seconds until the window resets.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
  securitySchemes:
    sessionToken:
      type: http
      scheme: bearer
      description: >-
        A staff session token, `uk_st_…`. Minted by sign-up, sign-in or the
        two-factor exchange. Only a 401 means it is spent; `not_a_member` (403)
        is about the organization named in `X-Organization-Id` and leaves the
        token good for the others.
    apiKey:
      type: http
      scheme: bearer
      description: >-
        An organization API key, `uk_sk_live_…` or `uk_sk_test_…`. The
        environment is resolved from the stored key row on every request, never
        from a request parameter.


        Every route behind this credential is rate limited **per key** — 1000
        requests a minute — with a second ceiling of 3000 a minute across all
        the keys of one environment, so splitting your traffic across keys
        isolates it and minting more keys does not buy more of it. A test key
        can never spend a live key's allowance. Every response carries the
        current state in headers; see the rate-limits guide.

````