# Rules for AI assistants

You are building a booking flow for a static HTML/CSS website with the Callyndar Booking API v1. Always follow these rules:

1. Only use endpoints, fields and values that are in this document. Invent nothing; if something is not in here, it does not exist.
2. Send the publishable key only as the header `Authorization: Bearer cal_pk_live_…`, never in the URL. Put no other keys or secrets in the code.
3. Use a new `Idempotency-Key` (for example `crypto.randomUUID()`) per booking attempt on `POST /bookings`; reuse the same key only to repeat exactly the same attempt.
4. On `409 slot_unavailable` or `hold_expired`: fetch the times again with `GET /availability` and let the visitor pick again.
5. Dates (`YYYY-MM-DD`) and times (`HH:MM`) are always venue-local time (`timezone` from `GET /venue`). Do not convert to the visitor's timezone.
6. Send the Turnstile token in `turnstile_token` on `POST /bookings` and `POST /holds/{id}/deposit` when `venue.turnstile_required` is true (site key: `venue.turnstile_site_key`); that optional Callyndar Turnstile is off by default. Protect the booking form against bots yourself in any case (your own captcha or Turnstile): that is the site builder's job.
7. Show the links `venue.privacy_url` and `venue.terms_url` next to the booking button.
8. Store no guest data in `localStorage`, `sessionStorage` or cookies (only a random `session_id`).
9. Show price and duration only as the API returns them (`price_cents: null` = price hidden). Never calculate a price, duration or deposit yourself.
10. Show a countdown to the hold's `expires_at`, and release the time with `DELETE /holds/{id}` when the visitor goes back.
11. When `hold.deposit.required` is true: first `POST /holds/{id}/deposit`, pay with Stripe.js (Payment Element with `stripeAccount`), then `POST /bookings` with `payment_intent_id`. After a redirect payment (iDEAL, Bancontact): `POST /bookings/recover`.
12. Use `textContent` (not `innerHTML`) to put API data on the page.
13. On an error show `error.message`; react to `error.code` as described in "Errors and limits".

---

# Callyndar API for custom websites

Build the booking flow of a Callyndar venue into your own HTML/CSS site, with no server and no widget.

With the Callyndar Booking API, a static website (HTML, CSS and a little JavaScript) can do exactly what the Callyndar booking widget does, but in your own design:

- the venue, opening hours and the required privacy and terms links;
- services, variants and prices (salon, barber, clinic) or the party size (restaurant);
- staff members, including "no preference";
- open and closed days, and the free times per day;
- holding a time with a countdown, the guest's details, an optional deposit and the booking itself.

The API deliberately does nothing more: it cannot retrieve, change or cancel bookings (the guest does that through the link in their confirmation email), and it exposes no customer data and no management functions.

## Quickstart in 5 steps

1. **Create a key.** The owner (or anyone with write access to Integrations) creates a publishable key at `/integrations` → "API & own website" (*API & eigen website*): `cal_pk_live_…`.
2. **Add a domain.** Put the exact domain of the site on the key, for example `https://www.salon-voorbeeld.be`. While building, you can turn on "Allow localhost" (*Localhost toestaan*).
3. **Show services.** `GET /api/v1/venue` and `GET /api/v1/services` give you everything you need to draw the first screen.
4. **Pick a time.** `GET /api/v1/calendar` colors the calendar, `GET /api/v1/availability` returns the free times of one day, and `POST /api/v1/holds` holds the chosen time.
5. **Book.** `POST /api/v1/bookings` with the guest's details and a new `Idempotency-Key` (plus a Turnstile token if the key asks for one). Protecting your form against bots is up to you, with your own captcha or Turnstile. Done: the booking appears in the calendar with source "API" and the guest receives their confirmation email.

```js
const res = await fetch('https://www.callyndar.com/api/v1/services', {
  headers: { Authorization: 'Bearer cal_pk_live_YOUR_KEY' },
});
const { services } = await res.json();
```

Want to try it right away? Follow the [5-minute quickstart](/developers/en/quickstart). Then read [Getting started](/developers/en/getting-started) and [The booking flow](/developers/en/booking-flow).

## Example to copy

- [`boeking.html`](/developers/voorbeeld/boeking.html): a single HTML file with the complete flow (services → staff member → day → times → hold with countdown → details (+ Turnstile if the key asks for it) → optional deposit → confirmation). Deliberately minimal CSS with clear `class` names: style it in your own design.
- [`callyndar-api.js`](/developers/voorbeeld/callyndar-api.js): a small `fetch` wrapper (ES module) with error handling, `Idempotency-Key` and a hold timer.

At `/integrations` you can download `boeking.html` with the venue's key already filled in.

## Working with an AI assistant?

Give your assistant one URL: [`/developers/en/llms-full.txt`](/developers/en/llms-full.txt). It contains all the docs, the reference, the rules and the complete example in a single file. Every page also exists as Markdown (for example `/developers/en/booking-flow.md`), and the machine-readable spec is at `/api/v1/openapi.json`.

Copyable prompt:

```text
Build a booking flow with the Callyndar API for this static HTML/CSS site.
First read https://www.callyndar.com/developers/en/llms-full.txt and follow the "Rules for AI assistants" in it.
Use only endpoints and fields from that documentation.
Publishable key: cal_pk_live_YOUR_KEY
API base: https://www.callyndar.com/api/v1
Style: use the existing CSS and layout of this site.
```

## All pages

- [5-minute quickstart](/developers/en/quickstart): key → venue → availability → hold → booking with curl
- [Getting started](/developers/en/getting-started): key, domains, bot protection, first call
- [The booking flow](/developers/en/booking-flow): salon and restaurant, step by step
- [Deposits](/developers/en/deposits): Stripe Payment Element and recovery after a redirect
- [Reference](/developers/en/reference): all endpoints, fields and errors
- [Errors and limits](/developers/en/errors-and-limits): error codes, rate limits and idempotency
- [Security](/developers/en/security): what may and may not go in your HTML
- [Testing](/developers/en/testing): local development and test cards
- [Changelog](/developers/en/changelog)

---

# 5-minute quickstart

From key to booking with five curl commands: venue, services, free times, hold and booking.

All you need is a terminal. A request without an `Origin` header always works, so you do not need a domain on the key yet. Prefer the browser? Every endpoint in the [API reference](/developers/en/reference) has a **Try it** button.

> Step 5 creates a real booking in the venue's calendar, with a confirmation e-mail. Use a test venue and your own e-mail address (see [Testing](/developers/en/testing#a-test-venue)), and cancel the booking afterwards through `manage_url`.

## 1. Set up your key

Create a publishable key on `/integrations` → **API & own website** (*API & eigen website*) (see [Getting started](/developers/en/getting-started)) and put it in your terminal:

```bash
export CALLYNDAR_KEY='cal_pk_live_YOUR_KEY'
export API='https://www.callyndar.com/api/v1'
```

## 2. Fetch the venue

```bash
curl "$API/venue" -H "Authorization: Bearer $CALLYNDAR_KEY"
```

Look at three fields: `venue.booking_mode` (`"services"` for salons, barbers, clinics and car washes; `"party_size"` for restaurants), `venue.timezone` (all dates and times are venue-local) and `venue.booking.phone_required`.

## 3. Pick a service and a day

Salon, barber, clinic or car wash: take an `id` from the services.

```bash
curl "$API/services" -H "Authorization: Bearer $CALLYNDAR_KEY"
export SERVICE_ID='…'   # services[0].id
```

Then ask for the free times of one day. A restaurant leaves out `service_ids` and sends `party_size`.

```bash
curl "$API/availability?date=2026-12-04&service_ids=$SERVICE_ID" \
  -H "Authorization: Bearer $CALLYNDAR_KEY"
```

You get `slots[]` with `time`, `end_time` and `available`. When `slots` is empty, `reason` says why (for example `closed_day`). Find an open day with `GET /calendar`.

## 4. Hold the time

```bash
curl -X POST "$API/holds" \
  -H "Authorization: Bearer $CALLYNDAR_KEY" \
  -H "Content-Type: application/json" \
  -d '{"date":"2026-12-04","time":"14:30","service_ids":["'"$SERVICE_ID"'"],"session_id":"quickstart-0001"}'
```

The answer has `hold_id` and `expires_at`. Until then the time is held for you (`capacity_reserved: true`). Changed your mind? Release it with `DELETE /holds/{id}`.

When `deposit.required` is true, a deposit comes first: see [Deposits](/developers/en/deposits).

## 5. Book

```bash
curl -X POST "$API/bookings" \
  -H "Authorization: Bearer $CALLYNDAR_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: $(uuidgen)" \
  -d '{"hold_id":"HOLD_ID_FROM_STEP_4","guest":{"first_name":"Test","last_name":"Guest","email":"you@example.com","phone":"+32 470 12 34 56"}}'
```

`booking.status` is `confirmed` (booked) or `pending` (the venue still confirms it). The guest gets a confirmation e-mail, and `booking.manage_url` is the page where they cancel or reschedule.

## Next steps

- [The booking flow](/developers/en/booking-flow): the same path with screens, variants, staff and a restaurant.
- [Errors and limits](/developers/en/errors-and-limits): what your site does on `slot_unavailable`, `hold_expired` and the rest.
- [`boeking.html`](/developers/voorbeeld/boeking.html): the complete flow in one HTML file to copy.

---

# Getting started

Create a key, set up domains, protect your form against bots and make your first call.

## 1. Create a key

A key belongs to exactly one venue. The key determines the venue: a venue ID never appears in the URL.

1. Sign in as the venue owner, or as a team member or partner with write access to the **Integrations** (*Integraties*) page.
2. Go to `/integrations` → the **API & own website** (*API & eigen website*) card → **Create key** (*Sleutel aanmaken*).
3. Copy the key `cal_pk_live_…`. You can copy it again later.

The API works from the **Starter** plan. On a free plan, or for a stopped or inactive venue, every call returns `403 not_enabled`. Exception: venues that run through a partner (reseller) keep using the API on the free plan too, within that plan's monthly limit (20 bookings). Once that limit is reached, `POST /bookings` returns `403 not_enabled` with `details.reason = "booking_limit"`. A venue that a partner is still setting up as a draft already answers read calls but not yet holds and bookings (`details.reason = "venue_in_setup"`, see [Testing](/developers/en/testing#during-the-setup-phase)).

There is one active key per venue. With **Rotate** (*Roteren*) you get a new key and the old one keeps working for another 24 hours (or you revoke it right away), so you can update the site without pressure.

## 2. Allowed domains

On the key you set the domains the site runs on, exactly as the browser sends them as `Origin`:

| Input | Meaning |
|---|---|
| `https://www.salon-voorbeeld.be` | exactly this domain |
| `https://salon-voorbeeld.be` | the domain without `www` (add it separately) |
| `https://*.salon-voorbeeld.be` | any subdomain, but not `salon-voorbeeld.be` itself |

- `https://` only. No paths (`/boeken`), no `http://`.
- **Allow localhost** (*Localhost toestaan*, on/off on the key) permits `http://localhost:*` and `http://127.0.0.1:*` while you build. Turn it off as soon as the site is live.
- If a call comes from the browser of another domain, the API responds with `403 forbidden_origin` without CORS headers. The browser then shows a CORS error in the console.

## 3. Bot protection

**Protecting your form against bots is your job as the site builder.** Put your own captcha or your own Cloudflare Turnstile on the booking form, as you would on any form on your site. On top of that, the API already checks domains, limits per key and per visitor, and all booking rules (see [Security](/developers/en/security)).

**Optional: Callyndar's Turnstile per key.** The owner can turn on **Bot check (Turnstile)** (*Botcontrole (Turnstile)*) on the key; it is off by default. When it is on, booking (`POST /bookings`) and starting a deposit (`POST /holds/{id}/deposit`) require a Turnstile token from Callyndar's widget. `GET /venue` tells you whether that is the case with `turnstile_required`, and gives you the `turnstile_site_key` you then have to use:

```html
<script src="https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit" async defer></script>
<div id="turnstile"></div>
```

```js
const widgetId = turnstile.render('#turnstile', {
  sitekey: venue.turnstile_site_key,
  callback: (token) => { turnstileToken = token; },
});
// after a failed attempt: turnstile.reset(widgetId)
```

A token can be used once. After a `turnstile_failed` error, call `turnstile.reset()` and send the new token.

If you use this option, Callyndar has to add every domain of your site to its Turnstile widget. Pass the domain on to Callyndar. If `turnstile_required` is `false`, simply omit `turnstile_token`.

## 4. Your first call

Always send the key in the `Authorization: Bearer …` header. A key in the URL (`?key=`) does not work: it would end up in logs.

```js
const API = 'https://www.callyndar.com/api/v1';
const KEY = 'cal_pk_live_YOUR_KEY';

const res = await fetch(`${API}/venue`, { headers: { Authorization: `Bearer ${KEY}` } });
if (!res.ok) {
  const { error } = await res.json();
  throw new Error(`${error.code}: ${error.message}`);
}
const { venue } = await res.json();
console.log(venue.name, venue.timezone, venue.booking_mode);
```

What you get back:

- `booking_mode`: `"services"` (salon, barber, clinic: services → staff member → time) or `"party_size"` (restaurant: party size → time).
- `timezone`: all dates (`YYYY-MM-DD`) and times (`HH:MM`) in the API are the **venue's local time**.
- `privacy_url` and `terms_url`: must be shown next to the booking button.
- `booking`: the venue's rules (min/max party size, days ahead, whether a phone number is required, whether deposits are enabled).

## Next step

Read [The booking flow](/developers/en/booking-flow), or open the example [`boeking.html`](/developers/voorbeeld/boeking.html) and fill in your key.

---

# The booking flow

Step by step from the first screen to the confirmation, for a salon and for a restaurant.

All calls go to `https://www.callyndar.com/api/v1` with the header `Authorization: Bearer cal_pk_live_YOUR_KEY`. Dates are `YYYY-MM-DD`, times `HH:MM`, always in the venue's time zone (`venue.timezone`). Show price and duration only as the API returns them.

## 0. Load the venue

`GET /venue` tells you which flow you are building:

| `venue.booking_mode` | Sector | Flow |
|---|---|---|
| `services` | salon, barber, clinic | services → (variant) → staff member or "no preference" → day → time |
| `party_size` | restaurant (and others) | party size → day → time |

Also keep `venue.booking` (rules), `venue.privacy_url`, `venue.terms_url`, `venue.turnstile_site_key` and `venue.turnstile_required`.

## Salon variant

### 1. Services and variants

`GET /services` returns `categories` (with `parent_id`, for a tree) and `services`. Per service:

- `duration_minutes`, `price_cents` (`null` = the venue hides the price; show nothing or `price_note`), `deposit_cents`.
- `variants`: choices such as "short / medium / long", each with its own duration and price.
- `duration_min_minutes`, `duration_max_minutes`, `price_from_cents`: what to show in your list. With variants, the shortest and longest duration and the lowest price ("30–60 min · from € 35"; one value when they are equal); otherwise the service's own values. Don't show the service's base duration and price next to variants.
- `variant_mode`:
  - `"customer"`: let the guest choose a variant (`variant_question` and `help_text` help with that).
  - `"staff"`: the venue decides later. The guest chooses nothing; you send the service along in `pending_ids`.
  - `null`: no variants.
