Skip to main content

Roll your own

No skin at all. You pass your own element and callbacks to createBotProt, and BotProt fits into your page the way you design it.

Example​

<div id="botprot">Loading…</div>

<script type="module">
// OT is window.OpenTicket, once botprot.js is ready (see Usage).
const container = document.getElementById('botprot');

const token = await OT.createBotProt(identifier, {
show: () => container,
final: () => {
container.remove();
},
fail: (message) => {
container.textContent = message;
},
});
</script>
  • show returns the element BotProt renders its steps into. It must be in the document.
  • final runs once the visitor is verified. BotProt is done with the element, and leaves cleaning it up to you.
  • fail runs when BotProt cannot finish. Its message is safe to show to visitors as-is.

The identifier is the shop's GUID. The Shop API refuses a token for any other identifier. It must be a non-empty string; anything else fails right away, with the code 'config'. So does a returnUrl that is not a valid URL (see Redirects).

All options​

All options are optional. Rolling your own usually starts with show.

OptionWhenDefault
show()Once, at the first stepA plain element at the bottom of the page, removed when the run ends
final(token)Once, when the visitor is verifiedNothing
fail(message, code, error)Once, when BotProt cannot finishNothing
redirect(url)When a step sends the visitor elsewherewindow.location.assign(url)
returnUrlAt the startThe current page
retrieveToken(key), storeToken(key, value, expiresAt)During the run, to keep it across a refresh or a redirectlocalStorage

createBotProt also resolves to the token, and rejects with the same error fail gets. When you await it, final and fail are only needed for what happens to the element.

The playground shows the documentation of each option, as it is in botprot.d.ts, and lets you try them.

How a run goes​

One call to createBotProt is one run:

  1. BotProt starts a session. When this visitor needs no check, the run is done right away: BotProt calls final without calling show.
  2. Otherwise it fetches the first step, calls show, and renders the step into your element, replacing what was there. Some steps finish by themselves, without the visitor doing anything; then final follows shortly after show.
  3. The visitor completes the step, and BotProt fetches the next one, until it has a final token.
  4. At the end, BotProt calls final and resolves, or calls fail and rejects. Note: A step can also send the visitor elsewhere.
  5. The final token is what the run is for. Send it in the x-botprot-verification header on every reservation and order request to the Shop API, see Using the final token.

Only one run is active per page. Calling createBotProt again cancels the previous run, which then rejects with an AbortError.

BotProt calls your callbacks but never depends on them. An error thrown in final or fail is logged in the console, and the run ends as it would have.

The element​

BotProt calls show() once, when it has the first step to render. Your element can wait until then, as in the dialog example below.

  • It must return an HTMLElement that is in the document. A step's scripts look up their elements in the document. Anything else, or a show() that throws, fails.
  • Each step replaces all children of the element. Placeholder content, such as "Loading…", disappears at the first step.
  • BotProt never removes your element. Each step replaces its content, and after the run BotProt leaves it as is. Tidy it up in final and fail.

Some steps finish by themselves, without the visitor doing anything. A shop without steps the visitor solves can still have one set up, such as a safety net that can send visitors to a waiting room when traffic peaks, see Steps without visitor input. To keep such a step from flashing by, keep the element hidden at first, and reveal it only when the step takes longer:

const container = document.getElementById('botprot');
// The 2.5x median duration of a transient final.
const NOMINAL_DELAY_MS = 800;
container.style.visibility = 'hidden';
let reveal;

const token = await OT.createBotProt(identifier, {
show: () => {
// Hidden, but still laid out, so the step renders into it as usual.
reveal = setTimeout(() => {
container.style.visibility = '';
}, NOMINAL_DELAY_MS);

return container;
},
final: () => {
clearTimeout(reveal);
container.remove();
},
fail: (message) => {
clearTimeout(reveal);
container.style.visibility = '';
container.textContent = message;
},
});

Hide it with visibility or opacity, not display: none: an element that is not displayed is not rendered at all, so a step's scripts may not work, for example because the step's size is 0, or its iframe does not load. The 800 ms is an example; pick a delay a little longer than such a step usually takes.

Success​

BotProt calls final(token) once, right before createBotProt resolves to the same token. Tidy up the element there, for example by removing it. Then continue with the token by sending it in the x-botprot-verification header of a reservation or order.

Failures​

fail(message, code, error) runs once, right before createBotProt rejects with the same error:

  • message is written for visitors and safe to show as-is.
  • code tells failures apart, if you want to handle some differently.
  • error is for developers: error.message says what went wrong, for logs and error reports.
