Developers

Getting started

From nothing to your step on a test booking. Register an app, write a manifest, connect it to your own venue and make a booking.

What you will build

You will build a small app that adds a "Choose a package" step to a venue's booking. The guest picks one of two packages. The Plus package costs five pounds and only one booking can hold it for a given time. At the end you will see your step on a test booking at your own venue.

You need:

  • A BookingNinja account with a venue you own. An app that BookingNinja has not approved yet can be connected only by its developer, on venues the developer owns.
  • A web server on the public internet. BookingNinja calls your app from its own servers, over HTTPS on port 443. It refuses private addresses, addresses with a port other than 443, and http:// addresses. While you build on your own machine, put a tunnel in front of it.

The code below is in PHP and in Node. Use whichever you prefer. Both do the same thing.

1. Register your app

In the venue admin, open Settings, then Apps, then Build your own app, and choose Register an app. Give your app a name and paste a manifest. The name you type replaces the name in the manifest.

A manifest is a JSON file that tells BookingNinja where your app lives and what it adds. This is the smallest one that adds a guest step:

json
{
  "name": "Package Picker",
  "description": "Lets guests choose a package for their visit.",
  "base_url": "https://picker.example.com",
  "redirect_uri": "https://picker.example.com/connected",
  "scopes": [],
  "extension_points": {
    "guest_step": { "default_label": "Choose a package" },
    "guest_summary": true
  },
  "catalogue": { "sync": false }
}
  • base_url is where BookingNinja sends its calls. Every endpoint path is added to it, so the guest step is {base_url}/guest-step.
  • redirect_uri is where BookingNinja sends the browser after a venue connects your app.
  • scopes lists what your app may do through BookingNinja's API. This app calls nothing, so the list is empty.
  • guest_step adds the step. default_label is the step's name in the booking flow.
  • guest_summary says your app returns a summary for the guest's confirmation.
  • catalogue.sync is false because this app has no list of items for BookingNinja to copy. Without it BookingNinja would ask your app for a catalogue that does not exist.

When you register, BookingNinja shows three values. They appear once. Copy them now.

Value What it is for
Client id Names your app when it asks BookingNinja for tokens.
Client secret Your app sends it with the client id to exchange a code for tokens. Keep it on your server.
Signing secret BookingNinja signs every call to your app with it. Your app checks the signature.

If you lose a secret, choose More on the app, then Rotate client secret or Rotate signing secret. The old value stops working straight away.

Your app starts as a draft. A draft's manifest changes the moment you save it.

2. Write the app

Your app answers five calls from BookingNinja and one browser redirect:

Call What it asks
POST /guest-step What should the guest see on your step?
POST /availability Which items are taken for this slot?
POST /holds Hold what the guest chose, and say what it costs.
POST /holds/confirm The booking is complete: turn the hold into a reservation.
POST /holds/release Let go of a hold or a reservation.
GET /connected The venue approved the connection (your redirect_uri).

Every call is a JSON POST with a signature in the X-BN-Signature header. Check it first. The next guide, Signatures and tokens, gives the verify() function used below.

Every reply must be a JSON object, even when it has nothing to say. Send {}, never an empty body.

The router

This receives each call, checks the signature and passes the request to a handler. Each handler returns a status and a reply.

php
<?php
// index.php. Run with: php -S 127.0.0.1:8080 index.php
require __DIR__.'/verify.php';   // verify() from the next guide
require __DIR__.'/handlers.php'; // the handlers below

$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
if ($path === '/connected') {
    connected();
    exit;
}

$body = file_get_contents('php://input');
if (! verify($_SERVER['HTTP_X_BN_SIGNATURE'] ?? '', $body, getenv('BN_SIGNING_SECRET'))) {
    reply(401, ['error' => ['code' => 'bad_signature', 'message' => 'The signature did not match.']]);
}

$routes = ['/guest-step' => 'guestStep', '/availability' => 'availability', '/holds' => 'holds',
    '/holds/confirm' => 'confirm', '/holds/release' => 'release'];
if (! isset($routes[$path])) {
    reply(404, ['error' => ['code' => 'not_found', 'message' => 'No such endpoint.']]);
}
[$status, $data] = $routes[$path](json_decode($body, true));
reply($status, $data);

function reply(int $status, array $data): never
{
    http_response_code($status);
    header('Content-Type: application/json');
    echo json_encode((object) $data); // an empty array becomes {}
    exit;
}
js
// server.mjs. Run with: node server.mjs
import http from 'node:http';
import { verify } from './verify.mjs'; // verify() from the next guide
import { guestStep, availability, holds, confirm, release, connected } from './handlers.mjs';