- `allow_service_combos`: `false` means one service per booking.
- `required_providers`: how many staff members the service needs at the same time (usually 1). With 2 or more it is a **duo treatment**: you always book it on its own (never together with other services, otherwise `422 invalid_input` with `reason: "multi_staff_combo"`) and the venue assigns the extra staff members.

You send the selection along in every following call in the same way:

- `service_ids`: the chosen services, in the order they were chosen.
- `variant_ids`: per position in `service_ids` the chosen variant, or `null`. In a query string: comma-separated with empty slots, e.g. `variant_ids=aaa,,bbb`.
- `pending_ids`: the services with `variant_mode: "staff"`.

The server always calculates the appointment duration itself from this selection.

### 2. Staff member

`GET /providers?service_ids=<id>,<id>` returns the staff members who can do **all** chosen services. Always show the option **"No preference"** as well: in that case you send no `provider_id` and Callyndar picks the first free staff member.

### 3. Day

`GET /calendar?from=2026-12-01&to=2026-12-31&provider_id=<id>` (max. 92 days) returns per day `open: true|false` with a `reason`:

| `reason` | Meaning |
|---|---|
| `past` | in the past |
| `weekly_closed` | regular closing day |
| `online_day_disabled` | open, but not bookable online |
| `holiday` | public holiday or closure (`message` = label) |
| `day_block` | the venue blocked the day (`message` = the owner's message, show it) |
| `beyond_max_advance` | further out than the venue allows online booking |
| `provider_leave` | the chosen staff member is on leave |
| `provider_not_working` | the chosen staff member does not work that day (schedule) |

### 4. Time

`GET /availability?date=2026-12-04&service_ids=<id>&variant_ids=<id>&provider_id=<id>` returns `slots`:

```json
{ "date": "2026-12-04", "duration_minutes": 45, "required_providers": 1,
  "slots": [{ "time": "10:30", "end_time": "11:15", "next_day": false, "available": 2, "provider_ids": ["…"] }],
  "reason": null, "reason_params": null }
```

No times? Then `reason` says why (e.g. `same_day_closed`, `online_booking_hours` with `reason_params.from/until`, or `not_enough_staff` with `reason_params.n` when the team is too small for a duo treatment). If `reason` is `null` and there are no slots, the day is fully booked.

- Duo treatment (`required_providers` ≥ 2): `available` = how many such appointments still fit at that moment; a chosen `provider_id` is the lead staff member.
- If the venue hides the number of free places, `available` is always `1` and `provider_ids` is empty. Then don't show "X left".

## Restaurant variant

1. **Party size**: between `venue.booking.min_party_size` and `max_party_size`.
2. **Day**: `GET /calendar` as above (without `provider_id`).
3. **Time**: `GET /availability?date=2026-12-04&party_size=4`. `available` = free places.

For a restaurant, never send `provider_id` (that returns `422 invalid_input`).

## 5. Hold the time

As soon as the guest picks a time:

```js
const hold = await api('/holds', { method: 'POST', body: {
  date: '2026-12-04', time: '10:30', party_size: 1,
  service_ids: [serviceId], variant_ids: [variantId], pending_ids: [],
  provider_id: providerId,           // omit or null = no preference
  session_id: sessionId,             // one random ID per visitor/tab
}});
```

- `session_id`: create one per visitor with `crypto.randomUUID()` and store it in `sessionStorage` at most. A new hold from the same session replaces the previous one.
- The server checks the time again against all rules (opening hours, blocks, holidays, capacity, service rules). If it is gone: `409 slot_unavailable` → fetch the times again.
- Response: `hold_id`, `expires_at`, `capacity_reserved`, `end_time`, `duration_minutes`, `provider_id`, `extra_provider_ids` (for a duo treatment the extra staff members, otherwise empty) and `deposit: { required, amount_cents, currency }`.
- A duo treatment always gets a real hold (`capacity_reserved: true`), even at a venue that otherwise works without holds.

**`capacity_reserved`**

- `true`: the time is really held for you until `expires_at`. Show a countdown ("Your time stays reserved for 4:59").
- `false`: the venue works without holds (or with table management). The time was free at the check, but is not held; `hold_id` then starts with `nh_`. The flow stays the same, only the text next to the countdown changes ("Complete your booking within 5 minutes").

If the guest goes back or closes the flow, release the time: `DELETE /holds/{hold_id}`. After `expires_at` you request a new hold.

## 6. Guest details

Ask for first name, last name, email, optionally phone and notes.

- Phone is required if `venue.booking.phone_required` is `"always"`, or `"conditional"` and the party size ≥ `phone_required_min_party_size`.
- Next to the booking button, always show the **privacy and terms notice** with links to `venue.privacy_url` and `venue.terms_url`, for example: "By booking you agree to the terms and the privacy policy of {venue}."
- Don't store guest details in `localStorage` or cookies.

**Booking for a company (optional).** If the guest wants an invoice made out to a company, send a `company` block: `name` (required), `vat_number` (VAT number with country prefix; spaces and dots are fine) and `reference` (purchase order or reference). A VAT number in the wrong format gives `400 invalid_input` on `company.vat_number`. Whether the number really exists is checked by Callyndar against EU VIES after the booking; if VIES is unreachable, the booking still goes through. Leave the block out for a private booking.

Does a deposit have to be paid (`hold.deposit.required`)? Then read [Deposits](/developers/en/deposits) first.

## 7. Book

```js
const res = await fetch(`${API}/bookings`, {
  method: 'POST',
  headers: {
    Authorization: `Bearer ${KEY}`,
    'Content-Type': 'application/json',
    'Idempotency-Key': crypto.randomUUID(),   // new per booking attempt
  },
  body: JSON.stringify({
    hold_id: hold.hold_id,
    guest: { first_name: 'An', last_name: 'Peeters', email: 'an@example.com', phone: '+32 470 12 34 56' },
    notes: 'A seat by the window, please',
    locale: 'nl',
    // company: { name: 'TEST Studio BV', vat_number: 'BE0123456749', reference: 'PO-118' },   optional
    turnstile_token: turnstileToken,
    // payment_intent_id: 'pi_…'   only after a deposit
  }),
});
```

The services, variants and staff member come from the hold; you don't send them again.

Response (`201`):

```json
{ "booking": { "id": "…", "status": "confirmed", "date": "2026-12-04", "time": "10:30", "end_time": "11:15",
  "party_size": 1, "provider_id": "…", "extra_provider_ids": [],
  "services": [{ "id": "…", "name": "Women's haircut", "variant_id": null, "variant_name": null, "duration_minutes": 45, "price_cents": 3500 }],
  "deposit_paid": false, "manage_url": "https://www.callyndar.com/r/…" } }
```

| `status` | What you show |
|---|---|
| `confirmed` | "Your booking is confirmed. You will receive an email." |
| `pending` | "Your request has been received. The venue will confirm it as soon as possible." |
| `waitlisted` | "It is fully booked; you are on the waitlist. The venue will contact you." |

Show the `manage_url`: the guest can cancel or reschedule there (the same link is in their confirmation email). Cancelling or rescheduling through the API is not possible.

## When things go wrong

- `409 slot_unavailable` or `409 hold_expired`: fetch `GET /availability` again and let the guest choose another time.
- `403 turnstile_failed`: `turnstile.reset()` and try again.
- `409 deposit_required`: start the deposit.
- `429 rate_limited`: wait `Retry-After` seconds.

All codes are in [Errors and limits](/developers/en/errors-and-limits).

---

# Deposits

Collect a deposit with the Stripe Payment Element on your own site, and complete the booking after a redirect (iDEAL, Bancontact).

Deposits only work if the venue has activated online payments (Stripe connected at `/integrations`). `GET /venue` shows this with `venue.booking.deposits_enabled`. The money goes straight to the venue (a direct charge on its Stripe account); you never touch card details.

## Does anything have to be paid?

- Up front (to show the price): `GET /deposit-policy?party_size=2&service_ids=…&variant_ids=…` → `{ required, amount_cents, currency, refund_window_hours }`.
- At the hold: `POST /holds` returns `deposit: { required, amount_cents, currency }`. That is the amount that counts.

A booking that requires a deposit never succeeds without one: `POST /bookings` without a valid payment returns `409 deposit_required`.

## The flow

1. **Hold** as always (`POST /holds`).
2. **Collect the guest's details** + Turnstile token.
3. **Start the payment**:

```js
const pay = await api(`/holds/${hold.hold_id}/deposit`, { method: 'POST', body: {
  guest: { first_name, last_name, email, phone },
  notes, locale: 'nl',
  turnstile_token: turnstileToken,
}});
// → { payment_intent_id, client_secret, amount_cents, currency, stripe_publishable_key, stripe_account }
```

The server checks the time again before a payment is created. The guest's details are stored with the payment, so the booking can be completed after a redirect.

4. **Show the Payment Element** with Stripe.js, on the venue's account:

```html
<script src="https://js.stripe.com/v3/"></script>
<div id="payment-element"></div>
```

```js
const stripe = Stripe(pay.stripe_publishable_key, { stripeAccount: pay.stripe_account });
const elements = stripe.elements({ clientSecret: pay.client_secret });
elements.create('payment').mount('#payment-element');

const { error, paymentIntent } = await stripe.confirmPayment({
  elements,
  redirect: 'if_required',
  confirmParams: { return_url: window.location.href.split('?')[0] },
});
if (error) { /* show error.message */ }
else if (paymentIntent.status === 'succeeded') { /* step 5 */ }
```

5. **Book** with the payment:

```js
await book({ hold_id: hold.hold_id, guest, notes, locale: 'nl',
             payment_intent_id: pay.payment_intent_id, turnstile_token: nieuwToken });
```

Turnstile tokens are single-use: render the widget again (or `turnstile.reset()`) before the booking call.

**Paid, but the hold has expired in the meantime?** (e.g. 3D Secure took a long time) `POST /bookings` then returns `409 hold_expired`. **Never** send a guest who has already paid back to the time selection: complete the booking with `POST /bookings/recover` and the `payment_intent_id` (see below). It books the time again if it is still free.

## Recovery after a redirect (iDEAL, Bancontact)

With some payment methods the guest leaves your site and comes back to your `return_url` with `?payment_intent=pi_…&redirect_status=succeeded` in the URL. Your JavaScript variables are then gone. Complete the booking with:

```js
const params = new URLSearchParams(location.search);
const pi = params.get('payment_intent');
if (pi) {
  const { booking } = await api('/bookings/recover', { method: 'POST', body: { payment_intent_id: pi } });
  // show the confirmation
}
```

- Only works for payments started with the **same key**; otherwise `404 not_found`.
- Already booked? Then you get the same booking back (`200`). A new booking returns `201`.
- Not paid yet (e.g. `processing`): `409 deposit_required` with `details.reason = "not_paid"`. Try again after a few seconds.
- If the time is gone in the meantime (the hold expired during a long payment), the payment is **not** used: `409 slot_unavailable`. Ask the guest to contact the venue; the venue can refund the deposit.

## Testing

Use a venue with a Stripe account in **test mode** and Stripe's test cards:

| Card | Result |
|---|---|
| `4242 4242 4242 4242` | succeeds |
| `4000 0025 0000 3155` | requires 3D Secure |
| `4000 0000 0000 9995` | declined (insufficient funds) |

Any future expiry date and any CVC work. For iDEAL and Bancontact, choose "Authorize" on Stripe's test page.

Apple Pay and Google Pay require your site's domain to be registered with the venue's Stripe account; check with Callyndar before you offer them.

---

# Multiple locations

A custom website for a venue with more than one location: one key per location, and the visitor first chooses where to book.

## One key per location

For the API, every location is a separate venue. A key belongs to exactly one location and determines which location you read and book. There is no key for all locations together and no location ID in the URL.

1. At the top of the dashboard, choose the location (the location switcher).
2. Go to `/integrations` → **API & own website** (*API & eigen website*) → **Create key** (*Sleutel aanmaken*), as in [Getting started](/developers/en/getting-started).
3. Repeat this for every location. Put the same domains of your site on every key.

Every key has its own limits, domain list and bot check. `GET /venue` with a key returns the name, address and opening hours of that one location.

## On your site

First let the visitor choose a location, then use that location's key for every call of that booking: services, availability, hold and booking.

```js
const KEYS = {
  centrum: 'cal_pk_live_…', // key of the Centrum location
  noord: 'cal_pk_live_…',   // key of the Noord location
};

function apiFor(location) {
  const key = KEYS[location];
  return (path, init = {}) => fetch(`https://www.callyndar.com/api/v1${path}`, {
    ...init,
    headers: { 'Authorization': `Bearer ${key}`, 'Content-Type': 'application/json', ...(init.headers ?? {}) },
    body: init.body ? JSON.stringify(init.body) : undefined,
  }).then(r => r.json());
}

