# Yatoon Booking System — Automation & Webhooks

Covers outgoing webhooks and the automation endpoints Zapier, Make and n8n
connect to. The permission and privacy controls described here are in the 4.7.7
model-refresh test build.

## Setting up

1. *Yatoon → Settings → API keys* — create a key. It is shown once, begins
   `ytk_`, and is stored only as a SHA-256 hash. New keys expire after 90 days
   by default and only work with the selected permissions, bounded by the
   creating user's WordPress capabilities. New keys start with only `automation`
   selected; add booking and availability permissions only when the integration
   needs those actions.
2. *Yatoon → Settings → Webhooks* — add an endpoint URL, choose the events,
   and decide whether the payload should include customer contact details.
   Each endpoint has its own signing secret. "Send test webhook" delivers a
   `booking.test` event.

Sensitive customer fields are omitted from REST booking and customer responses
by default. Add the `sensitive_data` permission only when the connected service
needs those fields; then request `include_sensitive=1`. Existing keys retain
their previous route access for a 90-day rotation window from the first load of
this 4.7.7 model-refresh build. Replace older keys with new least-privilege keys
and revoke the old credentials after reconnecting.

## Events

| Event | Fires when |
|---|---|
| `booking.created` | A booking is created through any path |
| `booking.cancelled` | Status becomes cancelled |
| `booking.rescheduled` | Start time changes |
| `booking.completed` | Status becomes completed |
| `booking.no_show` | Status becomes no-show |
| `booking.test` | Only from the "Send test webhook" button |

## Payload

`POST`, `Content-Type: application/json`:

```json
{
  "id": "0f9c2b3a-6d41-4a8e-9b77-2b6f1d4c8e55",
  "event": "booking.created",
  "created_at": "2026-10-02T18:00:03+00:00",
  "site": { "url": "https://example.com/", "name": "YoYo Nails" },
  "booking": {
    "id": 4821,
    "status": "confirmed",
    "service_id": 12,
    "service_name": "Acrylic Full Set",
    "staff_id": 3,
    "staff_name": "Mia",
    "start_time": "2026-10-02 14:00:00",
    "end_time": "2026-10-02 15:00:00",
    "timezone": "America/Indianapolis",
    "total": 65.0,
    "currency": "USD",
    "payment_status": "unpaid",
    "location_id": 1,
    "customer": {
      "name": "Ada Lovelace",
      "email": "ada@example.com",
      "phone": "+13175550142"
    }
  }
}
```

`booking.customer` is present **only** when that endpoint has "include
customer details" enabled. Leave it off for any consumer that does not need
personal data.

`start_time` and `end_time` are local wall-clock times in `booking.timezone`.

## Headers and signature verification

| Header | Value |
|---|---|
| `X-Yatoon-Event` | The event name |
| `X-Yatoon-Delivery` | Delivery UUID, stable across retries — use it to deduplicate |
| `X-Yatoon-Timestamp` | Unix seconds, as a string |
| `X-Yatoon-Signature` | `sha256=` + HMAC-SHA256 hex digest |
| `User-Agent` | `Yatoon/<installed plugin version>` |

The signature is computed over `timestamp + "." + rawBody`, keyed with that
endpoint's secret:

```
signature = HMAC_SHA256( X-Yatoon-Timestamp + "." + raw_request_body, endpoint_secret )
```

Node:

```js
const crypto = require('crypto');
function verify(req, secret) {
  const ts   = req.get('X-Yatoon-Timestamp');
  const sent = req.get('X-Yatoon-Signature') || '';
  const mine = 'sha256=' + crypto
    .createHmac('sha256', secret)
    .update(ts + '.' + req.rawBody)
    .digest('hex');
  const a = Buffer.from(sent), b = Buffer.from(mine);
  if (a.length !== b.length || !crypto.timingSafeEqual(a, b)) return false;
  return Math.abs(Date.now() / 1000 - Number(ts)) < 300;   // reject replays
}
```

PHP:

```php
$expected = 'sha256=' . hash_hmac( 'sha256', $timestamp . '.' . $raw_body, $secret );
if ( ! hash_equals( $expected, $signature_header ) ) { http_response_code( 400 ); exit; }
```

Verify against the **raw** body. Re-encoding the JSON changes the bytes and
the signature will not match.

## Delivery, retries and deduplication

* Delivery is asynchronous, on WP-Cron, one second after the event.
* Timeout 12 seconds. Redirects are not followed.
* `2xx` is success. Anything else, including a connection error, is retried
  up to **5 attempts total** with delays of **60s, 5min, 30min, 2h**. After
  the fifth attempt the delivery is abandoned and logged.
* Retries reuse the same `X-Yatoon-Delivery` UUID. Treat that value as an
  idempotency key — a `2xx` you sent after your own timeout will still be
  retried, so the same delivery can legitimately arrive twice.
* Outbound URLs go through an SSRF check: private and loopback address ranges
  are refused, with the resolved address cached for five minutes.
* Recent deliveries, their HTTP codes and failure reasons appear under
  *Settings → Webhooks*.

Respond quickly. Queue the work on your side and return `200` immediately
rather than doing it inside the request.

## Automation endpoints

Used by the Zapier/Make/n8n connectors. Same `yatoon/v1` namespace and the
same API key authentication as the REST API.

| Route | Method | Purpose |
|---|---|---|
| `/me` | GET | Connection test — confirms the key and reports the site |
| `/events` | GET | The event names available as triggers |
| `/subscriptions` | GET, POST | List or create a webhook subscription |
| `/subscriptions/{id}` | DELETE | Remove a subscription |
| `/triggers/{event}/sample` | GET | A sample payload, for building a Zap against real field names |

A subscription created this way gets the same signing, SSRF checks and retry
ladder as one added by hand in the admin.

If the webhook engine is not available on the site, these answer
`yatoon_webhooks_unavailable` (503).

## Creating bookings from automation

Use `POST /wp-json/yatoon/v1/bookings` — see `docs/rest-api.md`. Check
`GET /availability` first: the create call enforces the same rules and will
answer `yatoon_booking_conflict` (409) rather than double-book.

Booking creation through the API does not currently cover the front-end
extras — service options, tips and gift-card redemption. Those remain
front-end only.