const routes = { '/guest-step': guestStep, '/availability': availability, '/holds': holds,
  '/holds/confirm': confirm, '/holds/release': release };

const send = (res, status, data) => {
  res.writeHead(status, { 'Content-Type': 'application/json' });
  res.end(JSON.stringify(data));
};

http.createServer(async (req, res) => {
  const chunks = [];
  for await (const chunk of req) chunks.push(chunk);
  const raw = Buffer.concat(chunks); // the exact bytes, which the signature covers
  const url = new URL(req.url, 'http://localhost');

  if (url.pathname === '/connected') return connected(url, res);
  if (!verify(req.headers['x-bn-signature'], raw, process.env.BN_SIGNING_SECRET)) {
    return send(res, 401, { error: { code: 'bad_signature', message: 'The signature did not match.' } });
  }
  const handler = routes[url.pathname];
  if (!handler || req.method !== 'POST') {
    return send(res, 404, { error: { code: 'not_found', message: 'No such endpoint.' } });
  }
  const [status, data] = handler(JSON.parse(raw.toString('utf8')));
  send(res, status, data);
}).listen(8080);

Where the holds are kept

The handlers need somewhere to keep holds. The PHP version uses a small SQLite file. The Node version uses a Map, which forgets everything when the process restarts: use a database in a real app.

php
<?php
// handlers.php, part 1: storage and the packages
const OPTIONS = [
    'standard' => ['title' => 'Standard', 'text' => 'Your table and the house games.', 'price' => 0],
    'plus' => ['title' => 'Plus', 'text' => 'A reserved table with a host. One for each time.', 'price' => 500],
];

function db(): PDO
{
    static $db;
    if (! $db) {
        $db = new PDO('sqlite:'.__DIR__.'/app.db');
        $db->exec('create table if not exists holds (id text primary key, booking text, slot text,
            option_id text, expires_at integer, reservation_id text)');
    }
    return $db;
}

function slot(array $booking): string
{
    return $booking['date'].' '.$booking['start'];
}

