> Documentation index: https://docs.dev.repp.co.il/llms.txt - fetch it to find every page of these docs.

# Webhooks

Webhooks are **the source of truth** for your records. They come whether or not anyone has your page open, and are sent again until your server takes them. The SDK's [Events](https://docs.dev.repp.co.il/partners-events.md) say the same things to an open page, sooner, as a hint for the screen.

You hear only about what came from your system - a class whose request was posted from the panel, a room opened for rent from it - of businesses connected through your key. Like everything Repp tells you, an event carries ids, states, a booking's day and hours, and at most a chosen trainer's short name and photo. **Never a phone, a full name, a renter or an amount.**

## Set your endpoint

One endpoint per partner, an https address on your server. Set it from your server with your secret key (`Authorization: Bearer rsk_…`), as you make [sessions](https://docs.dev.repp.co.il/partners-sessions.md):

**Your endpoint**

| Call | Body | What it does |
| --- | --- | --- |
| `POST /partner/v1/webhook-endpoint` | `{ "url": "https://…" }` | Sets your endpoint, an https address on your server, and answers `201` with its `url`, `created` and signing `secret`, **shown this once**. Setting it again replaces the address and the secret; the old secret stops signing at once. `400 bad_webhook_url` for an address that is not https to a public host, test keys too: Repp sends from its cloud, so reach your own machine through a tunnel such as ngrok. |
| `GET /partner/v1/webhook-endpoint` | — | `200` with your endpoint's `url`, when it was set (`created`) and, while deliveries keep failing, since when (`failing_since`, else `null`). Never its secret. `404 not_found` when none is set. |
| `DELETE /partner/v1/webhook-endpoint` | — | `200 { "deleted": true }`, or `404 not_found`. Nothing is sent after, and events not delivered yet are dropped. |
| `POST /partner/v1/webhook-endpoint/test` | — | `202` with the test event's `id` (`evt_test_…`): one signed test event goes to your endpoint now, with made-up ids and `livemode: false`, so you can see your code verify and answer it. `404 not_found` with no endpoint; at most 30 an hour. |

**cURL**

```bash
curl -X POST "https://api.dev.repp.co.il/partner/v1/webhook-endpoint" \
  -H "Authorization: Bearer $REPP_SECRET_KEY" \
  -H "Content-Type: application/json" \
  -d '{
  "url": "https://app.example.com/repp/webhooks"
}'
```

**JavaScript**

```js
const response = await fetch("https://api.dev.repp.co.il/partner/v1/webhook-endpoint", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.REPP_SECRET_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    "url": "https://app.example.com/repp/webhooks"
  }),
});
if (!response.ok) throw new Error(`Repp answered ${response.status}`);
const { secret } = await response.json();
// Store secret as REPP_WEBHOOK_SECRET: it is shown only now.
```

**TypeScript**

```ts
interface WebhookEndpoint {
  url: string;
  /** Shown once: keep it with your secret key. */
  secret: string;
}

const response = await fetch("https://api.dev.repp.co.il/partner/v1/webhook-endpoint", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.REPP_SECRET_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    "url": "https://app.example.com/repp/webhooks"
  }),
});
if (!response.ok) throw new Error(`Repp answered ${response.status}`);
const { secret } = (await response.json()) as WebhookEndpoint;
// Store secret as REPP_WEBHOOK_SECRET: it is shown only now.
```

**Python**

```python
import os

import requests

response = requests.post(
    "https://api.dev.repp.co.il/partner/v1/webhook-endpoint",
    headers={"Authorization": f"Bearer {os.environ['REPP_SECRET_KEY']}"},
    json={
        "url": "https://app.example.com/repp/webhooks",
    },
    timeout=30,
)
response.raise_for_status()
secret = response.json()["secret"]
# Store secret as REPP_WEBHOOK_SECRET: it is shown only now.
```

**PHP**

```php
<?php
$ch = curl_init("https://api.dev.repp.co.il/partner/v1/webhook-endpoint");
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_HTTPHEADER => [
        "Authorization: Bearer " . getenv("REPP_SECRET_KEY"),
        "Content-Type: application/json",
    ],
    CURLOPT_POSTFIELDS => json_encode([
        "url" => "https://app.example.com/repp/webhooks",
    ]),
]);
$endpoint = json_decode(curl_exec($ch), true);
if (curl_getinfo($ch, CURLINFO_RESPONSE_CODE) >= 400) {
    throw new RuntimeException($endpoint["error"]["code"]);
}
// Store $endpoint["secret"] as REPP_WEBHOOK_SECRET: it is shown only now.
```

> **Warning:** The signing secret is shown once, when you set the endpoint. Keep it on your server beside your secret key, never in a page or a repository. If it may have leaked, set the endpoint again: you get a new secret, and the old one stops at once.

## An event

Each event is one `POST` of JSON to your endpoint, with the `Repp-Signature` header:

```json
{
  "id": "0b6e4f1a-9c2d-4e3f-8a7b-5c6d7e8f9a0b",
  "object": "event",
  "type": "class.substitute_chosen",
  "created": 1765123200,
  "livemode": false,
  "partner_business_id": "4012",
  "data": {
    "partner_class_id": "30146899",
    "partner_room_id": null,
    "repp_request_id": "5e2f8a1c-3b4d-4c6e-9f0a-1b2c3d4e5f6a",
    "repp_space_id": null,
    "repp_booking_id": null,
    "repp_series_id": null,
    "state": "chosen",
    "offers_count": 2,
    "trainer": {
      "display_name": "דנה כ.",
      "photo_url": null
    },
    "date": null,
    "start_hour": null,
    "end_hour": null,
    "weekly": null
  }
}
```

**Event fields**

| Field | Type | Description |
| --- | --- | --- |
| `id` | string | The event's id. A retry carries the same one: handle each id once. |
| `object` | `event` | Always `event`. |
| `type` | string | One of the types below. |
| `created` | integer | When it happened, in Unix seconds. Use it to order events, since they may arrive out of order. |
| `livemode` | boolean | `false` for test keys and test events. |
| `partner_business_id` | string | Your id of the business, as your server sent it in its sessions. |
| `data` | object | What happened, in the fields below; a field that does not apply is `null`. |

**data**

| Field | Type | Description |
| --- | --- | --- |
| `partner_class_id` | string or null | Your id of the class, for a `class.*` event. |
| `partner_room_id` | string or null | Your id of the room, for a `room.*` event. |
| `repp_request_id` | string or null | Repp's id of the request for a substitute trainer. |
| `repp_space_id` | string or null | Repp's id of the space your room was opened as. |
| `repp_booking_id` | string or null | Repp's id of the booking. With `date`, the key of one block in your calendar. |
| `repp_series_id` | string or null | For one week of a weekly booking: Repp's id of that weekly booking. `null` otherwise. |
| `state` | string | A class's state (`none`, `looking`, `offers`, `chosen`, `cancelled`, `no_one`), a booking's (`pending`, `confirmed`, `cancelled`), or `open` for a room just opened for rent. |
| `offers_count` | integer or null | How many offers wait on the class. |
| `trainer` | object or null | Once chosen: the substitute trainer's short name ("דנה כ.") and photo, never the full name or a phone. |
| `date` | YYYY-MM-DD or null | A booking's day, in Israel. |
| `start_hour`, `end_hour` | integer or null | A booking's whole hours, in Israel (`18`, `19`). |
| `weekly` | boolean or null | For a booking: `true` when it holds the same hours every week from `date` on. `null` for a class or a room just opened. |

## Event types

**Event types**

| Type | When | data |
| --- | --- | --- |
| `class.request_posted` | A request for a substitute trainer was posted from the panel for one of your classes. | `partner_class_id`, `repp_request_id`, `state` (`looking`). |
| `class.offer_received` | A trainer offered to teach the class. The business chooses on Repp. | `partner_class_id`, `repp_request_id`, `state` (`offers`), `offers_count`. |
| `class.substitute_chosen` | The business chose a substitute trainer: the class is covered. Show the trainer on the class in your calendar. | `partner_class_id`, `repp_request_id`, `state` (`chosen`), `trainer` (the short name, "דנה כ.", and photo only). |
| `class.trainer_cancelled` | The chosen substitute trainer cancelled coming. The class is not covered any more. | `partner_class_id`, `repp_request_id`, `state` (where the request stands now), `trainer` `null`. |
| `class.request_closed` | The request ended with nobody coming: the business cancelled it, or its hour came with nobody chosen. | `partner_class_id`, `repp_request_id`, `state` (`cancelled` or `no_one`). |
| `room.space_opened` | One of your rooms was opened for rent as a space on Repp, from the panel. | `partner_room_id`, `repp_space_id`, `state` (`open`). |
| `room.booking_requested` | A trainer asked to book the room for a day and hours, and the request waits for the business's yes. Hold the room softly, or warn. | `partner_room_id`, `repp_space_id`, `repp_booking_id`, `state` (`pending`), `date`, `start_hour`, `end_hour`, `weekly`. |
| `room.booking_confirmed` | The room is booked for a day and hours: booked at once, the business said yes, or a week of a weekly booking was paid. Block the room. | `partner_room_id`, `repp_space_id`, `repp_booking_id`, `state` (`confirmed`), `date`, `start_hour`, `end_hour`, `weekly`, and for one week of a weekly booking `repp_series_id`. |
| `room.booking_cancelled` | A booking of the room went: cancelled by either side, declined, a request that ran out, or a week of a weekly booking that was not paid. Free the room (a weekly one: every week still ahead). | `partner_room_id`, `repp_space_id`, `repp_booking_id`, `state` (`cancelled`), `date`, `start_hour`, `end_hour`, `weekly`, and for one week of a weekly booking `repp_series_id`. |

A room's events are about one booking. Key your blocks by `repp_booking_id` and `date`, never by hours. A booking with `weekly: true` holds those hours every week from `date` on, until a `room.booking_cancelled` with the same `repp_booking_id` frees every week still ahead. Each week of it is also told on its own about two days before, as a booking with its own `repp_booking_id` and `repp_series_id` naming the weekly one: `room.booking_confirmed` when that week was paid, `room.booking_cancelled` when it was not (that day is free, the weekly booking goes on) or when it went with its weekly booking.

## Verify the signature

Check every event before you trust it. `Repp-Signature` looks like `t=1765123200,v1=5257a869e7…`: `t` is when Repp signed it (Unix seconds), and `v1` is the hex HMAC-SHA256 of `<t>.<raw body>` with your signing secret.

- Take the **raw body**, the exact bytes Repp sent, before any JSON parsing: parsed and written again, it is not the same text.
- Read `t` and every `v1` from the header.
- Make the HMAC-SHA256 of `t`, a dot and the raw body, with your signing secret, in hex.
- Compare it with each `v1` in **constant time**, and refuse when none matches.
- Refuse a `t` more than 5 minutes from your clock, so an old event recorded on the way cannot be played again.

**JavaScript**

```js
import crypto from "node:crypto";
import express from "express";

const TOLERANCE = 300; // seconds

/** True when Repp-Signature is Repp's signature of this very body, made in the last 5 minutes. */
function verifyRepp(header, rawBody, secret) {
  const pairs = (header ?? "").split(",").map((part) => part.trim().split("="));
  const t = pairs.find(([key]) => key === "t")?.[1];
  const signatures = pairs.filter(([key]) => key === "v1").map(([, value]) => value);
  if (!t || !/^\d+$/.test(t) || signatures.length === 0) return false;
  if (Math.abs(Date.now() / 1000 - Number(t)) > TOLERANCE) return false;
  const expected = crypto.createHmac("sha256", secret).update(`${t}.`).update(rawBody).digest("hex");
  return signatures.some(
    (signature) => signature?.length === expected.length && crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected)),
  );
}

const app = express();

// The raw body: the signature is over the exact bytes Repp sent, never over parsed JSON.
app.post("/repp/webhooks", express.raw({ type: "application/json" }), (req, res) => {
  if (!verifyRepp(req.get("Repp-Signature"), req.body, process.env.REPP_WEBHOOK_SECRET)) {
    return res.status(400).end();
  }
  const event = JSON.parse(req.body.toString());
  res.status(200).end(); // answer at once,
  queue.add(event.id, event); // then do the work, once per event.id
});
```

**TypeScript**

```ts
import crypto from "node:crypto";
import express from "express";

interface ReppWebhookEvent {
  id: string; // the idempotency key: handle each id once
  object: "event";
  type: "class.request_posted" | "class.offer_received" | "class.substitute_chosen" | "class.trainer_cancelled" | "class.request_closed" | "room.space_opened" | "room.booking_requested" | "room.booking_confirmed" | "room.booking_cancelled";
  created: number; // Unix seconds
  livemode: boolean;
  partner_business_id: string;
  data: {
    partner_class_id: string | null;
    partner_room_id: string | null;
    repp_request_id: string | null;
    repp_space_id: string | null;
    repp_booking_id: string | null;
    state: string;
    offers_count: number | null;
    trainer: { display_name: string; photo_url: string | null } | null;
    date: string | null;
    start_hour: number | null;
    end_hour: number | null;
  };
}

const TOLERANCE = 300; // seconds

/** True when Repp-Signature is Repp's signature of this very body, made in the last 5 minutes. */
function verifyRepp(header: string | undefined, rawBody: Buffer, secret: string): boolean {
  const pairs = (header ?? "").split(",").map((part) => part.trim().split("="));
  const t = pairs.find(([key]) => key === "t")?.[1];
  const signatures = pairs.filter(([key]) => key === "v1").map(([, value]) => value);
  if (!t || !/^\d+$/.test(t) || signatures.length === 0) return false;
  if (Math.abs(Date.now() / 1000 - Number(t)) > TOLERANCE) return false;
  const expected = crypto.createHmac("sha256", secret).update(`${t}.`).update(rawBody).digest("hex");
  return signatures.some(
    (signature) => signature?.length === expected.length && crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected)),
  );
}

const app = express();

// The raw body: the signature is over the exact bytes Repp sent, never over parsed JSON.
app.post("/repp/webhooks", express.raw({ type: "application/json" }), (req, res) => {
  if (!verifyRepp(req.get("Repp-Signature"), req.body, process.env.REPP_WEBHOOK_SECRET!)) {
    return res.status(400).end();
  }
  const event = JSON.parse(req.body.toString()) as ReppWebhookEvent;
  res.status(200).end(); // answer at once,
  queue.add(event.id, event); // then do the work, once per event.id
});
```

**Python**

```python
import hashlib
import hmac
import os
import time

from flask import Flask, abort, request

TOLERANCE = 300  # seconds


def verify_repp(header, raw_body, secret):
    """True when Repp-Signature is Repp's signature of this very body, made in the last 5 minutes."""
    pairs = [part.strip().split("=", 1) for part in (header or "").split(",") if "=" in part]
    timestamps = [value for key, value in pairs if key == "t"]
    signatures = [value for key, value in pairs if key == "v1"]
    if not timestamps or not timestamps[0].isdigit() or not signatures:
        return False
    t = timestamps[0]
    if abs(time.time() - int(t)) > TOLERANCE:
        return False
    expected = hmac.new(secret.encode(), f"{t}.".encode() + raw_body, hashlib.sha256).hexdigest()
    return any(hmac.compare_digest(expected, signature) for signature in signatures)


app = Flask(__name__)


@app.post("/repp/webhooks")
def repp_webhooks():
    # The raw body: the signature is over the exact bytes Repp sent, never over parsed JSON.
    if not verify_repp(request.headers.get("Repp-Signature"), request.get_data(), os.environ["REPP_WEBHOOK_SECRET"]):
        abort(400)
    event = request.get_json()
    queue.enqueue(event["id"], event)  # do the work later, once per event["id"]
    return "", 200
```

**PHP**

```php
<?php
/** True when Repp-Signature is Repp's signature of this very body, made in the last 5 minutes. */
function verify_repp(?string $header, string $rawBody, string $secret, int $tolerance = 300): bool
{
    $t = null;
    $signatures = [];
    foreach (explode(",", $header ?? "") as $part) {
        [$key, $value] = array_pad(explode("=", trim($part), 2), 2, "");
        if ($key === "t") $t = $value;
        if ($key === "v1") $signatures[] = $value;
    }
    if ($t === null || !ctype_digit($t) || !$signatures || abs(time() - (int) $t) > $tolerance) {
        return false;
    }
    $expected = hash_hmac("sha256", $t . "." . $rawBody, $secret);
    foreach ($signatures as $signature) {
        if (hash_equals($expected, $signature)) return true;
    }
    return false;
}

// The raw body: the signature is over the exact bytes Repp sent, never over parsed JSON.
$rawBody = file_get_contents("php://input");
if (!verify_repp($_SERVER["HTTP_REPP_SIGNATURE"] ?? null, $rawBody, getenv("REPP_WEBHOOK_SECRET"))) {
    http_response_code(400);
    exit;
}
$event = json_decode($rawBody, true);
enqueue($event["id"], $event); // do the work later, once per $event["id"]
http_response_code(200);
```

> **Note:** cURL sends requests and cannot receive one, so verifying is shown in the four languages a server runs. Answer a bad signature with `400` and do nothing else.

## Answer fast, then work

- Answer **2xx within a few seconds**, before the work: put the event on your own queue and answer. A slow answer counts as a failure and the event comes again.
- Any answer that is not 2xx, a timeout or a connection that fails is a failure.
- Answer 2xx to an event type you do not use, so it is not sent again.

## Retries

An event that was not answered with a 2xx is sent again, with growing gaps between tries, for 3 days; after that it is dropped. Every try carries the same `id` and is signed again, with a new `t`. When your server was down for a while, a messenger that boots also tells its page each room's whole window, `room_bookings` (see [Events](https://docs.dev.repp.co.il/partners-events.md)).

## Each event once

The same event can come more than once: a retry after your answer was lost, or a try that crossed your answer. Keep the `id` of each event you handled, and answer 2xx to one you already have without doing its work again.

## Order is not guaranteed

Events can arrive out of order: a retry of an older event can come after a newer one. Keep, for each class and each booking day, the `created` of the last event you applied, and skip an event older than it. `data.state` is where the item stands at that event, so the newest one is always right.

## Test and live

- `POST /partner/v1/webhook-endpoint/test` sends one signed test event to your endpoint now, so you can try your verification before any business is connected.
- Events of test keys and test events carry `livemode: false`.
