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

# Build a booking flow

> Wire end-user sign-in into a custom booking flow that calls the MarketBox API, using the backend-for-frontend pattern.

This guide walks you through building a custom booking flow that signs users in
and calls the MarketBox API on their behalf. It covers both auth planes, the
backend-for-frontend (BFF) pattern, client onboarding, reading a user's
package credits, and letting them book their own credit.

If you haven't yet, read [End-user authentication](https://docs.gomarketbox.com/concepts/end-user-authentication.md)
first — it explains the two-plane model this guide builds on.

For the whole checkout on one page, from sign-in to the confirmation screen,
see [Client checkout, end to end](https://docs.gomarketbox.com/guides/client-checkout-end-to-end.md). For the
client's account page, see [Manage a client's account](https://docs.gomarketbox.com/guides/manage-a-client-account.md).

## Prerequisites: create an Application

In the project's [**API Access** page](https://app.gomarketbox.com/dashboard/project/\{projectId}/api-access/)
in the MarketBox dashboard, a project admin creates an **Application**. An Application is the container
for one integration (for example, your booking website): it groups the OAuth
client your users sign in through and the API key your backend calls with.

Creating an Application issues two things:

* A **`clientId`** — identifies your OAuth client. Safe to expose in browser
  config.
* A **one-time API key** — shown once, in the "Application created" dialog. Copy
  it now; it cannot be retrieved later. This is the server-only secret from
  [Authentication](https://docs.gomarketbox.com/concepts/authentication.md). It needs **Standard API access**,
  the default; a key without it is refused with `403 CAPABILITY_NOT_GRANTED`.
  See [Capabilities](https://docs.gomarketbox.com/concepts/authentication.md#capabilities).

The dialog also shows a **Connection details** block of per-environment
constants. The same block is available any time on the **Connection details**
panel of the API Access page.

### Values you receive

**Per-application** (from creating the Application):

| Field | Where it goes |
| - | - |
| `clientId` | Browser config (`NEXT_PUBLIC_OIDC_CLIENT_ID`) |
| API key | Server env var only (`MARKETBOX_API_KEY`) — never `NEXT_PUBLIC_` |

**Per-environment Connection details** (shared across all Applications):

| Field | Description |
| - | - |
| `issuer` | OIDC issuer URL (the authorization authority) |
| `authorizeUrl` | OAuth authorize endpoint |
| `tokenUrl` | OAuth token endpoint |
| `logoutUrl` | OAuth logout endpoint |
| `scopes` | Space-separated scopes (`openid email profile`) |
| `apiBaseUrl` | Base URL for the API — the same value as `$MARKETBOX_API_URL` |

> [!NOTE]
>
> These are standard OIDC values. MarketBox lists the endpoints explicitly rather
> than relying on OIDC discovery, because the discovery document does not advertise
> the hosted-login endpoints or a logout endpoint. Copy them directly from the
> Connection details panel.

## Wire hosted-login auth (PKCE)

Sign-in uses the OAuth 2.0 Authorization Code flow with PKCE. Your browser
redirects to **MarketBox hosted login**; after the user authenticates, MarketBox
redirects back to your callback URL with an authorization code, which you
exchange for tokens.

**1. Allow-list your redirect URLs**

In the dashboard, on your Application's settings, add:

* **Callback URL:** `https://example.com/auth/callback` (the page that
  handles the code exchange, replacing `example.com` with your own domain)
* **Logout URL:** `https://example.com` (where the user lands after
  sign-out)

For local development also add `http://localhost:4000/auth/callback` and
`http://localhost:4000`.

> [!WARNING]
>
> The registered logout URL must **exactly** match the `logout_uri` your app
> sends — the bare origin with no trailing slash. The match is an exact string
> comparison.

**2. Configure the OAuth client**

The env-var mapping from Connection details is direct — no derivation needed:

| Connection field | Env var |
| - | - |
| `issuer` | `NEXT_PUBLIC_OIDC_ISSUER` |
| `authorizeUrl` | `NEXT_PUBLIC_OIDC_AUTHORIZE_URL` |
| `tokenUrl` | `NEXT_PUBLIC_OIDC_TOKEN_URL` |
| `logoutUrl` | `NEXT_PUBLIC_OIDC_LOGOUT_URL` |
| `scopes` | `NEXT_PUBLIC_OAUTH_SCOPES` |
| `clientId` (per-app) | `NEXT_PUBLIC_OIDC_CLIENT_ID` |

The example below uses [`oidc-client-ts`](https://github.com/authts/oidc-client-ts)
in a Next.js app, but any OIDC/PKCE client works.

```ts theme={null}
// src/lib/oidc.ts
import { UserManager } from 'oidc-client-ts';

const origin = process.env.NEXT_PUBLIC_APP_ORIGIN ?? 'http://localhost:4000';
const issuer = process.env.NEXT_PUBLIC_OIDC_ISSUER!;

export function getUserManager() {
  return new UserManager({
    authority: issuer,
    client_id: process.env.NEXT_PUBLIC_OIDC_CLIENT_ID!,
    redirect_uri: `${origin}/auth/callback`,
    response_type: 'code', // Authorization Code + PKCE
    scope: process.env.NEXT_PUBLIC_OAUTH_SCOPES ?? 'openid email profile',
    loadUserInfo: false,
    // Endpoints are provided explicitly rather than via OIDC discovery.
    metadata: {
      issuer,
      authorization_endpoint: process.env.NEXT_PUBLIC_OIDC_AUTHORIZE_URL!,
      token_endpoint: process.env.NEXT_PUBLIC_OIDC_TOKEN_URL!,
      end_session_endpoint: process.env.NEXT_PUBLIC_OIDC_LOGOUT_URL!,
      jwks_uri: `${issuer}/.well-known/jwks.json`,
    },
  });
}

// The signed-in user's access token, or null when signed out or expired.
// The browser snippets below send it to your BFF as `Bearer <token>`.
export async function getAccessToken(): Promise<string | null> {
  const user = await getUserManager().getUser();
  return user && !user.expired ? user.access_token : null;
}
```

**3. Send the user to sign in**

```ts theme={null}
getUserManager().signinRedirect(); // redirects to MarketBox hosted login
```

**4. Handle the callback**

On your `/auth/callback` page, complete the PKCE code exchange and read the
access token:

```ts theme={null}
const um = getUserManager();
await um.signinCallback();              // exchanges the ?code= for tokens
const user = await um.getUser();
const accessToken = user?.access_token ?? null;
```

Forward the **access token**, not the ID token. It must come from your own
Application's `clientId`: a token issued to another client — the MarketBox
dashboard's or another Application's — is logged today and will be refused
with `401` once enforcement is switched on. See
[End-user authentication](https://docs.gomarketbox.com/concepts/end-user-authentication.md#where-the-user-token-comes-from).

Call your backend to onboard the user immediately after the first sign-in
(see [Onboard the client](#onboard-the-client)).

**5. Sign out**

The logout endpoint takes `client_id` + `logout_uri` rather than standard
RP-initiated logout, so clear the local session and redirect manually:

```ts theme={null}
await getUserManager().removeUser();
const params = new URLSearchParams({
  client_id: process.env.NEXT_PUBLIC_OIDC_CLIENT_ID!,
  logout_uri: process.env.NEXT_PUBLIC_APP_ORIGIN!,
});
window.location.assign(`${process.env.NEXT_PUBLIC_OIDC_LOGOUT_URL!}?${params}`);
```

## The BFF pattern

Your backend-for-frontend (BFF) is the only place that holds the API key.
Browser pages call BFF routes; BFF routes attach the key before calling the
MarketBox API.

```ts theme={null}
// app/api/bff/credits/route.ts
import { NextResponse } from 'next/server';

export async function GET(request: Request) {
  // Extract the bearer token forwarded by the browser
  const auth = request.headers.get('authorization');
  if (!auth?.toLowerCase().startsWith('bearer ')) {
    return NextResponse.json({ message: 'Missing bearer token' }, { status: 401 });
  }

  const projectId = process.env.MARKETBOX_PROJECT_ID!;
  const res = await fetch(
    `${process.env.MARKETBOX_API_URL}/v1/projects/${projectId}/clients/me/credits`,
    {
      headers: {
        'x-api-key': process.env.MARKETBOX_API_KEY!, // server-only — never in browser
        authorization: auth,                          // forwarded user token
        'content-type': 'application/json',
      },
    }
  );

  const body = await res.json().catch(() => ({}));
  return NextResponse.json(body, { status: res.status });
}
```

The browser calls `/api/bff/credits` with only `Authorization: Bearer <token>`.
It never touches `MARKETBOX_API_KEY`.

> [!TIP]
>
> **Hardening.** The example above has the browser hold the token in memory and
> send it to the BFF on each request. A more hardened variant stores the token in
> an **httpOnly cookie session** managed entirely by the BFF: after the code
> exchange the BFF sets a signed cookie, and subsequent requests read the token
> from the cookie rather than a request header. This removes the token from
> browser memory and from network headers visible in DevTools.

## Onboard the client

Call `POST /v1/projects/{projectId}/clients/me` once after the user's first
authenticated sign-in. It is **idempotent**: `201` the first time, `200` on every
later call, so it's safe to call on every callback.

On the first call it provisions the signed-in user as a **client** of the
project — an `ACTIVE` project membership with the `CLIENT` role and a client
profile, plus a Stripe Connect `stripeCustomerId` on that profile when the
project has payments configured.

A person who is already a member of the project, such as an admin or a
supplier, and signs in on your booking site becomes a client too. Onboarding
adds `CLIENT` to their roles and keeps the others.

Every other `/clients/me` route requires that `ACTIVE` membership. See
[Who may call an end-user route](https://docs.gomarketbox.com/concepts/end-user-authentication.md#who-may-call-an-end-user-route).

If the business has removed the person's access, onboarding refuses them, and
nothing is read or linked:

```json theme={null}
{
  "code": "MEMBERSHIP_INACTIVE",
  "message": "Your access to this business was removed. Ask them to invite you again.",
  "statusCode": 403,
  "requestId": "5c9e2a7f-8b3d-4e16-a4f0-1d7b6c3e9a25"
}
```

### Send the name your checkout collected

The body is optional. Send `firstName`, `lastName` and `phone` when your
checkout collected them:

```json theme={null}
{
  "firstName": "Emma",
  "lastName": "Bishop",
  "phone": "(416) 555-0134"
}
```

Without names, the client is recorded under the names from their sign-in. A
Google sign-in supplies real names. An email-and-password sign-up supplies only
the email address, so the business would see the client as the part of it
before the `@` on orders, bookings and emails.

Each field you send overwrites the stored value on every call, including for a
client who is already onboarded, and is copied to the client's record in Stripe.
A blank or `null` field counts as not sent and never clears a stored value.
Names are trimmed and must be at most 80 characters. The phone is stored in
E.164 form (`+14165550134`). An invalid name or phone is a `400`, and nothing is
written.

The name is the client's record in this project only. It does not rename the
person's MarketBox account.

### Change the name or phone later

`PATCH /v1/projects/{projectId}/clients/me` changes the signed-in client's
`firstName`, `lastName` or `phone`. It takes the same two credentials as
onboarding, and the client must already be onboarded, or it is a `404`.

* Send only the fields to change. A body with nothing to update is a `400`.
* Names are 1–80 characters after trimming. They can be changed but not
  cleared, so a blank or `null` name is a `400`.
* Send `phone: null` to clear the phone.

Call it **before** `POST /orders`, so booking and order emails use the new name.
The change is also copied to the client's record in Stripe. If that copy fails,
the profile is still updated and the call still returns `200`. The response is
the whole profile, with its saved addresses.

Call it immediately after the code exchange succeeds, before redirecting into
your app:

```ts theme={null}
// app/auth/callback/page.tsx (browser)
import { getAccessToken } from '@/lib/oidc'; // defined in Configure the OAuth client

const token = await getAccessToken();
const res = await fetch('/api/bff/onboard', {
  method: 'POST',
  headers: { authorization: `Bearer ${token}` },
});
// res.status === 201 → newly onboarded
// res.status === 200 → already onboarded (returning user)
router.replace('/me');
```

The BFF route forwards this to `POST /v1/projects/{projectId}/clients/me` with
both the API key and the bearer token.

## Returning visits: fetch credits

On authenticated pages, call your BFF to get the user's remaining package
credits:

```ts theme={null}
// Browser
const token = await getAccessToken();
const res = await fetch('/api/bff/credits', {
  headers: { authorization: `Bearer ${token}` },
});
const { data } = await res.json();
// data is an array of credit items; an empty array is normal before any purchase
```

The BFF calls `GET /v1/projects/{projectId}/clients/me/credits`. Each entry is
a `PACKAGE` order item the client owns:

```json theme={null}
{
  "data": [
    {
      "orderId": "ord_01kx16f0a1c7b2sd91xzq3mn5p",
      "orderItemId": "oi_01kx16f0a1d8c3se02yzq4mn6q",
      "packageId": "pkg_01kvr4cgb3esg8hxx32kwhre7g",
      "serviceId": "srv_01kv60qg12e82acr78edfnjhvv",
      "offeringId": "off_01kv60qge5eh59ap0gw0pqrrys",
      "quantity": 8,
      "quantityAllocated": 5,
      "quantityRemaining": 3,
      "quantityReturned": 1,
      "expiresAt": "2026-12-06T00:00:00.000Z",
      "orderStatus": "PAID"
    }
  ]
}
```

* **`quantityRemaining`** is the live balance: the sessions the client can
  still book.
* **`quantityReturned`** counts the sessions cancellations have returned to
  this credit, ever. They are already counted in `quantityRemaining`, so don't
  add them. A returned session may have been booked again since. Use it to say
  "1 session was returned to your package", not to work out a balance.

Only credits on `PAID` orders are listed. A credit that is used up, has
expired or was removed is left out. Pass `includeExpired=true` to keep the
expired ones.

## Book a client's own credit

The signed-in client can book sessions from their own credit:

```
POST /v1/projects/{projectId}/clients/me/orders/{orderId}/package-bookings
```

It takes the same two credentials as the other `/clients/me` routes, and the
bookings record the client as the person who made them. For the whole flow —
planning a slate from the credit, booking it, and the refusals this route adds —
see [Book a client's package credit](https://docs.gomarketbox.com/guides/book-a-package-credit.md).

## Reference

### Connection constants

Copy these from the Connection details panel in the dashboard (API Access page).
They are per-environment, not per-application.

| Connection field | Env var | Exposed to browser? |
| - | - | - |
| `issuer` | `NEXT_PUBLIC_OIDC_ISSUER` | Yes |
| `authorizeUrl` | `NEXT_PUBLIC_OIDC_AUTHORIZE_URL` | Yes |
| `tokenUrl` | `NEXT_PUBLIC_OIDC_TOKEN_URL` | Yes |
| `logoutUrl` | `NEXT_PUBLIC_OIDC_LOGOUT_URL` | Yes |
| `scopes` | `NEXT_PUBLIC_OAUTH_SCOPES` | Yes |
| `apiBaseUrl` | `MARKETBOX_API_URL` | **No** (BFF-only) |
| `clientId` (per-app) | `NEXT_PUBLIC_OIDC_CLIENT_ID` | Yes |

### Endpoints used in this guide

| Endpoint | Method | Auth required | Description |
| - | - | - | - |
| `/v1/projects/{projectId}/clients/me` | `POST` | `x-api-key` + `Bearer` | Onboard the signed-in client, optionally with `firstName`, `lastName` and `phone`. `201` first call, `200` if already onboarded. |
| `/v1/projects/{projectId}/clients/me` | `PATCH` | `x-api-key` + `Bearer` | Change the signed-in client's name or phone. |
| `/v1/projects/{projectId}/clients/me/credits` | `GET` | `x-api-key` + `Bearer` | The client's remaining package credits, with `quantityReturned`. |
| `/v1/projects/{projectId}/availability/package-slate` | `POST` | `x-api-key` | Plan the sessions left on a credit (`orderId` + `orderItemId`). |
| `/v1/projects/{projectId}/clients/me/orders/{orderId}/package-bookings` | `POST` | `x-api-key` + `Bearer` | Book sessions from the signed-in client's own credit. |

### Error and status cases

| Scenario | HTTP status | Resolution |
| - | - | - |
| Missing or invalid user token on an end-user route | `401` | Ensure the browser sends a valid `Authorization: Bearer` header and that the BFF forwards it. Sign the user in again. |
| API key present but no bearer on an end-user route | `401` | End-user routes require both credentials. |
| Valid token but the user isn't a client of the project yet | `403 FORBIDDEN`, "No active membership on this project" | Call onboarding (`POST .../clients/me`) for the signed-in user before other end-user routes. |
| The business removed the client's access | `403 MEMBERSHIP_INACTIVE` on onboarding; `403 FORBIDDEN` on the other `/clients/me` routes | The client asks the business to invite them again. |
| The API key lacks Standard API access | `403 CAPABILITY_NOT_GRANTED` | A project admin ticks **Standard API access** on the Application. |
| Booking an order that doesn't exist or belongs to another client | `404 NOT_FOUND` | Book only credits from `GET .../clients/me/credits`. |
| Booking a credit the credits read would not list (unpaid, used up, expired, removed) | `409 CREDIT_NOT_BOOKABLE` | Re-read the credits and offer only those listed. |
| Booking from a cancelled order | `409 ORDER_CANCELLED` | Don't retry. The credits were released when the order was cancelled. |
| Booking by a `slateId` or `slotIds` not planned from this credit | `404 NOT_FOUND` | Plan the slate with this `orderId` and `orderItemId`. |
| The API key's project scope doesn't include the requested project | `403` | The Application is scoped to a different project. Create an Application scoped to the correct project, or use a wildcard-scoped key if permitted. See [Projects and scope](https://docs.gomarketbox.com/concepts/projects-and-scope.md). |

### Security checklist

> [!TIP]
>
> `MARKETBOX_API_KEY` is in a server-only env var — no `NEXT_PUBLIC_` prefix.

> [!TIP]
>
> `MARKETBOX_API_URL` (for BFF use) is server-only — the browser never sees it.

> [!TIP]
>
> Callback and logout URLs are allow-listed in the Application settings.

> [!TIP]
>
> The BFF validates that the incoming `Authorization` header starts with `Bearer ` before forwarding it.

> [!TIP]
>
> The one-time API key was copied at creation time and stored in a secrets manager — never committed to source control.

## Run the sample app

A runnable Next.js reference implementation is available on GitHub:
[**pajawale/sample-booking-flow**](https://github.com/pajawale/sample-booking-flow).
It demonstrates:

* PKCE sign-in / sign-up / sign-out against MarketBox hosted login
* A callback page that onboards the client
* A credits page served through the BFF

Follow the repo's `README` to configure the Connection details and run it
locally on port 4000.


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