# Build a booking page

Source: https://developers.weerom.com/docs/booking-page

> Your own booking page on any site, with WeerOm as the backend. Pick a service, show free times, make the booking and handle every answer.

A shop that wants its own booking page, in its own design and on its own site, can keep WeerOm behind it. The page reads the services and the free times and sends the booking. WeerOm does the rest: it checks the shop's rules, puts the booking in the agenda, sends the customer the shop's confirmation mail and tells staff.

The page makes these calls, all with a public key:

| Step | Request |
| --- | --- |
| Read the shop's time zone | `GET /shop` |
| Pick a service | `GET /services` |
| Pick a staff member, if the shop lets customers choose | `GET /staff` |
| Show free times | `GET /availability` |
| Book | `POST /bookings` |

## Which key

| Where the code runs | Key | Why |
| --- | --- | --- |
| In the customer's browser | A public key, `wo_pub_...` | It reads only what the shop's own site shows, and it books under a visitor's limits. Anyone can read it in the page, and that is fine. |
| On your server, which calls WeerOm for the page | A write key, `wo_live_...` | Every request from a server comes from one address. A public key would hit the limit per address after 10 bookings in an hour. Keep this key out of the page. |

Both work with the code on this page. The examples use a public key in the browser, which needs no server at all. An administrator of the shop makes the key under **Settings**, **Features**, **Connections** and picks "Take bookings from a web page". See [Authentication](https://developers.weerom.com/docs/authentication).

## A helper for every call

Every request sends the key. Every error answers `{ "error": { "code", "message", "param", "request_id" } }`, and the page branches on `code`.

```js title="weerom.js"
const BASE = "https://api.weerom.com/v1";

// A public key. It may sit in this file: it reads the shop, its services,
// its staff and its free times, and it makes bookings. Nothing else.
const KEY = "wo_pub_1_3f9a1c2e5b7d4a68c0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5";

export class WeeromError extends Error {
  constructor(status, error, retryAfter) {
    super(error.message);
    this.status = status;
    this.code = error.code;
    this.param = error.param;
    this.requestId = error.request_id;
    this.retryAfter = retryAfter ? Number(retryAfter) : null;
  }
}

export async function weerom(path, { body, idempotencyKey } = {}) {
  const headers = { Authorization: `Bearer ${KEY}` };
  if (body) headers["Content-Type"] = "application/json";
  if (idempotencyKey) headers["Idempotency-Key"] = idempotencyKey;

  const response = await fetch(`${BASE}${path}`, {
    body: body ? JSON.stringify(body) : undefined,
    headers,
    method: body ? "POST" : "GET",
  });
  const json = await response.json();
  if (!response.ok) {
    throw new WeeromError(response.status, json.error, response.headers.get("Retry-After"));
  }
  return json;
}
```

The API answers `Access-Control-Allow-Origin: *` and allows the `Authorization`, `Content-Type` and `Idempotency-Key` headers, so a page on any domain can call it.

### Read the shop

Every time in the API is UTC. Show times to the customer in the shop's own zone, which `GET /shop` names.

```js
const shop = await weerom("/shop");
// { "object": "shop", "name": "Studio Noord", "time_zone": "Europe/Brussels", "currency": "EUR", ... }

const clock = new Intl.DateTimeFormat("nl-BE", {
  hour: "2-digit",
  minute: "2-digit",
  timeZone: shop.time_zone,
});

// The shop's own date today, such as "2026-11-30".
const today = new Intl.DateTimeFormat("en-CA", { timeZone: shop.time_zone }).format(new Date());
```

### Pick a service

```js
const services = await weerom("/services?active=true");

for (const service of services.data) {
  const euros = (service.price_cents / 100).toFixed(0);
  console.log(`${service.name}, ${service.minutes} min, €${euros}`);
}
// Knippen en baard, 45 min, €40
```

`name` is in the shop's own language. `name_translations` holds `en`, `nl`, `fr`, `de` and `pt`. An empty string there means the shop did not translate it, so fall back to `name`.

`price_cents` is the list price with VAT. A deal or a loyalty card can lower it for one customer. The booking that comes back says what they will pay in `price_cents`.

### Pick a staff member, or let anyone do it

```js
const staff = await weerom("/staff?active=true");
const staffName = new Map(staff.data.map((person) => [person.id, person.name]));
```

The staff list does not say who does which service. The free times do: ask for them without `staff_id`, and every slot names the `staff_id` that would do it. Offer the staff who appear there.

### Show free times

```js
async function freeTimes(serviceId, date, staffId) {
  const query = new URLSearchParams({ days: "7", date, service_id: serviceId });
  if (staffId) query.set("staff_id", staffId);
  const slots = await weerom(`/availability?${query}`);
  return slots.data;
}

const slots = await freeTimes(serviceId, today);
```

```json
{
  "object": "list",
  "data": [
    {
      "object": "slot",
      "service_id": "c2a41f6e-8d3b-4e97-b5a0-1f7c9e2d4a68",
      "staff_id": "8e1d5b7c-3a9f-4d20-b6c4-7a2e0f9d1c53",
      "starts_at": "2026-11-30T09:00:00.000Z",
      "ends_at": "2026-11-30T09:45:00.000Z"
    }
  ],
  "has_more": false,
  "next_cursor": null
}
```

| Parameter | What it does |
| --- | --- |
| `service_id` | Required. The service to book. An inactive or unknown service answers 404. |
| `date` | Required. The first day, as a date in the shop's own calendar: `2026-11-30`. Not a time and not UTC. 30 November in Brussels is 30 November whatever zone the customer is in. |
| `days` | 1 to 14. How many days from `date` on. 1 when left out. |
| `staff_id` | Only this staff member's free times. Leave it out to get the free times of everyone active who does the service. |

The list is sorted by `starts_at`, then by `staff_id`. Without `staff_id`, two staff free at 10:00 give two slots at 10:00. For an "anyone" choice, show each time once and keep the first slot for it:

```js
function oncePerTime(slots) {
  const seen = new Map();
  for (const slot of slots) {
    if (!seen.has(slot.starts_at)) seen.set(slot.starts_at, slot);
  }
  return [...seen.values()];
}

for (const slot of oncePerTime(slots)) {
  console.log(clock.format(new Date(slot.starts_at)), staffName.get(slot.staff_id));
}
// 10:00 Sam
```

The free times follow the shop's rules and its agenda: opening hours, bookings already made, the lead time and how far ahead a customer may book. A day outside those comes back with no slots.

### Book

Send the slot's `service_id`, `staff_id` and `starts_at` as they came, with the customer's details.

```js
async function book(slot, person, idempotencyKey) {
  return weerom("/bookings", {
    body: {
      customer: { email: person.email, name: person.name, phone: person.phone },
      comments: person.comments,
      locale: "nl",
      service_id: slot.service_id,
      staff_id: slot.staff_id,
      starts_at: slot.starts_at,
    },
    idempotencyKey,
  });
}
```

| Field | Notes |
| --- | --- |
| `customer.name` | First and last name. A booking with one name answers 400 "First and last name are required". |
| `customer.phone` | With the country code, such as `+32470123456`. A number without one is read as a number in the shop's country. A customer the shop already knows by this phone is reused, else WeerOm makes one. |
| `customer.email` | Required for a booking made as a customer. The confirmation and the reminder go here. |
| `comments` | A note to the shop, up to 500 characters. |
| `locale` | The language of the customer's mail: `en`, `nl`, `fr`, `de` or `pt`. The shop's own when left out. |
| `remind_by_email` | `false` turns off the reminder mail. `true` when left out. |

A public key always books as a customer and may not send `as`. The answer is 201 with the booking:

```json
{
  "object": "booking",
  "id": "0b6f2a4e-5d1c-4f7a-9a3e-2c8d1e6f4b90",
  "code": "UEAMEFC9",
  "status": "confirmed",
  "starts_at": "2026-11-30T09:00:00.000Z",
  "ends_at": "2026-11-30T09:45:00.000Z",
  "price_cents": 4000,
  "currency": "EUR",
  "source": "web",
  "...": "..."
}
```

Show the `code` on the thank-you screen. Staff find the booking by it.

## Book once, even on a bad connection

A phone on a train sends the booking, the connection drops, and the page cannot know whether it went through. Send an `Idempotency-Key` and retry with the same one. If the first request made the booking, the retry gets that same booking back with the header `Idempotent-Replayed: true`, and no second booking is made.

Make one key when the customer presses Book, and a new one when they change the time or their details.

```js
async function bookOnce(slot, person) {
  const idempotencyKey = crypto.randomUUID();
  for (let attempt = 1; ; attempt++) {
    try {
      return await book(slot, person, idempotencyKey);
    } catch (error) {
      const network = error instanceof TypeError;
      const busy = error.code === "request_in_progress" || error.status >= 500;
      if (!(network || busy) || attempt === 3) throw error;
      await new Promise((done) => setTimeout(done, attempt * 2000));
    }
  }
}
```

[Safe retries](https://developers.weerom.com/docs/idempotency) has the rules.

## Handle the answer

```js
try {
  const booking = await bookOnce(slot, person);
  showThanks(booking.code);
} catch (error) {
  if (!(error instanceof WeeromError)) throw error;

  switch (error.code) {
    case "slot_taken":
      // Someone else booked this time a moment ago.
      showMessage("Someone booked this time a moment ago. Pick another one.");
      showSlots(await freeTimes(slot.service_id, today));
      break;
    case "invalid_request":
      // The shop's own sentence, such as "Email is required".
      showFieldError(error.param, error.message);
      break;
    case "limit_reached":
      showMessage("Too many bookings in a short time. Call the shop or try again later.");
      break;
    case "bookings_paused":
      showMessage("The shop takes no online bookings right now. Call the shop.");
      break;
    case "not_allowed":
      showMessage("The shop cannot take this booking online. Call the shop.");
      break;
    case "not_found":
      // The service or the staff member is no longer bookable.
      showServices(await weerom("/services?active=true"));
      break;
    default:
      showMessage(`Something went wrong. Quote ${error.requestId} to the shop.`);
  }
}
```

`showThanks`, `showMessage`, `showSlots`, `showFieldError` and `showServices` stand for your own page's code.

| Status | `code` | When | What the page does |
| --- | --- | --- | --- |
| 201 | | The booking is made. | Show the code and the time. |
| 400 | `invalid_request` | A field is missing or does not fit the shop's rules. `message` says which, in English: "First and last name are required", "Email is required", "That email does not look right". `param` names the field when the API knows it. | Show the message next to the field, or your own words for it. |
| 403 | `not_allowed` | The shop blocked this customer from booking online. | Ask them to call the shop. |
| 404 | `not_found` | The service or the staff member is gone or inactive. | Load the services again. |
| 409 | `slot_taken` | The time is no longer free. Someone was faster, or the shop changed its hours. | Ask for the free times again and let the customer pick another. |
| 429 | `limit_reached` | Too many bookings from this address or for this person, or the customer already holds as many open bookings as the shop allows. | Say so. Do not retry in a loop. `Retry-After` says how long when the limit is per address or per person. |
| 503 | `bookings_paused` | The shop paused online booking. | Show the shop's phone number. |

A visitor's limits are the same as on the shop's own booking form. Today they are 10 booking requests an hour from one address, 5 bookings an hour for one phone number, 3 for one email, and 4 open bookings from one address. Every key also has its 120 requests a minute. See [Rate limits](https://developers.weerom.com/docs/rate-limits).

## What the customer gets

The booking is the same as one made on the shop's own site:

- The shop's confirmation mail, in the shop's look and in `locale`, with a button to manage the booking. From there the customer can move or cancel it under the shop's rules. Your page needs no screen for that.
- The reminder mail before the appointment, unless you sent `remind_by_email: false`.
- Staff get their usual notice of a new booking, and the booking shows in the agenda.
- A deal or a loyalty card the customer has applies to the price, as on the shop's own site.

## From a server instead

The same calls work from your server with a write key. Two things change:

- The visitor's limits do not apply, so your server must stop abuse itself, for example with its own limit per address.
- A write key may send `"as": "staff"`. That books as the shop. It skips the lead time, the limit on how far ahead, the paused switch, the cap on open bookings and a block on the customer. It needs no email and no last name, and it applies no deal. Leave it out for a page customers use, so the shop's rules hold.

A write key reads every customer and every booking. Keep it on the server. [An assistant that books](https://developers.weerom.com/docs/use-cases/assistant) shows this setup.
