Developers
Signatures and tokens
How to check that a call really came from BookingNinja, how a venue connects your app, and how your app calls BookingNinja back.
Two things keep an app and BookingNinja honest with each other. BookingNinja signs every call it makes to your app, so your app can tell the call is real. Your app holds a token when it calls BookingNinja, so BookingNinja can tell which venue it is acting for.
What BookingNinja sends
Every call from BookingNinja to your app is a JSON POST to {base_url}/{path}. It carries these headers:
| Header | Value |
|---|---|
X-BN-Signature |
t=<unix seconds>,v1=<hex HMAC-SHA256 of "<t>.<raw body>">, made with your signing secret |
X-BN-Installation |
The installation's id, ins_…. It is one app on one venue. |
X-BN-Request-Id |
Unique for each attempt. Put it in your logs. |
Idempotency-Key |
The same on every retry of one operation |
The body always carries a context with the installation, the venue and the venue's saved settings. A call about one booking also carries context.booking.
Checking the signature
Do this before you read anything else in the request.
- Read the raw body, exactly as it arrived. Do not parse it and encode it again: the signature covers the bytes, and a different encoding gives a different signature.
- Split the
X-BN-Signatureheader on commas. Taket, the time BookingNinja signed the call, in unix seconds, and everyv1value. - Reject the call if
tis more than 300 seconds from your clock, in either direction. This stops someone replaying an old call. - Compute
HMAC-SHA256of the text<t>.<raw body>(the number, a full stop, then the body), keyed with your signing secret, as lowercase hex. - Compare it with each
v1value in constant time. If one matches, the call is genuine.
A constant-time comparison matters. An ordinary string comparison stops at the first different character, and the time it takes can tell an attacker how much of a guess was right.
If the check fails, reply 401. The call fails, so a guest's step is skipped, but BookingNinja does not count a 4xx reply towards pausing your app. A wrong signing secret is easy to spot in Recent calls as a run of http_401.
<?php
// verify.php
function verify(string $header, string $body, string $secret, int $tolerance = 300): bool
{
$time = null;
$signatures = [];
foreach (explode(',', $header) as $part) {
[$key, $value] = array_pad(explode('=', trim($part), 2), 2, '');
if ($key === 't' && ctype_digit($value)) {
$time = (int) $value;
} elseif ($key === 'v1' && $value !== '') {
$signatures[] = strtolower($value);
}
}
if ($time === null || $signatures === [] || abs(time() - $time) > $tolerance) {
return false;
}
$expected = hash_hmac('sha256', $time.'.'.$body, $secret);
foreach ($signatures as $signature) {
if (hash_equals($expected, $signature)) {
return true;
}
}
return false;
}
// verify.mjs
import { createHmac, timingSafeEqual } from 'node:crypto';
// rawBody is the Buffer you read from the request, before any JSON parsing.
export function verify(header, rawBody, secret, tolerance = 300) {
let time = null;
const signatures = [];
for (const part of String(header ?? '').split(',')) {
const [key, value = ''] = part.trim().split('=', 2);
if (key === 't' && /^\d+$/.test(value)) time = Number(value);
else if (key === 'v1' && value) signatures.push(value.toLowerCase());
}
if (time === null || signatures.length === 0) return false;
if (Math.abs(Date.now() / 1000 - time) > tolerance) return false;
const expected = Buffer.from(
createHmac('sha256', secret).update(`${time}.`).update(rawBody).digest('hex'));
return signatures.some((signature) => {
const given = Buffer.from(signature);
return given.length === expected.length && timingSafeEqual(given, expected);
});
}
The default tolerance in both is 300 seconds, the same as BookingNinja's own.
To try your check from a terminal, sign a body yourself and send it:
BODY='{"context":{}}'
T=$(date +%s)
SIG=$(printf '%s.%s' "$T" "$BODY" | openssl dgst -sha256 -hmac "$BN_SIGNING_SECRET" -hex | sed 's/^.* //')
curl -X POST https://picker.example.com/availability \
-H "X-BN-Signature: t=$T,v1=$SIG" -H 'Content-Type: application/json' -d "$BODY"
When you rotate the signing secret (More, then Rotate signing secret on your app), every call from then on is signed with the new one. The old one stops working at once, and there is no overlap. Update your app straight after you rotate.
Retries and the idempotency key
BookingNinja may send the same operation more than once, for example when it did not hear your reply. Every attempt of one operation carries the same Idempotency-Key. A repeat with a key you have seen is a retry: return the first response and do not do the work again.
This matters most for holds, holds/confirm and actions. Store the first response against the key, and send it back for a repeat.
For events, the key is the event's own event_id.
How a venue connects your app
- Connect. The venue presses Connect on your app, in Settings, then Apps.
- Your install page (optional, recommended). If your manifest has an
install_url, BookingNinja sends the browser there first, with?authorize_url=…added. Sign the venue in to your own service. Make a randomstateand remember it for this browser. Then send the browser on toauthorize_urlwithstateadded as a further parameter (500 characters at most). - Consent. The venue sees what your app asks for: the
scopesin your manifest, in the wording below. It approves. - Your callback. BookingNinja sends the browser to your
redirect_uriwithcode,return_urland, if you supplied one, yourstate, unchanged. - Exchange. Your app calls the token endpoint with the
code(below). - Back to BookingNinja. Redirect the browser to
return_url, unchanged, with nothing added. It may be on a partner's own admin domain, so do not compare its host with the token endpoint's.
An installation stays pending until your app has exchanged the code. BookingNinja calls nothing until then.
Why state matters
Without state, anyone could send a signed-in user of your service a link that completes their own BookingNinja connection in that user's browser. That would silently link the attacker's venue to the victim's account. state proves that the browser coming back is the one that started the flow.
On the callback, require a state that you made, for this browser, and use it once. Never accept a callback without one. If your manifest has no install_url, there is no state: ask the signed-in user to confirm before you link the installation to their account.
Exchanging the code
Call POST https://app.bookingninja.io/api/v1/apps/oauth/token with a JSON body. Keep the client secret on your server.
{
"grant_type": "authorization_code",
"client_id": "your client id",
"client_secret": "your client secret",
"code": "the code from the callback",
"redirect_uri": "https://picker.example.com/connected"
}
redirect_uri must equal the one in your manifest. The code is single use and valid for 300 seconds. The reply:
{
"access_token": "an access token",
"refresh_token": "a refresh token",
"token_type": "Bearer",
"expires_in": 3600,
"installation_id": "ins_8f2k4a9b",
"scope": "bookings:read"
}
installation_id is the same value as context.installation_id and the X-BN-Installation header. Use it to match a call to the venue. scope lists the granted scopes, separated by spaces.
Refreshing
An access token lasts 3600 seconds. A refresh token lasts 90 days. Refresh before the access token runs out, or when a call comes back 401.
{
"grant_type": "refresh_token",
"client_id": "your client id",
"client_secret": "your client secret",
"refresh_token": "the refresh token you hold"
}
A refresh token works once. The reply is a new pair, and you must store it at once, before you use it. If your app sends the same code or refresh token again within 30 seconds of the first time, for example because a reply was lost, BookingNinja answers with another pair, and the earlier pair stays valid. After 30 seconds, a repeat looks like a stolen token. BookingNinja then revokes every token of the installation, and the venue has to connect again. If several processes can refresh, make them take turns with a lock.
The token endpoint allows 20 requests a minute for each client id and IP address, and 60 a minute for each IP address. Past that it answers 429 with the code rate_limited. Its other refusals are unsupported_grant_type, invalid_request and invalid_grant (all 400), and invalid_client (401).
Calling BookingNinja
Every call your app makes to BookingNinja is under /api/v1/apps on the same host as the token endpoint, and every body is JSON. Send the access token as Authorization: Bearer <access_token>. A token belongs to one installation and can never reach another venue's data.
| Call | Scope | What it does |
|---|---|---|
GET /api/v1/apps/installation |
none | The installation, the venue and the scopes the venue granted |
GET /api/v1/apps/bookings/{ref} |
bookings:read |
One booking your app is attached to, and your own saved data on it |
POST /api/v1/apps/bookings/{ref}/notes |
bookings:write_notes |
A note in the booking's history |
POST /api/v1/apps/bookings/{ref}/alerts |
bookings:alert |
An alert for the venue's staff |
PUT /api/v1/apps/bookings/{ref}/data |
none | Your app's own data on the booking, 4,096 bytes at most |
POST /api/v1/apps/catalogue/changed |
none | Your catalogue changed: fetch it again |
POST /api/v1/apps/blocks/refresh |
none | Your staff blocks changed for some bookings: fetch them again |
The scopes are:
| Scope | What the venue sees |
|---|---|
bookings:read |
See bookings that use this app |
bookings:write_notes |
Add notes to bookings that use this app |
bookings:alert |
Send alerts to your staff about bookings that use this app |
guests:read |
See the guest's name and contact details on those bookings |
A venue grants scopes when it connects. If you add a scope to your manifest later, venues already connected do not get it. Each has to connect again. Until then, a call that needs the scope is refused with 403 and the code insufficient_scope.
guests:read adds the guest's name, email address and phone number to a booking, once the booking is not a draft. Ask for it only if your app needs it.
A booking ref is the bkg_… value from context.booking.ref. Your app can reach a booking while its link to your app is live, and for 30 days after the link ends. Any other ref gets the same 404, whether it never existed or belongs to someone else.
The errors
Every error body is {"error": {"code": "...", "message": "..."}}.
| Status | Code | Meaning |
|---|---|---|
| 401 | invalid_token |
The token is missing, expired or revoked, or the installation is not active. Refresh it. |
| 403 | insufficient_scope |
The venue did not grant the scope this call needs |
| 403 | app_suspended |
BookingNinja has suspended your app |
| 403 | not_available |
Apps is not available for the venue, for example because it has closed |
| 404 | not_found |
No such booking for this installation |
| 422 | invalid_request |
The body is wrong. The message says what to fix. |
| 429 | rate_limited |
More than 300 calls a minute for this installation. Wait for the Retry-After seconds. |
Example: calling with a token, and refreshing
These keep one pair of tokens for one installation. A real app keeps a pair for each venue it is connected to, found by installation_id.
<?php
function bn(string $method, string $path, ?array $body = null, bool $retry = true): array
{
$tokens = loadTokens(); // your own storage
$ch = curl_init(getenv('BN_URL').'/api/v1/apps'.$path);
curl_setopt_array($ch, [CURLOPT_CUSTOMREQUEST => $method, CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => ['Authorization: Bearer '.$tokens['access_token'], 'Content-Type: application/json'],
CURLOPT_POSTFIELDS => $body === null ? null : json_encode($body)]);
$reply = json_decode((string) curl_exec($ch), true) ?? [];
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($status === 401 && $retry) {
refreshTokens();
return bn($method, $path, $body, false);
}
return [$status, $reply];
}
function refreshTokens(): void
{
$ch = curl_init(getenv('BN_URL').'/api/v1/apps/oauth/token');
curl_setopt_array($ch, [CURLOPT_POST => true, CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
CURLOPT_POSTFIELDS => json_encode(['grant_type' => 'refresh_token', 'client_id' => getenv('BN_CLIENT_ID'),
'client_secret' => getenv('BN_CLIENT_SECRET'), 'refresh_token' => loadTokens()['refresh_token']])]);
$pair = json_decode((string) curl_exec($ch), true);
saveTokens($pair); // store the new pair before anything else uses it
}
async function bn(method, path, body, retry = true) {
const { access_token } = await loadTokens(); // your own storage
const res = await fetch(`${process.env.BN_URL}/api/v1/apps${path}`, {
method,
headers: { Authorization: `Bearer ${access_token}`, 'Content-Type': 'application/json' },
body: body === undefined ? undefined : JSON.stringify(body),
});
if (res.status === 401 && retry) {
await refreshTokens();
return bn(method, path, body, false);
}
return [res.status, await res.json().catch(() => ({}))];
}
async function refreshTokens() {
const { refresh_token } = await loadTokens();
const res = await fetch(`${process.env.BN_URL}/api/v1/apps/oauth/token`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ grant_type: 'refresh_token', client_id: process.env.BN_CLIENT_ID,
client_secret: process.env.BN_CLIENT_SECRET, refresh_token }),
});
await saveTokens(await res.json()); // store the new pair before anything else uses it
}
BN_URL is https://app.bookingninja.io.
The next guide, The guest step, is where most apps spend their time.