// The visitor chose "centrum":
const api = apiFor('centrum');
const venue = await api('/venue');
```

If a partner sets up a new location as a draft, that location's key already works for reading, but it rejects holds and bookings (`venue_in_setup`) until the owner activates the venue. See [Testing](/developers/en/testing#during-the-setup-phase).

Never switch keys in the middle of one booking: a hold from the Centrum location does not exist for the Noord key.

## Staff members who work at multiple locations

If the same staff member works at two locations, the API takes that into account. If that person has an appointment at the Noord location, they are unavailable at the Centrum location at that time: not in `GET /availability`, and a `POST /holds` or `POST /bookings` at that time is rejected like any other occupied time. You don't need to do anything for this.

## What is not (yet) possible

- One key that serves all locations of a venue together.
- An endpoint that lists a venue's locations. For now, put the list of locations in your site yourself.

This may be added in a later version of v1; see the [Changelog](/developers/en/changelog).

---

# Errors and limits

The error format, all error codes and what your site does about them, the rate limits and the Idempotency-Key.

## Error format

Every error has the same shape, with the HTTP status of the code:

```json
{
  "error": {
    "code": "slot_unavailable",
    "message": "This time is not available. Fetch the times again.",
    "details": { "reason": "full" },
    "request_id": "req_8Kq2…"
  }
}
```

- Decide on `code`, not on `message` (the text may change).
- `details` is optional. For `invalid_input` it contains `details.fields`, a list of messages per field. For `not_enabled`, `details.reason` sometimes says why: `plan` (plan lower than Starter), `booking_limit` (monthly limit reached) or `venue_in_setup` (venue still in the setup phase).
- Every response (successful ones too) has the header `Callyndar-Request-Id`. Include it when you ask Callyndar for help.
- With a `server_error` you never get internal details; those are in Callyndar's logs under the `request_id`.

## Error codes

| Code | HTTP | Meaning | What does your site do? |
|---|---|---|---|
| `unauthorized` | 401 | No key, an unknown key or a revoked key. | Check the key on /integrations; a revoked key never works again. |
| `forbidden_origin` | 403 | The page's Origin is not on the key's domain list. | Add the domain to the key (exactly https://domain) or switch on "allow localhost" while building. |
| `not_enabled` | 403 | Online booking through the API is not available for this venue (plan below Starter, venue inactive or stopped, monthly limit reached, or a server setting is missing). A venue a partner is still setting up answers this on every write with details.reason "venue_in_setup"; reads do work. | Show a friendly message and point to the venue's phone or e-mail. With "venue_in_setup": wait until the owner has activated the venue. |
| `turnstile_failed` | 403 | The Turnstile token is missing, expired or already used. | Let the visitor do the Turnstile check again (turnstile.reset) and send the new token. |
| `not_found` | 404 | The hold, payment or route does not exist for this key. | Start again at picking a time. |
| `method_not_allowed` | 405 | This HTTP method does not exist on this path. | Use the method from the reference. |
| `invalid_input` | 422 | The request does not match the schema (details lists the fields). | Fix the fields from details.fields; do not resend the same request unchanged. |
| `slot_unavailable` | 409 | The chosen time is not (or no longer) bookable. | Fetch the times again with GET /availability and let the visitor pick another time. |
| `hold_expired` | 409 | The hold or slot confirmation expired, was already used or was released. | Request a new hold with POST /holds (the time may still be free). |
| `deposit_required` | 409 | This booking needs a deposit, or the payment sent along is not (yet) valid. | Start the deposit with POST /holds/{id}/deposit, then book with payment_intent_id. |
| `idempotency_conflict` | 409 | The same Idempotency-Key was used with a different body, or the first request is still running. | Use a new Idempotency-Key per booking attempt; with Retry-After, wait and try again. |
| `payload_too_large` | 413 | The body is larger than 16 KB. | Send only the fields from the reference. |
| `rate_limited` | 429 | Too many requests (per key or per visitor). | Wait the number of seconds from the Retry-After header. |
| `server_error` | 500 | Unexpected error on Callyndar's side. | Try again later; mention the request_id if it keeps happening. |

### Limits (generated)

All routes together: 600 requests per minute per key. At most 50 active holds per key at once.

| Write route | per key / min | per key + visitor IP / min |
|---|---|---|
| POST /holds | 120 | 30 |
| DELETE /holds/{id} | 240 | 60 |
| POST /bookings | 60 | 20 |
| POST /holds/{id}/deposit | 30 | 10 |
| POST /bookings/recover | 60 | 20 |

## Rate limits

| What | Limit |
|---|---|
| Per key, all routes combined | 600 requests per minute |
| Per visitor IP, all routes combined | 300 requests per minute |
| `POST /holds` | 120 per minute per key, 30 per minute per visitor |
| `DELETE /holds/{id}` | 240 per minute per key, 60 per minute per visitor |
| `POST /bookings` | 60 per minute per key, 20 per minute per visitor |
| `POST /holds/{id}/deposit` | 30 per minute per key, 10 per minute per visitor |
| `POST /bookings/recover` | 60 per minute per key, 20 per minute per visitor |
| Active holds at once | max. 50 per key |

"Per visitor" is the real IP address of the browser making the call. Above a limit you get `429 rate_limited` with the `Retry-After` header (seconds). Wait at least that long before trying again, and show the visitor a calm message ("One moment, please try again shortly").

Tip: fetch `/venue` and `/services` once per visit and keep them in a variable; only request `/availability` when the guest picks a day.

## Idempotency-Key

`POST /bookings` requires the `Idempotency-Key` header (8–128 characters: letters, digits and `. _ -`). Create a new one per **booking attempt**, e.g. `crypto.randomUUID()`.

- **Same key + same body**: you get the first response again (header `Idempotent-Replayed: true`). This lets you retry safely after a network error without booking twice. The `turnstile_token` does not count towards "same body": a retry with a new token is the same booking.
- **Same key + a different body**: `409 idempotency_conflict`.
- **The first request is still running**: `409 idempotency_conflict` with `Retry-After: 1`.
- Only **successful** responses are stored. After an error (e.g. `slot_unavailable`) you may reuse the same key; a hold only ever becomes one booking anyway.
- Keys expire after 24 hours.

## What your site does per situation

- **Time gone** (`slot_unavailable`, `hold_expired`): fetch the times again, let the guest choose a new time.
- **Deposit required** (`deposit_required`): start `POST /holds/{id}/deposit` and then book with `payment_intent_id`.
- **Bot check** (`turnstile_failed`): `turnstile.reset()` and try again.
- **Venue unavailable** (`not_enabled`): show the venue's phone number and email address from `/venue`.
- **Venue still in the setup phase** (`not_enabled` with `details.reason = "venue_in_setup"`): the partner is still setting up the venue and the owner has not activated it yet. Reading works, every write call (holds, deposit, booking) is rejected. Show "Online booking is coming soon"; see [Testing](/developers/en/testing#during-the-setup-phase).
- **Configuration** (`unauthorized`, `forbidden_origin`): this is an error in the site, not with the guest; check the key and domain list at `/integrations`.

---

# Security

What may go in your HTML, what never may, and what to do if a key is abused.

## A key in a static page: is that safe?

Yes. The publishable key (`cal_pk_live_…`) is **public by nature**, like Stripe's publishable key or a Google Maps key. Anyone can read it in the page source; that has been accounted for.

What a publishable key **can** do: exactly what an anonymous visitor can do with the Callyndar widget.

- read the venue, services, staff members, open days and free times;
- hold a time, start a deposit and make a booking.

What it **cannot** do:

- read guest details or customer lists;
- retrieve, change or cancel bookings (the guest does that through the link in their email);
- reach another venue (the key determines the venue);
- bypass a deposit, or manipulate price, duration or staff member (the server takes those from the database).

## Layers of defense (all server-side)

1. **One venue per key.** Guessing venue IDs is pointless.
2. **Domain list.** Another website cannot use your key in the browser of its visitors (`403 forbidden_origin`). Origin is not a password (a script outside the browser can forge it); hence the following layers. One exception: Callyndar's own origin is accepted for every key, so **Try it** in these docs works; that is not another website.
3. **All rules enforced again on the server**: opening hours, blocks, holidays, capacity, service rules and deposits, on every hold and every booking.
4. **Limits** per key and per visitor IP, across all servers, plus a maximum number of simultaneous holds.
5. **Bots**: your own captcha or Turnstile on the form (your responsibility as the site builder), and optionally per key Callyndar's Turnstile on booking and paying.
6. **Revoking takes effect immediately**: a revoked key returns `401` on the next call.

## What may go in your HTML/JS

- The publishable key `cal_pk_live_…`.
- The Turnstile site key (if the key asks for it) and the Stripe publishable key from the API responses.
- The site key of your own captcha or Turnstile (its secret key belongs on your own server, never in the HTML).

## What never goes in

- No other keys or secrets (no Stripe secret key, no passwords, no tokens from other services).
- Don't store guest details in `localStorage`, cookies or your own database. The guest fills them in, you send them to the API once, done. Only the `session_id` may go in `sessionStorage`.
- Don't store or log a payment's `client_secret`.
- Don't put API data into the page with `innerHTML`: use `textContent` (service names come from the venue, not from you).
- Don't send guest details or request bodies to analytics or error-logging tools.

## Maintaining the domain list

- Put only the site's own domains on the key, with `https://`.
- Use `https://*.domein.be` only if you really have multiple subdomains.
- Turn off "Allow localhost" (*Localhost toestaan*) as soon as the site is live.

## Abuse? Rotate the key

If you see bookings with source "API" in the calendar that don't belong there, or the owner reports spam:

1. Go to `/integrations` → **API & own website** (*API & eigen website*) → **Rotate** (*Roteren*).
2. Put the new key in the site and publish.
3. Revoke the old key (or let it expire by itself after 24 hours).

"Last used" and "last origin" on the card show whether the key is still being used anywhere.

## Privacy (GDPR)

The venue is the data controller, Callyndar is the processor. If you build the site on behalf of the venue, you also work on its behalf. Always show the privacy and terms links (`privacy_url`, `terms_url`) next to the booking button.

---

# Testing

Develop locally, test Turnstile and Stripe, and use a test venue.

## Developing locally

1. Turn on **Allow localhost** (*Localhost toestaan*) on the key. Then `http://localhost:<port>` and `http://127.0.0.1:<port>` work.
2. Serve your HTML through a local web server, not as `file://` (a page from disk sends `Origin: null` and is rejected). For example:

```sh
python3 -m http.server 5500
# or
npx serve .
```

3. Open `http://localhost:5500/boeking.html`.
4. Turn "Allow localhost" off again before the site goes live.

A call from the command line (without `Origin`) works too, handy for inspecting responses:

```sh
curl -H "Authorization: Bearer cal_pk_live_YOUR_KEY" https://www.callyndar.com/api/v1/venue
```

## A test venue

Don't book on a customer's real calendar while you build. Ask the owner to create a test venue (a second venue in the same account, with the same services) and create a separate key for it. Every test booking gets the normal confirmation email, so use your own email address.

You cancel test bookings on a real venue through the `manage_url` from the response.

## During the setup phase

If you create a client as a partner, that venue stays in the **setup phase** until the owner activates it (or, with a regular invitation, until the owner agrees). In that phase you can already create a key and build your site:

- **Reading works**: `GET /venue`, `/services`, `/providers`, `/calendar`, `/availability` and `/deposit-policy` respond normally, with the data you enter in the dashboard.
- **Writing is blocked**: `POST /holds`, `DELETE /holds/{id}`, `POST /holds/{id}/deposit`, `POST /bookings` and `POST /bookings/recover` return `403 not_enabled` with `details.reason = "venue_in_setup"`. So no bookings end up in the calendar of a venue that is not live yet.

```sh
curl -H "Authorization: Bearer cal_pk_live_YOUR_KEY" https://www.callyndar.com/api/v1/venue          # 200
curl -X POST -H "Authorization: Bearer cal_pk_live_YOUR_KEY" -H "Content-Type: application/json" \
  -d '{}' https://www.callyndar.com/api/v1/holds                                            # 403 venue_in_setup
```

On `venue_in_setup`, show a calm message on your site ("Online booking is coming soon"). As soon as the owner activates the venue, holds and bookings work with the same key, without changing anything. From then on the usual plan rule applies too (Starter or higher, see [Getting started](/developers/en/getting-started)).

You test the full booking path (hold, deposit, booking) after activation, or on a test venue as above.

## Turnstile

You test your own captcha or Turnstile like any other form on your site.

If Callyndar's optional Turnstile is on for the key (`turnstile_required: true`), always use the `turnstile_site_key` from `GET /venue`. It matches the secret key on Callyndar's side.

- In production that is Callyndar's real site key. Your site's domain must be added to that Turnstile widget (ask Callyndar), otherwise Turnstile shows an error.
- On a local or test installation of Callyndar, `/venue` returns Cloudflare's test site key `1x00000000000000000000AA`, which always passes. It only works together with the test secret of such an installation; in production a token from the test site key is rejected (`turnstile_failed`).

## Stripe

You test deposits on a venue whose Stripe account is in **test mode**. Test card `4242 4242 4242 4242`, a future expiry date and any CVC. More cards are listed under [Deposits](/developers/en/deposits).

## Go-live checklist

- [ ] The real venue's key is in the site, domain(s) are on the key, localhost is off.
- [ ] The form is protected against bots (own captcha or Turnstile). If you use Callyndar's Turnstile: domain added to Callyndar's Turnstile widget.
- [ ] Privacy and terms links are next to the booking button.
- [ ] A real test booking was made and cancelled through the `manage_url`.
- [ ] Error messages tested: time gone (`slot_unavailable`), hold expired (and Turnstile failed, if the key asks for it).
- [ ] The venue has been activated by the owner (no more `venue_in_setup` on `POST /holds`).
- [ ] No guest details in `localStorage`, no other secrets in the HTML.

---

# API reference