CodeMeansMessageRetry
configThis page is set up incorrectly, such as no identifier, an invalid returnUrl, or a show that returns nothingSomething went wrong during verification. Please try again.After fixing the page
networkBotProt could not be reached, or took longer than 15 secondsWe could not reach the verification service. Please check your connection and try again.Yes
statusBotProt responded with an error statusSomething went wrong during verification. Please try again.Yes
responseBotProt responded with something unusableSomething went wrong during verification. Please try again.Yes
rejectedBotProt concluded the visitor is unwantedWe could not verify that you are not a bot.No
limitThe visitor used up their attemptsToo many attempts. Please try again later.Later
unexpectedAnything elseSomething went wrong during verification. Please try again.Yes

These codes cover BotProt itself. Once you have a token, the Shop API can still refuse it with a 403 or 429, for example when it has expired. See When the token is refused.

To retry, call createBotProt again. Each call starts a fresh run:

const container = document.getElementById('botprot');

function start() {
OT.createBotProt(identifier, {
show: () => container,
// A retry can need no check at all, and then never calls show: clear the failure here.
final: () => container.replaceChildren(),
fail: (message, code) => {
container.replaceChildren(message);

// Retrying does not help when BotProt concluded the visitor is a bot.
if (code !== 'rejected') {
const retry = document.createElement('button');
retry.type = 'button';
retry.textContent = 'Try again';
retry.addEventListener('click', start);
container.append(retry);
}
},
}).then((token) => {
// Verified: continue with the token.
}, () => {
// fail already told the visitor, and the error is in the console.
});
}

start();

Redirects​

A step can send the visitor to another site, such as a waiting room. BotProt then calls redirect(url), which defaults to window.location.assign(url). Pass your own to save state first, or to leave the page another way. A redirect that throws fails with 'config'.

After a redirect, createBotProt neither resolves nor rejects: it waits while the page goes away.

When the visitor is done there, BotProt sends them back to returnUrl. By default, that is the page the run started on (window.location.href). A relative URL resolves against the current page. A value that is not a valid URL fails right away with 'config'.

OT.createBotProt(identifier, {
show: () => container,
// Save what the visitor would lose, then leave the page.
redirect: (url) => {
saveBasket();
window.location.assign(url);
},
// Come back to the checkout, not to the page BotProt started on.
returnUrl: '/checkout',
});

BotProt adds a botprot_next parameter to the return URL. On that page, call createBotProt again with the same identifier and options, and the run automatically continues where it left off.

Refresh and persistence​

BotProt stores how far the run got, per identifier, until its token expires. When the visitor refreshes the page or comes back from a redirect, calling createBotProt again with the same identifier continues from there, instead of starting over.

  • By default, BotProt uses localStorage, under BotProt:Token:Last:{identifier} and BotProt:Token:Queries:{identifier}.
  • To store it elsewhere, such as in a cookie, pass both retrieveToken(key) and storeToken(key, value, expiresAt). One without the other is not used. An empty value means forget the key, and retrieveToken returns null when nothing is stored. After the time in expiresAt has passed, it will also return null
  • A failure forgets the stored run, so trying again starts over. The exception is network: then trying again continues where the visitor was.
  • A final token stays stored until it expires, and a new run for the same identifier resolves to it right away. BotProt only forgets it when it starts again after it has expired. On a shared device, such as a point of sale, or after a successful order, clear it yourself.

From the reference skin​

The reference skin is a good start for a skin of your own. This is the same idea in plain JavaScript, ready to copy and change. The example below improves on the reference skin in two ways:

  • The dialog opens in show(), so it never appears when no check is needed.
  • A failure shows the message with a "Try again" button.
// A dialog over the page, like the reference skin, that can retry.
function createDialogSkin() {
let dialog;

function open() {
if (!dialog) {
dialog = document.createElement('dialog');
// Esc does not close it: the visitor has to finish the check.
dialog.addEventListener('cancel', (event) => event.preventDefault());
document.body.append(dialog);
dialog.showModal();
}

return dialog;
}

function close() {
dialog?.close();
dialog?.remove();
}

return {
// Only called at the first step: no dialog when no check is needed.
show: open,
final: close,
fail: (message) => {
const retry = document.createElement('button');
retry.type = 'button';
retry.textContent = 'Try again';
retry.addEventListener('click', () => window.location.reload());
// BotProt can fail before the first step, when there is no dialog yet.
open().replaceChildren(message, retry);
},
};
}

const token = await OT.createBotProt(identifier, createDialogSkin());

Debugging​

While you build, set OpenTicket.debug = true in the console. BotProt then logs each step of the run. Failures are always logged with console.error, prefixed with [@openticket/botprot-lobby:…] and the part that failed.