function plusIsTaken(array $booking): bool
{
    $q = db()->prepare("select count(*) from holds where option_id = 'plus' and slot = ?
        and booking != ? and (reservation_id is not null or expires_at > ?)");
    $q->execute([slot($booking), $booking['ref'], time()]);
    return $q->fetchColumn() > 0;
}
js
// handlers.mjs, part 1: storage and the packages
const OPTIONS = {
  standard: { title: 'Standard', text: 'Your table and the house games.', price: 0 },
  plus: { title: 'Plus', text: 'A reserved table with a host. One for each time.', price: 500 },
};
const holdsById = new Map(); // id -> { id, booking, slot, option, expiresAt, reservationId }

const slot = (booking) => `${booking.date} ${booking.start}`;

function plusIsTaken(booking) {
  return [...holdsById.values()].some((h) => h.option === 'plus' && h.slot === slot(booking)
    && h.booking !== booking.ref && (h.reservationId || h.expiresAt > Date.now()));
}

context.booking is the booking the call is about: its ref, date, start, end and party_size. ref stays the same from the first draft to the end of the booking.

The step and availability

guest-step returns the blocks to draw. This one returns a single options block, a short fixed list of choices. An option can carry an unavailable_label to show it greyed out. That is how this app tells the guest the Plus package has gone.

availability is part of every step. BookingNinja calls it straight after guest-step. This app has no items to grey out, so it returns an empty list. If it answered with an error, BookingNinja would skip your step.

php
<?php
// handlers.php, part 2: guest-step and availability
function guestStep(array $req): array
{
    $booking = $req['context']['booking'];
    $options = [];
    foreach (OPTIONS as $id => $option) {
        $card = ['id' => $id, 'title' => $option['title'], 'description' => $option['text'],
            'price_hint' => $option['price'] > 0 ? '+£'.number_format($option['price'] / 100, 2) : 'Included'];
        if ($id === 'plus' && plusIsTaken($booking)) {
            $card['unavailable_label'] = 'Taken';
        }
        $options[] = $card;
    }
    return [200, ['title' => 'Choose a package',
        'blocks' => [['type' => 'options', 'id' => 'package', 'required' => true, 'options' => $options]]]];
}

function availability(array $req): array
{
    return [200, ['unavailable' => []]];
}
js
// handlers.mjs, part 2: guest-step and availability
export function guestStep({ context }) {
  const options = Object.entries(OPTIONS).map(([id, option]) => ({
    id,
    title: option.title,
    description: option.text,
    price_hint: option.price > 0 ? `+£${(option.price / 100).toFixed(2)}` : 'Included',
    ...(id === 'plus' && plusIsTaken(context.booking) ? { unavailable_label: 'Taken' } : {}),
  }));
  return [200, { title: 'Choose a package',
    blocks: [{ type: 'options', id: 'package', required: true, options }] }];
}

export function availability() {
  return [200, { unavailable: [] }];
}

Holds

holds runs when the guest chooses. The guest's choice arrives in answers, under the block's id. This app returns the price as lines. Each line has a label, a quantity and a unit_price in the venue currency's minor units. In a venue that uses pounds, 500 is five pounds. BookingNinja adds the lines to the booking total.

If the choice has gone, reply 409 with the code unavailable and the ids that have gone. The guest sees your message and picks again.

There is one live hold for each booking. The expires_at you send back must not be earlier than the one BookingNinja asked for, so this app sends the same value back.

php
<?php
// handlers.php, part 3: holds
function holds(array $req): array
{
    $booking = $req['context']['booking'];
    $choice = $req['answers']['package'] ?? null;
    if (! isset(OPTIONS[$choice])) {
        return [422, ['error' => ['code' => 'invalid_request', 'message' => 'Choose a package.']]];
    }
    if ($choice === 'plus' && plusIsTaken($booking)) {
        return [409, ['error' => ['code' => 'unavailable', 'unavailable' => ['plus'],
            'message' => 'Sorry, the Plus package has just gone for that time.']]];
    }
    db()->prepare('delete from holds where booking = ? and reservation_id is null')->execute([$booking['ref']]);
    $id = 'hld_'.bin2hex(random_bytes(8));
    db()->prepare('insert into holds (id, booking, slot, option_id, expires_at) values (?, ?, ?, ?, ?)')
        ->execute([$id, $booking['ref'], slot($booking), $choice, strtotime($req['expires_at'])]);
    $price = OPTIONS[$choice]['price'];
    $lines = $price > 0 ? [['label' => OPTIONS[$choice]['title'].' package', 'quantity' => 1, 'unit_price' => $price]] : [];
    return [200, ['hold_id' => $id, 'expires_at' => $req['expires_at'], 'lines' => $lines]];
}
js
// handlers.mjs, part 3: holds
export function holds({ context, answers, expires_at }) {
  const booking = context.booking;
  const choice = answers?.package;
  if (!OPTIONS[choice]) {
    return [422, { error: { code: 'invalid_request', message: 'Choose a package.' } }];
  }
  if (choice === 'plus' && plusIsTaken(booking)) {
    return [409, { error: { code: 'unavailable', unavailable: ['plus'],
      message: 'Sorry, the Plus package has just gone for that time.' } }];
  }
  for (const [id, h] of holdsById) if (h.booking === booking.ref && !h.reservationId) holdsById.delete(id);
  const id = `hld_${crypto.randomUUID()}`;
  holdsById.set(id, { id, booking: booking.ref, slot: slot(booking), option: choice,
    expiresAt: Date.parse(expires_at), reservationId: null });
  const { title, price } = OPTIONS[choice];
  const lines = price > 0 ? [{ label: `${title} package`, quantity: 1, unit_price: price }] : [];
  return [200, { hold_id: id, expires_at: expires_at, lines }];
}

The check and the insert are two steps here. Two guests can race for the Plus package. In a real app, do both in one database transaction, or give the database a unique index so the second insert fails.

Confirm and release

When the booking is complete, BookingNinja calls holds/confirm with the hold's id. Turn the hold into a reservation and reply with its id. A repeat of the same call must return the same reservation. The optional guest_summary is what the guest sees on their confirmation page and in emails.

holds/release tells your app to let go of a hold or a reservation. Reply 200 with {} even when it has already gone.

php
<?php
// handlers.php, part 4: holds/confirm and holds/release
function confirm(array $req): array
{
    $q = db()->prepare('select * from holds where id = ?');
    $q->execute([$req['hold_id']]);
    $hold = $q->fetch(PDO::FETCH_ASSOC);
    if (! $hold) {
        return [404, ['error' => ['code' => 'hold_not_found', 'message' => 'No such hold.']]];
    }
    if ($hold['reservation_id'] === null) {
        if ($hold['expires_at'] <= time()) {
            return [409, ['error' => ['code' => 'hold_expired', 'message' => 'That hold has expired.']]];
        }
        $hold['reservation_id'] = 'res_'.bin2hex(random_bytes(8));
        db()->prepare('update holds set reservation_id = ? where id = ?')->execute([$hold['reservation_id'], $hold['id']]);
    }
    $option = OPTIONS[$hold['option_id']];
    return [200, ['reservation_id' => $hold['reservation_id'],
        'guest_summary' => ['heading' => 'Your package', 'lines' => [['label' => $option['title'], 'note' => $option['text']]]]]];
}

function release(array $req): array
{
    db()->prepare('delete from holds where id = ? or reservation_id = ?')
        ->execute([$req['hold_id'] ?? '', $req['reservation_id'] ?? '']);
    return [200, []];
}
js
// handlers.mjs, part 4: holds/confirm and holds/release
export function confirm({ hold_id }) {
  const hold = holdsById.get(hold_id);
  if (!hold) return [404, { error: { code: 'hold_not_found', message: 'No such hold.' } }];
  if (!hold.reservationId) {
    if (hold.expiresAt <= Date.now()) {
      return [409, { error: { code: 'hold_expired', message: 'That hold has expired.' } }];
    }
    hold.reservationId = `res_${crypto.randomUUID()}`;
  }
  const option = OPTIONS[hold.option];
  return [200, { reservation_id: hold.reservationId,
    guest_summary: { heading: 'Your package', lines: [{ label: option.title, note: option.text }] } }];
}

export function release({ hold_id, reservation_id }) {
  for (const [id, h] of holdsById) {
    if (id === hold_id || (reservation_id && h.reservationId === reservation_id)) holdsById.delete(id);
  }
  return [200, {}];
}

The callback

A venue connects your app with the Connect button. BookingNinja then sends the browser to your redirect_uri with a one-time code and a return_url. Exchange the code for tokens, then send the browser on to return_url. The installation stays pending until you do: until then BookingNinja calls nothing.

The token endpoint is https://app.bookingninja.io/api/v1/apps/oauth/token.

php
<?php
// handlers.php, part 5: the callback
function connected(): void
{
    $ch = curl_init(getenv('BN_URL').'/api/v1/apps/oauth/token'); // https://app.bookingninja.io
    curl_setopt_array($ch, [CURLOPT_POST => true, CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
        CURLOPT_POSTFIELDS => json_encode(['grant_type' => 'authorization_code',
            'client_id' => getenv('BN_CLIENT_ID'), 'client_secret' => getenv('BN_CLIENT_SECRET'),
            'code' => $_GET['code'] ?? '', 'redirect_uri' => 'https://picker.example.com/connected'])]);
    $tokens = json_decode((string) curl_exec($ch), true);
    if (curl_getinfo($ch, CURLINFO_HTTP_CODE) !== 200 || ! isset($tokens['installation_id'])) {
        http_response_code(502);
        exit('Could not connect to BookingNinja.');
    }
    // Keep installation_id, access_token and refresh_token with your own record of this venue.
    header('Location: '.$_GET['return_url'], true, 302);
}
js
// handlers.mjs, part 5: the callback
export async function connected(url, res) {
  const reply = await fetch(`${process.env.BN_URL}/api/v1/apps/oauth/token`, { // https://app.bookingninja.io
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ grant_type: 'authorization_code',
      client_id: process.env.BN_CLIENT_ID, client_secret: process.env.BN_CLIENT_SECRET,
      code: url.searchParams.get('code'), redirect_uri: 'https://picker.example.com/connected' }),
  });
  const tokens = await reply.json().catch(() => ({}));
  if (!reply.ok || !tokens.installation_id) {
    res.writeHead(502).end('Could not connect to BookingNinja.');
    return;
  }
  // Keep installation_id, access_token and refresh_token with your own record of this venue.
  res.writeHead(302, { Location: url.searchParams.get('return_url') }).end();
}

This manifest has no install_url, so the callback carries no state. Before you ship, add an install_url and check the state it brings back. Signatures and tokens explains why.

3. Connect it to your own venue

Set the environment variables your code reads: BN_SIGNING_SECRET, BN_CLIENT_ID, BN_CLIENT_SECRET and BN_URL. Start your app and make sure the tunnel reaches it.

Then, in the venue admin, open Settings, then Apps. Your app is under Available apps. Choose Connect, check the consent screen and approve. BookingNinja sends the browser to your /connected address, your app exchanges the code, and the app moves to Connected apps.

4. Switch the step on for a session

A step does nothing until a venue switches it on for a session. Open the session in the session editor and go to its Apps tab. Switch on "Offer Choose a package on this session" and save.

5. Make a test booking

Open your venue's booking page and book that session. After you pick a date, a time and a party size, your step appears. Choose Plus, finish the booking and look at your confirmation page: the package is in the summary.

Now book again for the same time. The Plus package shows as "Taken".

If something does not work, go back to Build your own app and choose Recent calls on your app. It lists the last 50 calls BookingNinja made to your app, with the endpoint, the status, how long your app took and a short error category. Testing explains each category.