Every endpoint of API v1.4.0, generated from the OpenAPI document the API serves. Base URL: `https://www.callyndar.com/api/v1`. Authentication: `Authorization: Bearer <publishable key>` (except openapi.json). Machine-readable: [`/api/v1/openapi.json`](https://www.callyndar.com/api/v1/openapi.json).

## GET /venue

**Venue info and booking settings.** Name, contact details, timezone, opening hours, booking rules, privacy/terms links and the Turnstile site key.

**Response 200**

| Field | Type | Required | Description |
|---|---|---|---|
| `venue` | object | yes |  |
| `venue.name` | string | yes |  |
| `venue.description` | string \| null | yes |  |
| `venue.business_type` | "restaurant" \| "generic" \| "salon" \| "barber" \| "clinic" \| "carwash" | yes |  |
| `venue.booking_mode` | "party_size" \| "services" | yes | "services": pick services → staff or wash bay → time (salon, barber, clinic, carwash). "party_size": pick guests → time (restaurant). |
| `venue.address` | string \| null | yes |  |
| `venue.city` | string \| null | yes |  |
| `venue.country` | string \| null | yes |  |
| `venue.phone` | string \| null | yes |  |
| `venue.email` | string \| null | yes |  |
| `venue.website` | string \| null | yes |  |
| `venue.logo_url` | string \| null | yes | Absolute URL of the logo (or null). |
| `venue.timezone` | string | yes | IANA zone. All dates/times of the API are venue-local. |
| `venue.currency` | string | yes |  |
| `venue.default_locale` | "nl" \| "en" \| "fr" | yes | Language of the guest e-mails and the manage page. |
| `venue.opening_hours` | object[] | yes |  |
| `venue.opening_hours[].weekday` | integer | yes | 0 = Monday … 6 = Sunday. |
| `venue.opening_hours[].open` | boolean | yes |  |
| `venue.opening_hours[].periods` | object[] | yes |  |
| `venue.opening_hours[].periods[].from` | string | yes | Venue-local time, HH:MM (24h). |
| `venue.opening_hours[].periods[].until` | string | yes | Venue-local time, HH:MM (24h). |
| `venue.booking` | object | yes |  |
| `venue.booking.min_party_size` | integer | yes |  |
| `venue.booking.max_party_size` | integer | yes |  |
| `venue.booking.max_advance_days` | integer | yes |  |
| `venue.booking.holds_enabled` | boolean | yes | true: POST /holds really reserves the time (capacity_reserved). false: it returns a signed confirmation only. |
| `venue.booking.hold_seconds` | integer | yes |  |
| `venue.booking.auto_confirm` | boolean | yes |  |
| `venue.booking.auto_confirm_max_party_size` | integer \| null | yes |  |
| `venue.booking.cancellation_cutoff_hours` | integer \| null | yes |  |
| `venue.booking.allow_service_combos` | boolean | yes |  |
| `venue.booking.service_picker_mode` | "list" \| "guided" | yes |  |
| `venue.booking.phone_required` | "never" \| "always" \| "conditional" | yes |  |
| `venue.booking.phone_required_min_party_size` | integer | yes |  |
| `venue.booking.deposits_enabled` | boolean | yes | The venue can take online deposits (Stripe connected). |
| `venue.privacy_url` | string | yes | Show this link next to the booking button (GDPR notice, mandatory). |
| `venue.terms_url` | string | yes | Show this link next to the booking button (mandatory). |
| `venue.turnstile_site_key` | string \| null | yes | Callyndar Turnstile site key to render on your page when turnstile_required is true. |
| `venue.turnstile_required` | boolean | yes | The key asks for the optional Callyndar Turnstile token on bookings and deposits (off by default). |

**Errors:** `unauthorized` (401), `forbidden_origin` (403), `not_enabled` (403), `rate_limited` (429), `server_error` (500) — What your site does for each code is in [Errors and limits](/developers/en/errors-and-limits).

**Example**

```bash
curl 'https://www.callyndar.com/api/v1/venue' \
  -H 'Authorization: Bearer cal_pk_live_YOUR_KEY'
```

```js
const res = await fetch('https://www.callyndar.com/api/v1/venue', {
  headers: {
    Authorization: 'Bearer cal_pk_live_YOUR_KEY',
  },
});
const data = await res.json();
if (!res.ok) throw new Error(`${data.error.code}: ${data.error.message}`);
```

**Response 200 (example)**

```json
{
  "venue": {
    "name": "Studio Voorbeeld",
    "description": "Hair salon in the centre of Antwerp.",
    "business_type": "salon",
    "booking_mode": "services",
    "address": "Meir 1",
    "city": "Antwerpen",
    "country": "BE",
    "phone": "+32 3 123 45 67",
    "email": "hallo@studio-voorbeeld.be",
    "website": "https://www.studio-voorbeeld.be",
    "logo_url": "https://callyndar.com/media/logos/studio-voorbeeld.png",
    "timezone": "Europe/Brussels",
    "currency": "EUR",
    "default_locale": "nl",
    "opening_hours": [
      {
        "weekday": 0,
        "open": false,
        "periods": []
      },
      {
        "weekday": 1,
        "open": true,
        "periods": [
          {
            "from": "09:00",
            "until": "18:00"
          }
        ]
      },
      {
        "weekday": 2,
        "open": true,
        "periods": [
          {
            "from": "09:00",
            "until": "12:30"
          },
          {
            "from": "13:30",
            "until": "20:00"
          }
        ]
      },
      {
        "weekday": 3,
        "open": true,
        "periods": [
          {
            "from": "09:00",
            "until": "18:00"
          }
        ]
      },
      {
        "weekday": 4,
        "open": true,
        "periods": [
          {
            "from": "09:00",
            "until": "18:00"
          }
        ]
      },
      {
        "weekday": 5,
        "open": true,
        "periods": [
          {
            "from": "09:00",
            "until": "16:00"
          }
        ]
      },
      {
        "weekday": 6,
        "open": false,
        "periods": []
      }
    ],
    "booking": {
      "min_party_size": 1,
      "max_party_size": 1,
      "max_advance_days": 60,
      "holds_enabled": true,
      "hold_seconds": 600,
      "auto_confirm": true,
      "auto_confirm_max_party_size": null,
      "cancellation_cutoff_hours": 24,
      "allow_service_combos": true,
      "service_picker_mode": "list",
      "phone_required": "always",
      "phone_required_min_party_size": 1,
      "deposits_enabled": false
    },
    "privacy_url": "https://callyndar.com/sites/studio-voorbeeld/privacy",
    "terms_url": "https://callyndar.com/sites/studio-voorbeeld/terms",
    "turnstile_site_key": null,
    "turnstile_required": false
  }
}
```

## GET /services

**Services, categories and variants.** Everything the guest can pick, with duration, price and deposit as the venue set them.

**Response 200**

| Field | Type | Required | Description |
|---|---|---|---|
| `currency` | string | yes |  |
| `service_picker_mode` | "list" \| "guided" | yes |  |
| `allow_service_combos` | boolean | yes |  |
| `categories` | object[] | yes |  |
| `categories[].id` | string | yes |  |
| `categories[].parent_id` | string \| null | yes |  |
| `categories[].name` | string | yes |  |
| `categories[].sort_order` | integer | yes |  |
| `categories[].image_url` | string \| null | yes |  |
| `services` | object[] | yes |  |
| `services[].id` | string | yes |  |
| `services[].name` | string | yes |  |
| `services[].description` | string \| null | yes |  |
| `services[].category_id` | string \| null | yes |  |
| `services[].duration_minutes` | integer \| null | yes | Base duration of the service. For a service with variants, show duration_min_minutes–duration_max_minutes instead. |
| `services[].price_cents` | integer \| null | yes | null when the venue hides the price. Base price; for a service with variants, show price_from_cents instead. |
| `services[].duration_min_minutes` | integer \| null | yes | Shortest variant duration, or duration_minutes for a service without variants. Show "min–max min", or one value when both are equal. |
| `services[].duration_max_minutes` | integer \| null | yes | Longest variant duration, or duration_minutes for a service without variants. |
| `services[].price_from_cents` | integer \| null | yes | Lowest variant price ("from …"), or price_cents for a service without variants. null when the venue hides the price. |
| `services[].price_note` | string \| null | yes |  |
| `services[].deposit_cents` | integer \| null | yes | Deposit of this service (null without online payments). |
| `services[].variant_mode` | "customer" \| "staff" \| null | yes | "customer": the guest picks a variant. "staff": the venue decides later (send the service id in pending_ids). |
| `services[].variant_question` | string \| null | yes |  |
| `services[].required_providers` | integer | yes | Staff members this service needs at once (1 for most services). A service with 2 or more is a multi-staff treatment: it is booked on its own (never in a combination) and the venue assigns the extra staff. |
| `services[].variants` | object[] | yes |  |
| `services[].variants[].id` | string | yes |  |
| `services[].variants[].name` | string | yes |  |
| `services[].variants[].help_text` | string \| null | yes |  |
| `services[].variants[].duration_minutes` | integer \| null | yes |  |
| `services[].variants[].price_cents` | integer \| null | yes |  |
| `services[].variants[].deposit_cents` | integer \| null | yes |  |

**Errors:** `unauthorized` (401), `forbidden_origin` (403), `not_enabled` (403), `rate_limited` (429), `server_error` (500) — What your site does for each code is in [Errors and limits](/developers/en/errors-and-limits).

**Example**

```bash
curl 'https://www.callyndar.com/api/v1/services' \
  -H 'Authorization: Bearer cal_pk_live_YOUR_KEY'
```

```js
const res = await fetch('https://www.callyndar.com/api/v1/services', {
  headers: {
    Authorization: 'Bearer cal_pk_live_YOUR_KEY',
  },
});
const data = await res.json();
if (!res.ok) throw new Error(`${data.error.code}: ${data.error.message}`);
```

**Response 200 (example)**

```json
{
  "currency": "EUR",
  "service_picker_mode": "list",
  "allow_service_combos": true,
  "categories": [
    {
      "id": "2d7e9f1a-3c5b-4d8e-b6a1-0c2d3e4f5a6b",
      "parent_id": null,
      "name": "Haar",
      "sort_order": 0,
      "image_url": null
    }
  ],
  "services": [
    {
      "id": "5b6f0c3e-2a4d-4f1b-9c7e-1d2a3b4c5d6e",
      "name": "Knippen",
      "description": "Wassen, knippen en drogen.",
      "category_id": "2d7e9f1a-3c5b-4d8e-b6a1-0c2d3e4f5a6b",
      "duration_minutes": 45,
      "price_cents": 4500,
      "duration_min_minutes": 45,
      "duration_max_minutes": 45,
      "price_from_cents": 4500,
      "price_note": null,
      "deposit_cents": null,
      "variant_mode": null,
      "variant_question": null,
      "required_providers": 1,
      "variants": []
    },
    {
      "id": "8e1d4a72-6c3b-4e9f-a2d5-7f0b1c2d3e4f",
      "name": "Kleuren",
      "description": null,
      "category_id": "2d7e9f1a-3c5b-4d8e-b6a1-0c2d3e4f5a6b",
      "duration_minutes": 90,
      "price_cents": 7500,
      "duration_min_minutes": 60,
      "duration_max_minutes": 120,
      "price_from_cents": 6500,
      "price_note": "vanaf",
      "deposit_cents": null,
      "variant_mode": "customer",
      "variant_question": "Hoe lang is je haar?",
      "required_providers": 1,
      "variants": [
        {
          "id": "b3f8d6c1-0a2e-4f5b-9d4c-8e9f0a1b2c3d",
          "name": "Kort haar",
          "help_text": null,
          "duration_minutes": 60,
          "price_cents": 6500,
          "deposit_cents": null
        },
        {
          "id": "c4a9e7d2-1b3f-4a6c-8e5d-9f0a1b2c3d4e",
          "name": "Lang haar",
          "help_text": "Voorbij de schouders",
          "duration_minutes": 120,
          "price_cents": 9500,
          "deposit_cents": null
        }
      ]
    }
  ]
}
```

## GET /providers

**Staff for a selection.** Active staff members (salon, barber, clinic) or wash bays (carwash) that can do all given services. Empty for restaurants.

**Query parameters**

| Name | Type | Required | Description |
|---|---|---|---|
| `service_ids` | string | no | Comma-separated service ids; only staff who can do ALL of them are returned. |

**Response 200**

| Field | Type | Required | Description |
|---|---|---|---|
| `providers` | object[] | yes |  |
| `providers[].id` | string | yes |  |
| `providers[].name` | string | yes |  |
| `providers[].specialty` | string \| null | yes |  |
| `providers[].bio` | string \| null | yes |  |
| `providers[].avatar_url` | string \| null | yes |  |

**Errors:** `unauthorized` (401), `forbidden_origin` (403), `not_enabled` (403), `invalid_input` (422), `rate_limited` (429), `server_error` (500) — What your site does for each code is in [Errors and limits](/developers/en/errors-and-limits).

**Example**

```bash
curl 'https://www.callyndar.com/api/v1/providers?service_ids=5b6f0c3e-2a4d-4f1b-9c7e-1d2a3b4c5d6e' \
  -H 'Authorization: Bearer cal_pk_live_YOUR_KEY'
```

```js
const res = await fetch('https://www.callyndar.com/api/v1/providers?service_ids=5b6f0c3e-2a4d-4f1b-9c7e-1d2a3b4c5d6e', {
  headers: {
    Authorization: 'Bearer cal_pk_live_YOUR_KEY',
  },
});
const data = await res.json();
if (!res.ok) throw new Error(`${data.error.code}: ${data.error.message}`);
```

**Response 200 (example)**

```json
{
  "providers": [
    {
      "id": "9a8b7c6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d",
      "name": "Lisa",
      "specialty": "Kleurspecialist",
      "bio": null,
      "avatar_url": null
    },
    {
      "id": "1f2e3d4c-5b6a-4978-8a6b-5c4d3e2f1a09",
      "name": "Tom",
      "specialty": null,
      "bio": null,
      "avatar_url": null
    }
  ]
}
```

## GET /calendar

**Open and closed days.** Per day open/closed with the reason (weekly closed, holiday, owner day block with message, beyond the booking window) and full days off of staff. Max. 92 days per request.

**Query parameters**

| Name | Type | Required | Description |
|---|---|---|---|
| `from` | string | no | First day (default: today in the venue timezone). |
| `to` | string | no | Last day, inclusive (default: from + 30 days, max. 92 days span). |
| `provider_id` | string | no | Salon: also report full days off of this staff member as closed. |

**Response 200**

| Field | Type | Required | Description |
|---|---|---|---|
| `from` | string | yes | Venue-local date, YYYY-MM-DD. |
| `to` | string | yes | Venue-local date, YYYY-MM-DD. |
| `timezone` | string | yes |  |
| `days` | object[] | yes |  |
| `days[].date` | string | yes | Venue-local date, YYYY-MM-DD. |
| `days[].open` | boolean | yes |  |
| `days[].reason` | "past" \| "weekly_closed" \| "online_day_disabled" \| "holiday" \| "day_block" \| "beyond_max_advance" \| "provider_leave" \| "provider_not_working" \| null | yes |  |
| `days[].message` | string \| null | yes | Message of the owner for a blocked day (or a holiday label). |
| `provider_leave` | object[] | yes |  |
| `provider_leave[].provider_id` | string | yes |  |
| `provider_leave[].from` | string | yes | Venue-local date, YYYY-MM-DD. |
| `provider_leave[].to` | string | yes | Venue-local date, YYYY-MM-DD. |

**Errors:** `unauthorized` (401), `forbidden_origin` (403), `not_enabled` (403), `invalid_input` (422), `rate_limited` (429), `server_error` (500) — What your site does for each code is in [Errors and limits](/developers/en/errors-and-limits).

**Example**

```bash
curl 'https://www.callyndar.com/api/v1/calendar?from=2026-12-01&to=2026-12-07' \
  -H 'Authorization: Bearer cal_pk_live_YOUR_KEY'
```

```js
const res = await fetch('https://www.callyndar.com/api/v1/calendar?from=2026-12-01&to=2026-12-07', {
  headers: {
    Authorization: 'Bearer cal_pk_live_YOUR_KEY',
  },
});
const data = await res.json();
if (!res.ok) throw new Error(`${data.error.code}: ${data.error.message}`);
```

**Response 200 (example)**

```json
{
  "from": "2026-12-01",
  "to": "2026-12-07",
  "timezone": "Europe/Brussels",
  "days": [
    {
      "date": "2026-12-01",
      "open": true,
      "reason": null,
      "message": null
    },
    {
      "date": "2026-12-02",
      "open": true,
      "reason": null,
      "message": null
    },
    {
      "date": "2026-12-03",
      "open": false,
      "reason": "day_block",
      "message": "Opleiding — we zijn gesloten."
    },
    {
      "date": "2026-12-04",
      "open": true,
      "reason": null,
      "message": null
    },
    {
      "date": "2026-12-05",
      "open": true,
      "reason": null,
      "message": null
    },
    {
      "date": "2026-12-06",
      "open": false,
      "reason": "weekly_closed",
      "message": null
    },
    {
      "date": "2026-12-07",
      "open": false,
      "reason": "weekly_closed",
      "message": null
    }
  ],
  "provider_leave": [
    {
      "provider_id": "1f2e3d4c-5b6a-4978-8a6b-5c4d3e2f1a09",
      "from": "2026-12-04",
      "to": "2026-12-05"
    }
  ]
}
```

## GET /availability

**Free times on one day.** The same slots as the Callyndar booking widget, for this party size / selection / staff member.

**Query parameters**

| Name | Type | Required | Description |
|---|---|---|---|
| `date` | string | yes | Venue-local date, YYYY-MM-DD. |
| `party_size` | integer | no | Number of guests (restaurants) — 1 for an appointment. (default: `1`) |
| `service_ids` | string | no | Comma-separated service ids (provider sectors: required to size the appointment). |
| `variant_ids` | string | no | Comma-separated variant ids aligned with service_ids; leave an entry empty ("a,,b") for a service without a variant. |
| `pending_ids` | string | no | Comma-separated service ids whose variant the venue decides (variant_mode "staff"). |
| `provider_id` | string | no | A specific staff member; omit for "no preference". |

**Response 200**

| Field | Type | Required | Description |
|---|---|---|---|
| `date` | string | yes | Venue-local date, YYYY-MM-DD. |
| `duration_minutes` | integer \| null | yes | Length of the appointment the slots are measured with. |
| `required_providers` | integer | yes | Staff members the chosen treatment needs at once (1 unless it is a multi-staff treatment). |
| `slots` | object[] | yes |  |
| `slots[].time` | string | yes | Venue-local time, HH:MM (24h). |
| `slots[].end_time` | string | yes | Venue-local time, HH:MM (24h). |
| `slots[].next_day` | boolean | yes | true for an after-midnight slot of a late opening window. |
| `slots[].available` | integer | yes | Free places (restaurant) or free staff members (salon) at this time; for a multi-staff treatment, how many such appointments still fit. Always 1 when the venue hides the remaining-seats count. |
| `slots[].provider_ids` | string[] | yes | Salon: staff free at this time (empty for restaurants, and empty when the venue hides the remaining-seats count). |
| `reason` | "past_date" \| "same_day_disabled" \| "same_day_closed" \| "party_size" \| "online_booking_closed_day" \| "online_booking_hours" \| "closed_day" \| "blocked_date" \| "day_block" \| "holiday" \| "beyond_max_advance" \| "not_enough_staff" \| null | yes | Why the day has no slots (null when it has some, or simply is full). |
| `reason_params` | object (map) \| null | yes |  |

**Errors:** `unauthorized` (401), `forbidden_origin` (403), `not_enabled` (403), `invalid_input` (422), `rate_limited` (429), `server_error` (500) — What your site does for each code is in [Errors and limits](/developers/en/errors-and-limits).

**Example**

```bash
curl 'https://www.callyndar.com/api/v1/availability?date=2026-12-04&service_ids=5b6f0c3e-2a4d-4f1b-9c7e-1d2a3b4c5d6e&provider_id=9a8b7c6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d' \
  -H 'Authorization: Bearer cal_pk_live_YOUR_KEY'
```

```js
const res = await fetch('https://www.callyndar.com/api/v1/availability?date=2026-12-04&service_ids=5b6f0c3e-2a4d-4f1b-9c7e-1d2a3b4c5d6e&provider_id=9a8b7c6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d', {
  headers: {
    Authorization: 'Bearer cal_pk_live_YOUR_KEY',
  },
});
const data = await res.json();
if (!res.ok) throw new Error(`${data.error.code}: ${data.error.message}`);
```

**Response 200 (example)**

```json
{
  "date": "2026-12-04",
  "duration_minutes": 45,
  "required_providers": 1,
  "slots": [
    {
      "time": "09:00",
      "end_time": "09:45",
      "next_day": false,
      "available": 1,
      "provider_ids": [
        "9a8b7c6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d"
      ]
    },
    {
      "time": "09:15",
      "end_time": "10:00",
      "next_day": false,
      "available": 1,
      "provider_ids": [
        "9a8b7c6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d"
      ]
    },
    {
      "time": "14:30",
      "end_time": "15:15",
      "next_day": false,
      "available": 1,
      "provider_ids": [
        "9a8b7c6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d"
      ]
    }
  ],
  "reason": null,
  "reason_params": null
}
```

## GET /deposit-policy

**Is a deposit due?.** Whether this selection needs an online deposit and how much.

**Query parameters**

| Name | Type | Required | Description |
|---|---|---|---|
| `party_size` | integer | no | Number of guests (restaurants) — 1 for an appointment. (default: `1`) |
| `service_ids` | string | no | Comma-separated service ids. |
| `variant_ids` | string | no | Comma-separated variant ids aligned with service_ids. |
| `pending_ids` | string | no | Comma-separated pending service ids. |

**Response 200**

| Field | Type | Required | Description |
|---|---|---|---|
| `required` | boolean | yes |  |
| `amount_cents` | integer | yes |  |
| `currency` | string | yes |  |
| `refund_window_hours` | integer | yes |  |

**Errors:** `unauthorized` (401), `forbidden_origin` (403), `not_enabled` (403), `invalid_input` (422), `rate_limited` (429), `server_error` (500) — What your site does for each code is in [Errors and limits](/developers/en/errors-and-limits).

**Example**

```bash
curl 'https://www.callyndar.com/api/v1/deposit-policy?service_ids=5b6f0c3e-2a4d-4f1b-9c7e-1d2a3b4c5d6e' \
  -H 'Authorization: Bearer cal_pk_live_YOUR_KEY'
```

```js
const res = await fetch('https://www.callyndar.com/api/v1/deposit-policy?service_ids=5b6f0c3e-2a4d-4f1b-9c7e-1d2a3b4c5d6e', {
  headers: {
    Authorization: 'Bearer cal_pk_live_YOUR_KEY',
  },
});
const data = await res.json();
if (!res.ok) throw new Error(`${data.error.code}: ${data.error.message}`);
```

**Response 200 (example)**

```json
{
  "required": true,
  "amount_cents": 1500,
  "currency": "EUR",
  "refund_window_hours": 24
}
```

## POST /holds

**Hold a time.** Re-checks the time with every rule and holds it (capacity_reserved: true) or returns a signed confirmation (false) for venues without holds.

**Body (JSON)**

| Field | Type | Required | Description |
|---|---|---|---|
| `date` | string | yes | Venue-local date, YYYY-MM-DD. |
| `time` | string | yes | Venue-local time, HH:MM (24h). |
| `party_size` | integer | no | Number of guests (restaurants) — 1 for an appointment. (default: `1`) |
| `service_ids` | string[] | no | Chosen services, in the order the guest picked them. |
| `variant_ids` | (string \| null)[] | no | Chosen variant per service_ids entry (same index), null when that service has no variant choice. |
| `pending_ids` | string[] | no | Services with variant_mode "staff" whose variant the venue decides later. |
| `provider_id` | string \| null | no | A specific staff member; omit or null for "no preference". |
| `session_id` | string | yes | One random id per visitor/browser tab (e.g. crypto.randomUUID()). A new hold of the same session replaces the previous one. |

**Response 201**

| Field | Type | Required | Description |
|---|---|---|---|
| `hold_id` | string | yes | Pass to POST /bookings. A UUID (real hold) or "nh_…" (signed confirmation). |
| `expires_at` | string | yes | ISO timestamp; show a countdown and ask a new hold after it. |
| `capacity_reserved` | boolean | yes | true: the time is really held for you until expires_at. false: it was free when checked but is not held. |
| `date` | string | yes | Venue-local date, YYYY-MM-DD. |
| `time` | string | yes | Venue-local time, HH:MM (24h). |
| `end_time` | string | yes | Venue-local time, HH:MM (24h). |
| `duration_minutes` | integer | yes |  |
| `party_size` | integer | yes |  |
| `provider_id` | string \| null | yes |  |
| `extra_provider_ids` | string[] | yes | Additional staff a multi-staff treatment reserved (empty otherwise). |
| `deposit` | object | yes |  |
| `deposit.required` | boolean | yes |  |
| `deposit.amount_cents` | integer | yes |  |
| `deposit.currency` | string | yes |  |

**Errors:** `unauthorized` (401), `forbidden_origin` (403), `not_enabled` (403), `slot_unavailable` (409), `invalid_input` (422), `rate_limited` (429), `server_error` (500) — What your site does for each code is in [Errors and limits](/developers/en/errors-and-limits).

**Example**

```bash
curl -X POST 'https://www.callyndar.com/api/v1/holds' \
  -H 'Authorization: Bearer cal_pk_live_YOUR_KEY' \
  -H 'Content-Type: application/json' \
  -d '{
  "date": "2026-12-04",
  "time": "14:30",
  "party_size": 1,
  "service_ids": [
    "5b6f0c3e-2a4d-4f1b-9c7e-1d2a3b4c5d6e"
  ],
  "provider_id": "9a8b7c6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d",
  "session_id": "c1d7c0f0-4f7e-4c55-8f0a-6f8c2b7d9e01"
}'
```

```js
const res = await fetch('https://www.callyndar.com/api/v1/holds', {
  method: 'POST',
  headers: {
    Authorization: 'Bearer cal_pk_live_YOUR_KEY',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    "date": "2026-12-04",
    "time": "14:30",
    "party_size": 1,
    "service_ids": [
      "5b6f0c3e-2a4d-4f1b-9c7e-1d2a3b4c5d6e"
    ],
    "provider_id": "9a8b7c6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d",
    "session_id": "c1d7c0f0-4f7e-4c55-8f0a-6f8c2b7d9e01"
  }),
});
const data = await res.json();
if (!res.ok) throw new Error(`${data.error.code}: ${data.error.message}`);
```

**Response 201 (example)**

```json
{
  "hold_id": "3f0c2a5e-8b1d-4c7e-9a40-2d6f1e9b7c11",
  "expires_at": "2026-12-01T13:40:00.000Z",
  "capacity_reserved": true,
  "date": "2026-12-04",
  "time": "14:30",
  "end_time": "15:15",
  "duration_minutes": 45,
  "party_size": 1,
  "provider_id": "9a8b7c6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d",
  "extra_provider_ids": [],
  "deposit": {
    "required": false,
    "amount_cents": 0,
    "currency": "EUR"
  }
}
```

## DELETE /holds/{id}

**Release a hold.** Gives the time back (guest goes back or closes the flow). Idempotent.

**Path parameters**

| Name | Type | Required | Description |
|---|---|---|---|
| `id` | string | yes | hold_id from POST /holds |

**Response 200**

| Field | Type | Required | Description |
|---|---|---|---|
| `released` | boolean | yes |  |

**Errors:** `unauthorized` (401), `forbidden_origin` (403), `not_enabled` (403), `not_found` (404), `rate_limited` (429), `server_error` (500) — What your site does for each code is in [Errors and limits](/developers/en/errors-and-limits).

**Example**

```bash
curl -X DELETE 'https://www.callyndar.com/api/v1/holds/3f0c2a5e-8b1d-4c7e-9a40-2d6f1e9b7c11' \
  -H 'Authorization: Bearer cal_pk_live_YOUR_KEY'
```

```js
const res = await fetch('https://www.callyndar.com/api/v1/holds/3f0c2a5e-8b1d-4c7e-9a40-2d6f1e9b7c11', {
  method: 'DELETE',
  headers: {
    Authorization: 'Bearer cal_pk_live_YOUR_KEY',
  },
});
const data = await res.json();
if (!res.ok) throw new Error(`${data.error.code}: ${data.error.message}`);
```

**Response 200 (example)**

```json
{
  "released": true
}
```

## POST /holds/{id}/deposit

**Start the deposit payment.** Creates the Stripe PaymentIntent on the venue's account for this hold. Mount the Payment Element with client_secret and stripe_account.

Send turnstile_token only when the key has the optional Callyndar Turnstile switched on (GET /venue → turnstile_required, off by default).

**Path parameters**

| Name | Type | Required | Description |
|---|---|---|---|
| `id` | string | yes | hold_id from POST /holds |

**Body (JSON)**

| Field | Type | Required | Description |
|---|---|---|---|
| `guest` | object | yes |  |
| `guest.first_name` | string | yes |  |
| `guest.last_name` | string | yes |  |
| `guest.email` | string (email) | yes |  |
| `guest.phone` | string | no | Required when the venue asks for it (GET /venue → booking.phone_required). |
| `company` | object | no | Optional: the guest books for a company. Leave out for a private booking. |
| `company.name` | string | yes | Company name the invoice should be made out to. |
| `company.vat_number` | string | no | EU VAT number with country prefix (spaces and dots allowed). Checked against VIES after the booking; an unreachable VIES never refuses the booking. |
| `company.reference` | string | no | Purchase order or reference for the invoice. |
| `notes` | string | no |  |
| `locale` | "nl" \| "en" \| "fr" | no | Language of the guest e-mails and the manage page. |
| `turnstile_token` | string | no | Cloudflare Turnstile token — only when the key has the optional Callyndar Turnstile switched on (GET /venue → turnstile_required; off by default). Protecting your form against bots is your own job (your own captcha or Turnstile). |

**Response 201**

| Field | Type | Required | Description |
|---|---|---|---|
| `payment_intent_id` | string | yes |  |
| `client_secret` | string | yes | For stripe.elements({ clientSecret }) — never store it. |
| `amount_cents` | integer | yes |  |
| `currency` | string | yes |  |
| `stripe_publishable_key` | string | yes |  |
| `stripe_account` | string | yes | Connected account: Stripe(stripe_publishable_key, { stripeAccount }). |

**Errors:** `unauthorized` (401), `forbidden_origin` (403), `not_enabled` (403), `turnstile_failed` (403), `not_found` (404), `hold_expired` (409), `slot_unavailable` (409), `invalid_input` (422), `rate_limited` (429), `server_error` (500) — What your site does for each code is in [Errors and limits](/developers/en/errors-and-limits).

**Example**

```bash
curl -X POST 'https://www.callyndar.com/api/v1/holds/3f0c2a5e-8b1d-4c7e-9a40-2d6f1e9b7c11/deposit' \
  -H 'Authorization: Bearer cal_pk_live_YOUR_KEY' \
  -H 'Content-Type: application/json' \
  -d '{
  "guest": {
    "first_name": "Test",
    "last_name": "Gast",
    "email": "test.gast@example.com",
    "phone": "+32 470 12 34 56"
  },
  "locale": "nl"
}'
```

```js
const res = await fetch('https://www.callyndar.com/api/v1/holds/3f0c2a5e-8b1d-4c7e-9a40-2d6f1e9b7c11/deposit', {
  method: 'POST',
  headers: {
    Authorization: 'Bearer cal_pk_live_YOUR_KEY',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    "guest": {
      "first_name": "Test",
      "last_name": "Gast",
      "email": "test.gast@example.com",
      "phone": "+32 470 12 34 56"
    },
    "locale": "nl"
  }),
});
const data = await res.json();
if (!res.ok) throw new Error(`${data.error.code}: ${data.error.message}`);
```

**Response 201 (example)**

```json
{
  "payment_intent_id": "pi_3QxTESTa1b2c3d4e5f6g7h8",
  "client_secret": "pi_3QxTESTa1b2c3d4e5f6g7h8_secret_TESTabc123",
  "amount_cents": 1500,
  "currency": "EUR",
  "stripe_publishable_key": "pk_live_TESTexamplekey",
  "stripe_account": "acct_1TESTexample"
}
```

## POST /bookings

**Book.** Turns the hold into a booking with the guest details. Requires an Idempotency-Key per booking attempt.

Send turnstile_token only when the key has the optional Callyndar Turnstile switched on (GET /venue → turnstile_required, off by default).

Use a new Idempotency-Key per booking attempt; the same key + body returns the first answer again.

**Headers**

| Name | Type | Required | Description |
|---|---|---|---|
| `Idempotency-Key` | string | yes | A new random value per booking attempt (8–128 chars). Retrying with the same key and body returns the first answer. |

**Body (JSON)**

| Field | Type | Required | Description |
|---|---|---|---|
| `hold_id` | string | yes | hold_id from POST /holds (a UUID, or an "nh_…" slot confirmation). |
| `guest` | object | yes |  |
| `guest.first_name` | string | yes |  |
| `guest.last_name` | string | yes |  |
| `guest.email` | string (email) | yes |  |
| `guest.phone` | string | no | Required when the venue asks for it (GET /venue → booking.phone_required). |
| `company` | object | no | Optional: the guest books for a company. Leave out for a private booking. |
| `company.name` | string | yes | Company name the invoice should be made out to. |
| `company.vat_number` | string | no | EU VAT number with country prefix (spaces and dots allowed). Checked against VIES after the booking; an unreachable VIES never refuses the booking. |
| `company.reference` | string | no | Purchase order or reference for the invoice. |
| `notes` | string | no | Remarks of the guest (allergies, wishes). |
| `locale` | "nl" \| "en" \| "fr" | no | Language of the guest e-mails and the manage page. |
| `payment_intent_id` | string | no | The PaymentIntent of a paid deposit (POST /holds/{id}/deposit). |
| `turnstile_token` | string | no | Cloudflare Turnstile token — only when the key has the optional Callyndar Turnstile switched on (GET /venue → turnstile_required; off by default). Protecting your form against bots is your own job (your own captcha or Turnstile). |

**Response 201**

| Field | Type | Required | Description |
|---|---|---|---|
| `booking` | object | yes |  |
| `booking.id` | string | yes |  |
| `booking.status` | "confirmed" \| "pending" \| "waitlisted" | yes | confirmed = booked; pending = the venue confirms it; waitlisted = full, on the waiting list. |
| `booking.date` | string | yes | Venue-local date, YYYY-MM-DD. |
| `booking.time` | string | yes | Venue-local time, HH:MM (24h). |
| `booking.end_time` | string | yes | Venue-local time, HH:MM (24h). |
| `booking.party_size` | integer | yes |  |
| `booking.provider_id` | string \| null | yes |  |
| `booking.extra_provider_ids` | string[] | yes |  |
| `booking.services` | object[] | yes |  |
| `booking.services[].id` | string | yes |  |
| `booking.services[].name` | string | yes |  |
| `booking.services[].variant_id` | string \| null | yes |  |
| `booking.services[].variant_name` | string \| null | yes |  |
| `booking.services[].duration_minutes` | integer \| null | yes |  |
| `booking.services[].price_cents` | integer \| null | yes |  |
| `booking.deposit_paid` | boolean | yes |  |
| `booking.company` | object \| null | yes | The company block sent with the booking, or null. |
| `booking.company.name` | string | yes |  |
| `booking.company.vat_number` | string \| null | yes | Normalised (BE0123456749). |
| `booking.company.reference` | string \| null | yes |  |
| `booking.manage_url` | string | yes | Page where the guest cancels or reschedules (also in the confirmation e-mail). |

**Errors:** `unauthorized` (401), `forbidden_origin` (403), `not_enabled` (403), `turnstile_failed` (403), `not_found` (404), `hold_expired` (409), `slot_unavailable` (409), `deposit_required` (409), `idempotency_conflict` (409), `payload_too_large` (413), `invalid_input` (422), `rate_limited` (429), `server_error` (500) — What your site does for each code is in [Errors and limits](/developers/en/errors-and-limits).

**Example**

```bash
curl -X POST 'https://www.callyndar.com/api/v1/bookings' \
  -H 'Authorization: Bearer cal_pk_live_YOUR_KEY' \
  -H 'Content-Type: application/json' \
  -H 'Idempotency-Key: 6f1c9a52-0d3e-4b8a-9c71-2e5d4f3a1b90' \
  -d '{
  "hold_id": "3f0c2a5e-8b1d-4c7e-9a40-2d6f1e9b7c11",
  "guest": {
    "first_name": "Test",
    "last_name": "Gast",
    "email": "test.gast@example.com",
    "phone": "+32 470 12 34 56"
  },
  "notes": "Graag een stille plek.",
  "locale": "nl",
  "company": {
    "name": "TEST Studio BV",
    "vat_number": "BE 0123.456.749",
    "reference": "PO-2026-118"
  }
}'
```

```js
const res = await fetch('https://www.callyndar.com/api/v1/bookings', {
  method: 'POST',
  headers: {
    Authorization: 'Bearer cal_pk_live_YOUR_KEY',
    'Content-Type': 'application/json',
    'Idempotency-Key': crypto.randomUUID(),
  },
  body: JSON.stringify({
    "hold_id": "3f0c2a5e-8b1d-4c7e-9a40-2d6f1e9b7c11",
    "guest": {
      "first_name": "Test",
      "last_name": "Gast",
      "email": "test.gast@example.com",
      "phone": "+32 470 12 34 56"
    },
    "notes": "Graag een stille plek.",
    "locale": "nl",
    "company": {
      "name": "TEST Studio BV",
      "vat_number": "BE 0123.456.749",
      "reference": "PO-2026-118"
    }
  }),
});
const data = await res.json();
if (!res.ok) throw new Error(`${data.error.code}: ${data.error.message}`);
```

**Response 201 (example)**

```json
{
  "booking": {
    "id": "7c1e5a9d-3b2f-4e8a-9d6c-0b1a2c3d4e5f",
    "status": "confirmed",
    "date": "2026-12-04",
    "time": "14:30",
    "end_time": "15:15",
    "party_size": 1,
    "provider_id": "9a8b7c6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d",
    "extra_provider_ids": [],
    "services": [
      {
        "id": "5b6f0c3e-2a4d-4f1b-9c7e-1d2a3b4c5d6e",
        "name": "Knippen",
        "variant_id": null,
        "variant_name": null,
        "duration_minutes": 45,
        "price_cents": 4500
      }
    ],
    "deposit_paid": false,
    "company": {
      "name": "TEST Studio BV",
      "vat_number": "BE0123456749",
      "reference": "PO-2026-118"
    },
    "manage_url": "https://callyndar.com/r/7c1e5a9d-3b2f-4e8a-9d6c-0b1a2c3d4e5f"
  }
}
```

## POST /bookings/recover

**Finish a booking after a payment redirect.** After iDEAL/Bancontact the guest comes back to your return_url. Call this with the payment_intent from the URL to finish (or fetch) the booking. Only works for payments started with this key.

**Body (JSON)**

| Field | Type | Required | Description |
|---|---|---|---|
| `payment_intent_id` | string | yes |  |

**Response 200**

| Field | Type | Required | Description |
|---|---|---|---|
| `booking` | object | yes |  |
| `booking.id` | string | yes |  |
| `booking.status` | "confirmed" \| "pending" \| "waitlisted" | yes | confirmed = booked; pending = the venue confirms it; waitlisted = full, on the waiting list. |
| `booking.date` | string | yes | Venue-local date, YYYY-MM-DD. |
| `booking.time` | string | yes | Venue-local time, HH:MM (24h). |
| `booking.end_time` | string | yes | Venue-local time, HH:MM (24h). |
| `booking.party_size` | integer | yes |  |
| `booking.provider_id` | string \| null | yes |  |
| `booking.extra_provider_ids` | string[] | yes |  |
| `booking.services` | object[] | yes |  |
| `booking.services[].id` | string | yes |  |
| `booking.services[].name` | string | yes |  |
| `booking.services[].variant_id` | string \| null | yes |  |
| `booking.services[].variant_name` | string \| null | yes |  |
| `booking.services[].duration_minutes` | integer \| null | yes |  |
| `booking.services[].price_cents` | integer \| null | yes |  |
| `booking.deposit_paid` | boolean | yes |  |
| `booking.company` | object \| null | yes | The company block sent with the booking, or null. |
| `booking.company.name` | string | yes |  |
| `booking.company.vat_number` | string \| null | yes | Normalised (BE0123456749). |
| `booking.company.reference` | string \| null | yes |  |
| `booking.manage_url` | string | yes | Page where the guest cancels or reschedules (also in the confirmation e-mail). |

**Errors:** `unauthorized` (401), `forbidden_origin` (403), `not_enabled` (403), `not_found` (404), `deposit_required` (409), `slot_unavailable` (409), `hold_expired` (409), `invalid_input` (422), `rate_limited` (429), `server_error` (500) — What your site does for each code is in [Errors and limits](/developers/en/errors-and-limits).

**Example**

```bash
curl -X POST 'https://www.callyndar.com/api/v1/bookings/recover' \
  -H 'Authorization: Bearer cal_pk_live_YOUR_KEY' \
  -H 'Content-Type: application/json' \
  -d '{
  "payment_intent_id": "pi_3QxTESTa1b2c3d4e5f6g7h8"
}'
```

```js
const res = await fetch('https://www.callyndar.com/api/v1/bookings/recover', {
  method: 'POST',
  headers: {
    Authorization: 'Bearer cal_pk_live_YOUR_KEY',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    "payment_intent_id": "pi_3QxTESTa1b2c3d4e5f6g7h8"
  }),
});
const data = await res.json();
if (!res.ok) throw new Error(`${data.error.code}: ${data.error.message}`);
```

**Response 200 (example)**

```json
{
  "booking": {
    "id": "7c1e5a9d-3b2f-4e8a-9d6c-0b1a2c3d4e5f",
    "status": "confirmed",
    "date": "2026-12-04",
    "time": "14:30",
    "end_time": "15:15",
    "party_size": 1,
    "provider_id": "9a8b7c6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d",
    "extra_provider_ids": [],
    "services": [
      {
        "id": "5b6f0c3e-2a4d-4f1b-9c7e-1d2a3b4c5d6e",
        "name": "Knippen",
        "variant_id": null,
        "variant_name": null,
        "duration_minutes": 45,
        "price_cents": 4500
      }
    ],
    "deposit_paid": false,
    "company": {
      "name": "TEST Studio BV",
      "vat_number": "BE0123456749",
      "reference": "PO-2026-118"
    },
    "manage_url": "https://callyndar.com/r/7c1e5a9d-3b2f-4e8a-9d6c-0b1a2c3d4e5f"
  }
}
```

## GET /openapi.json

**This specification (OpenAPI 3.1).** No key needed.

**Example**

```bash
curl 'https://www.callyndar.com/api/v1/openapi.json'
```

```js
const res = await fetch('https://www.callyndar.com/api/v1/openapi.json', {
});
const data = await res.json();
if (!res.ok) throw new Error(`${data.error.code}: ${data.error.message}`);
```

---

# Changelog

Changes to the API. Within v1 only additions are made; anything that breaks goes into `/api/v2`.

## v1.4 — 2 December 2026

- New fields on every service in `GET /services`: `duration_min_minutes`, `duration_max_minutes` and `price_from_cents`. For a service with variants they come from the variants (shortest and longest duration, lowest price); otherwise they equal `duration_minutes` and `price_cents`. For a service with variants, show this range ("30–60 min · from € 35") instead of the service's base duration and price. `price_from_cents` is `null` when the venue hides the price. The existing fields are unchanged. See [Booking flow](/developers/en/booking-flow#1-services-and-variants).

## v1.3 — 2 December 2026

- Optional `company` block (`name`, `vat_number`, `reference`) on `POST /bookings` and `POST /holds/{id}/deposit`: the guest books for a company. The VAT number is checked against EU VIES after the booking and never blocks it. After a deposit with a redirect, `POST /bookings/recover` carries the block over. See [Booking flow](/developers/en/booking-flow#6-guest-details).
- The booking response has a new field `booking.company` (or `null`).

## Documentation — 1 December 2026 (new docs)

- The [API reference](/developers/en/reference) is now generated straight from the OpenAPI document, with parameters, request and response examples, the possible errors and code samples in curl, JavaScript, PHP and Python for every endpoint.
- **Try it**: send every `GET` and `POST /holds` from the docs, with your own publishable key, to the real API of that venue.
- New [5-minute quickstart](/developers/en/quickstart), and all docs in English at [/developers/en](/developers/en).
- `openapi.json` now has `tags` and examples (`example`) per parameter, body, response and error code. No change to the API itself.

## v1.2 — 1 December 2026

- A venue in the **setup phase** (created by a partner, not yet activated by the owner) now responds on all `GET` routes, so you can already build and test your site. Write calls are still rejected with `403 not_enabled` and the new `details.reason = "venue_in_setup"`. See [Testing](/developers/en/testing#during-the-setup-phase).

## Documentation — 1 December 2026

- New page [Multiple locations](/developers/en/multiple-locations): one key per location, the visitor first chooses a location, and staff members who work at multiple locations are seen as busy in every location. No change to the API itself.

## v1.1 — 25 November 2026

- Duo treatments (services that need multiple staff members at the same time): `required_providers` on services and in `/availability`, `extra_provider_ids` filled in holds and bookings, `reason: "not_enough_staff"` on a day without enough staff members, `multi_staff_combo` if such a service is part of a combination. Such a booking always gets a real hold.
- If a venue hides the number of free places, `/availability` returns `available: 1` and an empty `provider_ids`.
- Callyndar's Turnstile is now **off by default** per key. Protecting your form against bots is the site builder's job (own captcha or Turnstile); Callyndar's Turnstile is an optional extra that the owner turns on per key (`GET /venue` → `turnstile_required`).

## v1.0 — 23 November 2026

First version of the Callyndar Booking API for custom websites.

- Publishable keys per venue (`cal_pk_live_…`) with domain list, "Allow localhost" and Turnstile per key; managed at `/integrations`.
- Reading: `GET /venue`, `/services`, `/providers`, `/calendar`, `/availability`, `/deposit-policy`.
- Booking: `POST /holds` (real hold or signed slot confirmation, `capacity_reserved`), `DELETE /holds/{id}`, `POST /bookings` with `Idempotency-Key`.
- Deposits: `POST /holds/{id}/deposit` (Stripe Payment Element on the venue's account) and `POST /bookings/recover` after a redirect payment.
- Every slot and booking response already contains `provider_id` and `extra_provider_ids` (empty), and services have `required_providers` (1): ready for treatments with multiple staff members.
- OpenAPI 3.1 at `/api/v1/openapi.json`, all docs in a single file at `/developers/en/llms-full.txt`.

What you can expect in v1 (additive): new optional fields and new endpoints. Ignore fields you don't recognize.

---

# Example: boeking.html

One standalone file with the complete flow. Replace the key at the top with the venue's key.

```html
<!doctype html>
<html lang="nl">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Online boeken</title>
<!--
  Callyndar — voorbeeld boekingsflow (één los bestand, vanilla JS).
  Docs: https://callyndar.com/developers  ·  Alles in één bestand voor je AI: /developers/llms-full.txt

  1. Vul hieronder in het script CALLYNDAR_KEY in (je publishable key van /integrations).
  2. Zet het domein van deze pagina op de sleutel (of "localhost toestaan" tijdens het bouwen).
  Bots: bescherm het formulier zelf (eigen captcha of Turnstile). De Turnstile van Callyndar is een
  optionele extra per sleutel; dit voorbeeld laadt hem alleen als GET /venue turnstile_required: true geeft.
  3. Serveer het bestand via een webserver (niet als file://), bv. `python3 -m http.server 5500`.
  4. Stijl de klassen .cal-* in je eigen ontwerp. De CSS hieronder is bewust minimaal.
-->
<style>
  .cal-booking { max-width: 640px; margin: 0 auto; padding: 16px; font-family: system-ui, sans-serif; line-height: 1.4; }
  .cal-step { margin: 20px 0; }
  .cal-step[hidden] { display: none; }
  .cal-step h2 { font-size: 1.1rem; margin: 0 0 8px; }
  .cal-list { display: grid; gap: 8px; }
  .cal-option { display: flex; gap: 8px; align-items: flex-start; padding: 10px; border: 1px solid #ccc; border-radius: 8px; cursor: pointer; }
  .cal-option-meta { color: #666; font-size: .9em; }
  .cal-days, .cal-slots { display: flex; flex-wrap: wrap; gap: 6px; }
  .cal-day, .cal-slot, .cal-button { padding: 8px 12px; border: 1px solid #888; border-radius: 6px; background: #fff; cursor: pointer; font: inherit; }
  .cal-day[disabled], .cal-slot[disabled], .cal-button[disabled] { opacity: .4; cursor: not-allowed; }
  .cal-day.is-selected, .cal-slot.is-selected { background: #222; color: #fff; }
  .cal-button-primary { background: #222; color: #fff; border-color: #222; }
  .cal-field { display: grid; gap: 4px; margin-bottom: 10px; }
  .cal-field input, .cal-field textarea, .cal-field select { padding: 8px; font: inherit; }
  .cal-hold { padding: 8px 12px; background: #f4f4f4; border-radius: 6px; }
  .cal-error { color: #b00020; }
  .cal-notice { font-size: .85em; color: #555; }
  .cal-muted { color: #666; }
</style>
</head>
<body>
<div class="cal-booking" id="cal-booking">
  <h1 class="cal-venue-name" id="cal-venue-name">Online boeken</h1>
  <p class="cal-error" id="cal-error" role="alert" hidden></p>

  <section class="cal-step cal-step-services" id="step-services" hidden>
    <h2>Kies je behandeling</h2>
    <div class="cal-list cal-services" id="cal-services"></div>
    <button class="cal-button cal-button-primary" id="btn-services-next" type="button">Verder</button>
  </section>

  <section class="cal-step cal-step-provider" id="step-provider" hidden>
    <h2>Bij wie?</h2>
    <div class="cal-list cal-providers" id="cal-providers"></div>
  </section>

  <section class="cal-step cal-step-party" id="step-party" hidden>
    <h2>Met hoeveel personen?</h2>
    <select class="cal-party" id="cal-party"></select>
    <button class="cal-button cal-button-primary" id="btn-party-next" type="button">Verder</button>
  </section>

  <section class="cal-step cal-step-date" id="step-date" hidden>
    <h2>Kies een dag</h2>
    <div class="cal-days" id="cal-days"></div>
    <p class="cal-muted" id="cal-day-note"></p>
  </section>

  <section class="cal-step cal-step-time" id="step-time" hidden>
    <h2>Kies een tijd</h2>
    <div class="cal-slots" id="cal-slots"></div>
    <p class="cal-muted" id="cal-slots-note"></p>
  </section>

  <section class="cal-step cal-step-details" id="step-details" hidden>
    <h2>Jouw gegevens</h2>
    <p class="cal-hold" id="cal-hold"></p>
    <form id="cal-form" novalidate>
      <label class="cal-field">Voornaam <input name="first_name" autocomplete="given-name" required maxlength="100"></label>
      <label class="cal-field">Achternaam <input name="last_name" autocomplete="family-name" required maxlength="100"></label>
      <label class="cal-field">E-mail <input name="email" type="email" autocomplete="email" required maxlength="254"></label>
      <label class="cal-field">Telefoon <span class="cal-muted" id="cal-phone-hint">(optioneel)</span>
        <input name="phone" type="tel" autocomplete="tel" maxlength="32"></label>
      <label class="cal-field">Opmerkingen <textarea name="notes" rows="3" maxlength="1000"></textarea></label>
      <div class="cal-turnstile" id="cal-turnstile"></div>
      <div class="cal-payment" id="cal-payment" hidden>
        <p id="cal-payment-amount"></p>
        <div id="cal-payment-element"></div>
      </div>
      <p class="cal-notice" id="cal-legal"></p>
      <button class="cal-button cal-button-primary" id="btn-book" type="submit">Boeken</button>
      <button class="cal-button" id="btn-release" type="button">Andere tijd kiezen</button>
    </form>
  </section>

  <section class="cal-step cal-step-done" id="step-done" hidden>
    <h2 id="cal-done-title">Bedankt!</h2>
    <p id="cal-done-text"></p>
    <p><a id="cal-manage" href="#" target="_blank" rel="noopener">Je boeking bekijken, verzetten of annuleren</a></p>
  </section>
</div>

<script>
const CALLYNDAR_KEY = 'cal_pk_live_JOUW_SLEUTEL';
const CALLYNDAR_API = 'https://www.callyndar.com/api/v1';

// ── API client ────────────────────────────────────────────────────────────────
class CallyndarError extends Error {
  constructor(code, message, status, details, retryAfter) {
    super(message); this.code = code; this.status = status; this.details = details; this.retryAfter = retryAfter;
  }
}
async function api(method, path, body, headers) {
  let res;
  try {
    res = await fetch(CALLYNDAR_API + path, {
      method,
      headers: Object.assign({ Authorization: 'Bearer ' + CALLYNDAR_KEY }, body ? { 'Content-Type': 'application/json' } : {}, headers || {}),
      body: body ? JSON.stringify(body) : undefined,
    });
  } catch (e) {
    throw new CallyndarError('network_error', 'Geen verbinding. Controleer je internet en probeer opnieuw.', 0);
  }
  const data = await res.json().catch(() => null);
  if (!res.ok) {
    const e = (data && data.error) || {};
    throw new CallyndarError(e.code || 'server_error', e.message || ('HTTP ' + res.status), res.status, e.details, Number(res.headers.get('Retry-After')) || null);
  }
  return data;
}
const qs = (params) => {
  const q = new URLSearchParams();
  Object.entries(params).forEach(([k, v]) => {
    if (v === undefined || v === null || v === '' || (Array.isArray(v) && v.length === 0)) return;
    q.set(k, Array.isArray(v) ? v.map((x) => (x == null ? '' : x)).join(',') : String(v));
  });
  const s = q.toString();
  return s ? '?' + s : '';
};

// ── state (nothing about the guest is ever stored) ────────────────────────────
const state = {
  venue: null, catalog: null,
  chosen: [],            // [{ service, variantId }]
  providerId: null,      // null = geen voorkeur
  partySize: 1,
  date: null, hold: null, stopTimer: null,
  turnstileId: null, turnstileToken: null, tokenWaiters: [],
  stripe: null, elements: null, payment: null,
};
const $ = (id) => document.getElementById(id);
const el = (tag, cls, text) => { const n = document.createElement(tag); if (cls) n.className = cls; if (text != null) n.textContent = text; return n; };
const euro = (cents) => (cents == null ? '' : new Intl.NumberFormat('nl-BE', { style: 'currency', currency: 'EUR' }).format(cents / 100));

function sessionId() {
  let id = sessionStorage.getItem('cal_session_id');
  if (!id) { id = crypto.randomUUID(); sessionStorage.setItem('cal_session_id', id); }
  return id;
}
function show(stepId) {
  document.querySelectorAll('.cal-step').forEach((s) => { s.hidden = s.id !== stepId; });
  if (stepId !== 'step-done') document.querySelectorAll('.cal-step').forEach((s) => {
    // keep the earlier steps visible so the guest sees their choices
    const order = ['step-services', 'step-provider', 'step-party', 'step-date', 'step-time', 'step-details'];
    if (order.indexOf(s.id) !== -1 && order.indexOf(s.id) < order.indexOf(stepId) && isStepUsed(s.id)) s.hidden = false;
  });
}
function isStepUsed(id) {
  const services = state.venue && state.venue.booking_mode === 'services';
  if (id === 'step-services' || id === 'step-provider') return services;
  if (id === 'step-party') return !services;
  return true;
}
function showError(err) {
  const box = $('cal-error');
  if (!err) { box.hidden = true; box.textContent = ''; return; }
  let msg = err.message || String(err);
  if (err.code === 'rate_limited') msg = 'Even geduld: probeer het over ' + (err.retryAfter || 30) + ' seconden opnieuw.';
  if (err.code === 'not_enabled') msg = 'Online boeken is nu niet mogelijk. Neem contact op met de zaak' + (state.venue && state.venue.phone ? ' (' + state.venue.phone + ').' : '.');
  if (err.code === 'forbidden_origin' || err.code === 'unauthorized') msg = 'Deze pagina is niet goed ingesteld (sleutel of domein). ' + (err.message || '');
  box.textContent = msg; box.hidden = false;
}
const selection = () => ({
  service_ids: state.chosen.map((c) => c.service.id),
  variant_ids: state.chosen.map((c) => c.variantId || null),
  pending_ids: state.chosen.filter((c) => c.service.variant_mode === 'staff').map((c) => c.service.id),
});

// ── 1. venue ──────────────────────────────────────────────────────────────────
async function start() {
  try {
    const { venue } = await api('GET', '/venue');
    state.venue = venue;
    $('cal-venue-name').textContent = venue.name;
    renderLegal();
    if (venue.turnstile_required) loadTurnstile();

    const pi = new URLSearchParams(location.search).get('payment_intent');
    if (pi) return recoverAfterRedirect(pi);

    if (venue.booking_mode === 'services') {
      state.catalog = await api('GET', '/services');
      renderServices();
      show('step-services');
    } else {
      const sel = $('cal-party');
      for (let n = venue.booking.min_party_size; n <= venue.booking.max_party_size; n++) sel.append(el('option', null, String(n)));
      sel.value = String(Math.min(Math.max(2, venue.booking.min_party_size), venue.booking.max_party_size));
      show('step-party');
    }
  } catch (err) { showError(err); }
}

function renderLegal() {
  const p = $('cal-legal'); p.textContent = '';
  const a1 = el('a', null, 'voorwaarden'); a1.href = state.venue.terms_url; a1.target = '_blank'; a1.rel = 'noopener';
  const a2 = el('a', null, 'privacybeleid'); a2.href = state.venue.privacy_url; a2.target = '_blank'; a2.rel = 'noopener';
  p.append('Door te boeken ga je akkoord met de ', a1, ' en het ', a2, ' van ' + state.venue.name + '.');
}

// ── 2. services + variants (salon) ────────────────────────────────────────────
function renderServices() {
  const box = $('cal-services'); box.textContent = '';
  const multi = state.catalog.allow_service_combos;
  state.catalog.services.forEach((svc) => {
    const row = el('label', 'cal-option cal-service');
    const input = el('input'); input.type = multi ? 'checkbox' : 'radio'; input.name = 'service'; input.value = svc.id;
    const body = el('div');
    body.append(el('strong', null, svc.name));
    // With variants: their range ("30–60 min · vanaf € 35"), never the base duration/price.
    const dMin = svc.duration_min_minutes, dMax = svc.duration_max_minutes;
    const dur = dMin ? (dMin === dMax ? dMin + ' min' : dMin + '–' + dMax + ' min') : '';
    const from = svc.variants.some((v) => v.price_cents !== svc.price_from_cents);
    const price = svc.price_from_cents == null ? '' : (from ? 'vanaf ' : '') + euro(svc.price_from_cents);
    const meta = [dur, price, svc.price_note || ''].filter(Boolean).join(' · ');
    if (meta) body.append(el('div', 'cal-option-meta', meta));
    if (svc.description) body.append(el('div', 'cal-option-meta', svc.description));
    if (svc.variant_mode === 'customer' && svc.variants.length) {
      const select = el('select', 'cal-variant'); select.dataset.service = svc.id; select.hidden = true;
      select.append(el('option', null, svc.variant_question || 'Kies een optie'));
      select.firstChild.value = '';
      svc.variants.forEach((v) => {
        const o = el('option', null, [v.name, v.duration_minutes ? v.duration_minutes + ' min' : '', euro(v.price_cents)].filter(Boolean).join(' · '));
        o.value = v.id; select.append(o);
      });
      body.append(select);
      input.addEventListener('change', () => document.querySelectorAll('.cal-variant').forEach((s) => {
        s.hidden = !document.querySelector('input[name=service][value="' + s.dataset.service + '"]').checked;
      }));
    } else if (svc.variant_mode === 'staff') {
      body.append(el('div', 'cal-option-meta', 'De zaak bepaalt de precieze behandeling ter plaatse.'));
    }
    row.append(input, body);
    box.append(row);
  });
}

$('btn-services-next').addEventListener('click', async () => {
  showError(null);
  const picked = [...document.querySelectorAll('input[name=service]:checked')].map((i) => state.catalog.services.find((s) => s.id === i.value));
  if (!picked.length) return showError(new Error('Kies minstens één behandeling.'));
  state.chosen = [];
  for (const service of picked) {
    let variantId = null;
    if (service.variant_mode === 'customer' && service.variants.length) {
      variantId = document.querySelector('.cal-variant[data-service="' + service.id + '"]').value || null;
      if (!variantId) return showError(new Error('Maak een keuze voor "' + service.name + '".'));
    }
    state.chosen.push({ service, variantId });
  }
  try {
    const { providers } = await api('GET', '/providers' + qs({ service_ids: selection().service_ids }));
    renderProviders(providers);
    show('step-provider');
  } catch (err) { showError(err); }
});

function renderProviders(providers) {
  const box = $('cal-providers'); box.textContent = '';
  const add = (id, name, meta) => {
    const b = el('button', 'cal-option cal-provider'); b.type = 'button';
    b.append(el('strong', null, name));
    if (meta) b.append(el('span', 'cal-option-meta', meta));
    b.addEventListener('click', () => { state.providerId = id; loadDays(); });
    box.append(b);
  };
  add(null, 'Geen voorkeur', 'De eerste vrije medewerker');
  providers.forEach((p) => add(p.id, p.name, p.specialty));
}

// ── 3. party size (restaurant) ────────────────────────────────────────────────
$('btn-party-next').addEventListener('click', () => { state.partySize = Number($('cal-party').value); loadDays(); });

// ── 4. day ────────────────────────────────────────────────────────────────────
async function loadDays() {
  showError(null);
  try {
    const cal = await api('GET', '/calendar' + qs({ provider_id: state.providerId }));
    const box = $('cal-days'); box.textContent = ''; $('cal-day-note').textContent = '';
    cal.days.forEach((d) => {
      const date = new Date(d.date + 'T12:00:00');
      const b = el('button', 'cal-day', date.toLocaleDateString('nl-BE', { weekday: 'short', day: 'numeric', month: 'short' }));
      b.type = 'button';
      b.disabled = !d.open;
      if (!d.open && d.message) b.title = d.message;
      b.addEventListener('click', () => {
        document.querySelectorAll('.cal-day').forEach((x) => x.classList.remove('is-selected'));
        b.classList.add('is-selected'); state.date = d.date; loadTimes();
      });
      if (!d.open && d.reason === 'day_block' && d.message) b.addEventListener('mouseenter', () => { $('cal-day-note').textContent = d.message; });
      box.append(b);
    });
    show('step-date');
  } catch (err) { showError(err); }
}

// ── 5. time ───────────────────────────────────────────────────────────────────
async function loadTimes() {
  showError(null);
  try {
    const sel = selection();
    const av = await api('GET', '/availability' + qs({
      date: state.date, party_size: state.partySize, service_ids: sel.service_ids, variant_ids: sel.service_ids.length ? sel.variant_ids : [],
      pending_ids: sel.pending_ids, provider_id: state.providerId,
    }));
    const box = $('cal-slots'); box.textContent = '';
    $('cal-slots-note').textContent = av.slots.length ? '' : 'Geen vrije tijden op deze dag. Kies een andere dag.';
    av.slots.forEach((s) => {
      const b = el('button', 'cal-slot', s.time); b.type = 'button';
      b.addEventListener('click', () => holdSlot(s.time, b));
      box.append(b);
    });
    show('step-time');
  } catch (err) { showError(err); }
}

// ── 6. hold + countdown ───────────────────────────────────────────────────────
async function holdSlot(time, button) {
  showError(null);
  document.querySelectorAll('.cal-slot').forEach((x) => x.classList.remove('is-selected'));
  button.classList.add('is-selected');
  try {
    const hold = await api('POST', '/holds', Object.assign({
      date: state.date, time, party_size: state.partySize, session_id: sessionId(),
    }, selection(), state.providerId ? { provider_id: state.providerId } : {}));
    state.hold = hold; state.payment = null;
    $('cal-payment').hidden = true;
    const b = state.venue.booking;
    const needPhone = b.phone_required === 'always' || (b.phone_required === 'conditional' && state.partySize >= b.phone_required_min_party_size);
    $('cal-form').phone.required = needPhone;
    $('cal-phone-hint').textContent = needPhone ? '(verplicht)' : '(optioneel)';
    $('btn-book').textContent = hold.deposit.required ? 'Verder naar betalen (' + euro(hold.deposit.amount_cents) + ')' : 'Boeken';
    startCountdown();
    show('step-details');
  } catch (err) { handleSlotError(err); }
}

function startCountdown() {
  if (state.stopTimer) state.stopTimer();
  const end = new Date(state.hold.expires_at).getTime();
  const label = state.hold.capacity_reserved ? 'Je tijd blijft voor je vastgehouden: nog ' : 'Rond je boeking af binnen ';
  const tick = () => {
    const left = Math.max(0, Math.round((end - Date.now()) / 1000));
    $('cal-hold').textContent = state.date + ' om ' + state.hold.time + ' · ' + label + Math.floor(left / 60) + ':' + String(left % 60).padStart(2, '0');
    if (left === 0) { stop(); showError(new Error('De tijd is verlopen. Kies opnieuw een tijd.')); state.hold = null; loadTimes(); }
  };
  const id = setInterval(tick, 1000); const stop = () => clearInterval(id);
  state.stopTimer = stop; tick();
}

$('btn-release').addEventListener('click', async () => {
  if (state.stopTimer) state.stopTimer();
  if (state.hold) api('DELETE', '/holds/' + encodeURIComponent(state.hold.hold_id)).catch(() => {});
  state.hold = null; loadTimes();
});

function handleSlotError(err) {
  if (err.code === 'slot_unavailable' || err.code === 'hold_expired') {
    if (state.stopTimer) state.stopTimer();
    state.hold = null;
    showError(new Error('Deze tijd is net niet meer beschikbaar. Kies een andere tijd.'));
    return loadTimes();
  }
  if (err.code === 'turnstile_failed') resetTurnstile();
  showError(err);
}

// ── Turnstile ─────────────────────────────────────────────────────────────────
function loadTurnstile() {
  window.onCalTurnstileLoad = () => {
    state.turnstileId = turnstile.render('#cal-turnstile', {
      sitekey: state.venue.turnstile_site_key,
      callback: (token) => { state.turnstileToken = token; state.tokenWaiters.splice(0).forEach((r) => r(token)); },
      'expired-callback': () => { state.turnstileToken = null; },
    });
  };
  const s = document.createElement('script');
  s.src = 'https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit&onload=onCalTurnstileLoad';
  s.async = true; document.head.append(s);
}
function resetTurnstile() {
  state.turnstileToken = null;
  if (window.turnstile && state.turnstileId !== null) turnstile.reset(state.turnstileId);
}
/** A fresh (unused) token; tokens are single-use. */
function takeToken() {
  if (!state.venue.turnstile_required) return Promise.resolve(undefined);
  if (state.turnstileToken) { const t = state.turnstileToken; state.turnstileToken = null; return Promise.resolve(t); }
  return new Promise((resolve) => state.tokenWaiters.push(resolve)).then((t) => { state.turnstileToken = null; return t; });
}

// ── 7. guest details → (deposit) → book ───────────────────────────────────────
function guestFromForm() {
  const f = $('cal-form');
  if (!f.reportValidity()) return null;
  const guest = { first_name: f.first_name.value.trim(), last_name: f.last_name.value.trim(), email: f.email.value.trim() };
  if (f.phone.value.trim()) guest.phone = f.phone.value.trim();
  return { guest, notes: f.notes.value.trim() || undefined, locale: 'nl' };
}

$('cal-form').addEventListener('submit', async (e) => {
  e.preventDefault(); showError(null);
  const details = guestFromForm(); if (!details || !state.hold) return;
  const btn = $('btn-book'); btn.disabled = true;
  try {
    if (state.hold.deposit.required && !state.payment) {
      await startDeposit(details);
    } else if (state.payment) {
      await payAndBook(details);
    } else {
      await book(details, undefined);
    }
  } catch (err) { handleSlotError(err); }
  finally { btn.disabled = false; }
});

async function startDeposit(details) {
  const turnstile_token = await takeToken();
  const pay = await api('POST', '/holds/' + encodeURIComponent(state.hold.hold_id) + '/deposit', Object.assign({ turnstile_token }, details));
  state.payment = pay;
  if (state.venue.turnstile_required) resetTurnstile(); // the booking needs its own token
  await loadScript('https://js.stripe.com/v3/');
  state.stripe = Stripe(pay.stripe_publishable_key, { stripeAccount: pay.stripe_account });
  state.elements = state.stripe.elements({ clientSecret: pay.client_secret });
  state.elements.create('payment').mount('#cal-payment-element');
  $('cal-payment-amount').textContent = 'Aanbetaling: ' + euro(pay.amount_cents);
  $('cal-payment').hidden = false;
  $('btn-book').textContent = 'Betalen en boeken';
}

async function payAndBook(details) {
  const { error, paymentIntent } = await state.stripe.confirmPayment({
    elements: state.elements,
    redirect: 'if_required',
    confirmParams: { return_url: location.href.split('?')[0] },
  });
  if (error) throw new CallyndarError('payment_failed', error.message || 'De betaling is niet gelukt.', 0);
  if (paymentIntent && paymentIntent.status === 'succeeded') {
    try {
      return await book(details, paymentIntent.id);
    } catch (err) {
      // Paid, but the hold ran out during the payment: finish through
      // /bookings/recover — never send a paying guest back to the time picker.
      if (err.code === 'hold_expired' || err.code === 'not_found') return recoverAfterRedirect(paymentIntent.id);
      if (err.code === 'slot_unavailable') {
        showError(new Error('De tijd was intussen niet meer vrij. Neem contact op met de zaak voor je aanbetaling.'));
        return;
      }
      throw err;
    }
  }
  throw new CallyndarError('payment_pending', 'De betaling is nog niet bevestigd. Probeer het zo opnieuw.', 0);
}

async function book(details, paymentIntentId) {
  const turnstile_token = await takeToken();
  const body = Object.assign({ hold_id: state.hold.hold_id, turnstile_token }, details, paymentIntentId ? { payment_intent_id: paymentIntentId } : {});
  const headers = { 'Idempotency-Key': crypto.randomUUID() };
  let result;
  try {
    result = await api('POST', '/bookings', body, headers);
  } catch (err) {
    // A network error or 5xx: retry ONCE with the same key (the server replays the first answer).
    if (err.code !== 'network_error' && !(err.status >= 500)) throw err;
    result = await api('POST', '/bookings', body, headers);
  }
  done(result.booking);
}

// ── after an iDEAL / Bancontact redirect ──────────────────────────────────────
async function recoverAfterRedirect(paymentIntentId) {
  try {
    const { booking } = await api('POST', '/bookings/recover', { payment_intent_id: paymentIntentId });
    history.replaceState(null, '', location.pathname);
    done(booking);
  } catch (err) {
    if (err.code === 'deposit_required') return showError(new Error('Je betaling is nog niet bevestigd. Vernieuw de pagina over enkele seconden.'));
    if (err.code === 'slot_unavailable') return showError(new Error('De tijd was intussen niet meer vrij. Neem contact op met de zaak voor je aanbetaling.'));
    showError(err);
  }
}

// ── 8. confirmation ───────────────────────────────────────────────────────────
function done(booking) {
  if (state.stopTimer) state.stopTimer();
  const text = {
    confirmed: 'Je boeking is bevestigd. Je krijgt een bevestiging per e-mail.',
    pending: 'Je aanvraag is ontvangen. De zaak bevestigt ze zo snel mogelijk per e-mail.',
    waitlisted: 'Het is volzet: je staat op de wachtlijst. De zaak neemt contact met je op.',
  };
  $('cal-done-title').textContent = booking.status === 'confirmed' ? 'Geboekt!' : 'Bedankt!';
  $('cal-done-text').textContent = booking.date + ' om ' + booking.time + ' — ' + (text[booking.status] || text.pending);
  $('cal-manage').href = booking.manage_url;
  show('step-done');
}

function loadScript(src) {
  return new Promise((resolve, reject) => {
    if (document.querySelector('script[src="' + src + '"]')) return resolve();
    const s = document.createElement('script'); s.src = src; s.onload = resolve; s.onerror = () => reject(new Error('Kon ' + src + ' niet laden.'));
    document.head.append(s);
  });
}

start();
</script>
</body>
</html>
```

# Example: callyndar-api.js

```js
// callyndar-api.js — thin fetch wrapper for the Callyndar Booking API v1.
// ES module, no dependencies. Copy it into your site and import it:
//
//   import { createCallyndarClient, holdTimer, CallyndarError } from './callyndar-api.js';
//   const api = createCallyndarClient({ key: 'cal_pk_live_…', baseUrl: 'https://www.callyndar.com/api/v1' });
//   const { venue } = await api.venue();
//
// Docs: https://www.callyndar.com/developers — the key is a publishable key
// (public by design). Never put any other secret in your site.

export class CallyndarError extends Error {
    constructor({ code, message, status, details, requestId, retryAfter }) {
        super(message || code || 'Request failed');
        this.name = 'CallyndarError';
        this.code = code || 'server_error';
        this.status = status || 0;
        this.details = details || null;
        this.requestId = requestId || null;
        /** Seconds to wait (rate_limited / idempotency_conflict), or null. */
        this.retryAfter = retryAfter;
    }
}

function list(ids) {
    if (!ids) return undefined;
    return ids.map((id) => (id == null ? '' : id)).join(',');
}

function query(params) {
    const q = new URLSearchParams();
    for (const [k, v] of Object.entries(params || {})) {
        if (v === undefined || v === null || v === '') continue;
        q.set(k, Array.isArray(v) ? list(v) : String(v));
    }
    const s = q.toString();
    return s ? `?${s}` : '';
}

function newIdempotencyKey() {
    if (globalThis.crypto && typeof globalThis.crypto.randomUUID === 'function') return globalThis.crypto.randomUUID();
    return `idem-${Date.now()}-${Math.random().toString(36).slice(2, 12)}`;
}

export function createCallyndarClient({ key, baseUrl = 'https://www.callyndar.com/api/v1' }) {
    if (!key || !key.startsWith('cal_pk_')) throw new Error('createCallyndarClient: pass your publishable key (cal_pk_live_…)');
    const base = baseUrl.replace(/\/+$/, '');

    async function request(method, path, { body, headers } = {}) {
        let res;
        try {
            res = await fetch(`${base}${path}`, {
                method,
                headers: {
                    Authorization: `Bearer ${key}`,
                    ...(body !== undefined ? { 'Content-Type': 'application/json' } : {}),
                    ...(headers || {}),
                },
                body: body !== undefined ? JSON.stringify(body) : undefined,
            });
        } catch (err) {
            throw new CallyndarError({ code: 'network_error', message: 'No connection to Callyndar. Check your internet and try again.', status: 0, details: { cause: String(err) } });
        }
        const requestId = res.headers.get('Callyndar-Request-Id');
        const retryHeader = res.headers.get('Retry-After');
        const data = res.status === 204 ? null : await res.json().catch(() => null);
        if (!res.ok) {
            const e = (data && data.error) || {};
            throw new CallyndarError({
                code: e.code || (res.status === 403 ? 'forbidden_origin' : 'server_error'),
                message: e.message || `HTTP ${res.status}`,
                status: res.status,
                details: e.details,
                requestId: e.request_id || requestId,
                retryAfter: retryHeader ? Number(retryHeader) : null,
            });
        }
        return data;
    }

    return {
        venue: () => request('GET', '/venue'),
        services: () => request('GET', '/services'),
        providers: (serviceIds) => request('GET', `/providers${query({ service_ids: serviceIds })}`),
        calendar: (from, to, providerId) => request('GET', `/calendar${query({ from, to, provider_id: providerId })}`),
        /** params: { date, party_size, service_ids, variant_ids, pending_ids, provider_id } */
        availability: (params) => request('GET', `/availability${query(params)}`),
        /** params: { party_size, service_ids, variant_ids, pending_ids } */
        depositPolicy: (params) => request('GET', `/deposit-policy${query(params)}`),
        /** body: { date, time, party_size, service_ids, variant_ids, pending_ids, provider_id, session_id } */
        createHold: (body) => request('POST', '/holds', { body }),
        releaseHold: (holdId) => request('DELETE', `/holds/${encodeURIComponent(holdId)}`),
        /** body: { guest, notes, locale, turnstile_token } */
        deposit: (holdId, body) => request('POST', `/holds/${encodeURIComponent(holdId)}/deposit`, { body }),
        /**
         * body: { hold_id, guest, notes, locale, payment_intent_id, turnstile_token }
         * A fresh Idempotency-Key per booking attempt; one automatic retry with the
         * SAME key after a network error or a 5xx (safe: the server replays).
         */
        async book(body, { idempotencyKey } = {}) {
            const headers = { 'Idempotency-Key': idempotencyKey || newIdempotencyKey() };
            try {
                return await request('POST', '/bookings', { body, headers });
            } catch (err) {
                const retryable = err instanceof CallyndarError && (err.code === 'network_error' || err.status >= 500);
                if (!retryable) throw err;
                await new Promise((r) => setTimeout(r, 1000));
                return request('POST', '/bookings', { body, headers });
            }
        },
        recover: (paymentIntentId) => request('POST', '/bookings/recover', { body: { payment_intent_id: paymentIntentId } }),
    };
}

/**
 * Countdown for a hold. Calls onTick(secondsLeft) every second and onExpire()
 * once at expires_at. Returns a stop() function.
 */
export function holdTimer(expiresAt, onTick, onExpire) {
    const end = new Date(expiresAt).getTime();
    let done = false;
    const tick = () => {
        if (done) return;
        const left = Math.max(0, Math.round((end - Date.now()) / 1000));
        if (onTick) onTick(left);
        if (left === 0) {
            done = true;
            clearInterval(id);
            if (onExpire) onExpire();
        }
    };
    const id = setInterval(tick, 1000);
    tick();
    return () => { done = true; clearInterval(id); };
}

/** "4:05" for a number of seconds. */
export function formatCountdown(seconds) {
    const m = Math.floor(seconds / 60);
    const s = String(seconds % 60).padStart(2, '0');
    return `${m}:${s}`;
}

/** "€ 35,00" for cents (null → ''). */
export function formatPrice(cents, currency = 'EUR', locale = 'nl-BE') {
    if (cents == null) return '';
    return new Intl.NumberFormat(locale, { style: 'currency', currency }).format(cents / 100);
}
```
