Skip to content
OnCharge.io
View as Markdown
Developer docs

Shopper gate

Before a shopper sees your store, the shopper gate asks them to:

  1. enter their email address;
  2. type the one-time code OnCharge emails to it;
  3. scroll your terms to the end (the Continue button stays disabled until they do);
  4. draw their signature.

OnCharge keeps the evidence and gives the shopper's browser a signed completion token, so they are not asked again on every page. They are asked again when the token expires (after 30 days by default) or, if you choose, when you publish new terms.

The gate is required for stores in the research-use-only (RUO) program and optional for every other store. RUO stores must keep their whole catalog private: a visitor who has not passed the gate must not receive product names, prices or images from any page or endpoint. The compliance review checks for the gate (see Markers).

Choose an install#

Your storeInstallEnough for RUO?
WooCommerceThe WordPress plugin: gates the whole store on your server.Yes
Custom storefront with a server (Next.js, Hydrogen, Remix, Express, Laravel, Django, …)A server check on every request, with the snippet or iframe on the gate page.Yes
Shopify Online Store theme, Webflow, Framer, Wix, other site buildersThe snippet in overlay mode.No: see Shopify
Your own gate UIThe gate API from your front end, then the server check.Yes, with the server check

An overlay is a browser-side control: the page has already been sent when the overlay covers it, so anyone who turns JavaScript off, or reads the page with a script, sees the catalog. That is fine for an optional gate. For RUO stores, the decision has to happen on the server.

Before you start#

In the OnCharge dashboard, open Integrations → Shopper gate. You need:

  • Your store ID (a UUID), shown on that page.
  • Your store's websites. The hosted gate only runs on them, and only they receive the completion token. They are your store's domain, the domains under Security → Domains, the website on your application, and hosts you connected for the compliance feed. Each must be https without a port; the www. variant of each is included.
  • The gate turned on. RUO stores: always on. Other stores: select Turn on.
  • Your terms. Write them in the terms editor on that page, or publish them from a page on your site (the plugin's A page on this site setting, or PUT …/terms with the gate key). Until you do, shoppers see OnCharge's default terms. Each change is a new version; the token records which version the shopper signed.
  • A gate key (gk_…, optional). Create it on the same page; it is shown once. The plugin and your server use it to publish terms from your site and to report how the gate is installed. It cannot read shopper records.
  • How long a completion lasts: 1 to 90 days (default 30), and whether new terms ask shoppers again (always on for RUO stores).

What OnCharge keeps#

For each shopper who completes the gate:

EvidenceDetail
EmailThe address, and when it was verified with the code.
TermsVersion, SHA-256 of the exact text, the text itself, when it was shown and when it was scrolled to the end.
SignatureSHA-256 and size of the PNG, and when it was signed. The image stays in private storage; you can view it through a link that lasts five minutes.
Request detailsIP address and user agent of every step, and the time of each step.

Nothing else about the shopper is collected. The completion token holds no email or other personal data. Unfinished sessions are deleted after a week, and one-time codes after two days. You can see completions under Integrations → Shopper gate and read them with the merchant API.

WooCommerce plugin#

The gate is part of OnCharge Secure Checkout (1.8.0 and later) and OnCharge Compliance Scanner (1.2.0 and later). Install either; if both are installed, only one copy of the gate runs. Both update from the WordPress admin like any other plugin.

  1. In WordPress, open Settings → OnCharge shopper gate.
  2. Store ID: leave it blank to use the one Secure Checkout is set up with, or paste it from the dashboard.
  3. Gate key (optional): paste it to publish your terms from a page on your site and to send the plugin's daily report to the dashboard.
  4. Terms: choose OnCharge dashboard (the terms you wrote there) or A page on this site (the plugin publishes the page's text as your terms whenever it changes; needs the gate key).
  5. Public pages: legal and contact pages are public already (see below). Tick any other page that must stay public.
  6. Select Save, then Check now. The status table shows whether the gate is on, the terms in use, the result of the check, and whether page caches were found.

The gate turns itself on when the store's settings in OnCharge say so: for RUO stores, as soon as the plugin knows the store ID.

Why the gate runs on the server#

The plugin decides in PHP, before WordPress renders anything, so a visitor who has not passed never receives store content: not with JavaScript turned off, not through a feed or the REST API, not from a scraper. The gate page is served in place of the requested page (same address, HTTP 200), so the shopper lands where they meant to go once they are through.

What is gated#

  • Every storefront page: home, shop, product, category and tag pages, search, blog posts, cart, checkout and account pages.
  • WooCommerce actions: add to cart, cart updates, coupons, checkout, checkout links and wc-ajax, and every admin-ajax.php and admin-post.php action not listed under What stays public. AJAX answers 403 with { "error": "gate_required" }.
  • Every REST route outside the namespaces and routes listed under What stays public, the WooCommerce Store API (wc/store) always. They answer 401 (oncharge_gate_required).
  • RSS and Atom feeds (never answered 304 Not Modified to a visitor who has not passed), sitemaps (WordPress's own and those of SEO plugins), and comments on anything but a public page. Any address or query field with "sitemap" in its name counts as a sitemap, however it is encoded, so a page at such an address is gated even if you ticked it as public.

Live search, quick view, wishlists, chat widgets and similar features work for shoppers once they have passed.

What stays public#

  • Pages whose whole slug is a legal or contact page, judged by the page WordPress actually shows: terms (and terms-of-service, terms-and-conditions, tos, …), privacy / privacy-policy, refund / returns / refund-policy, shipping / delivery / shipping-policy, contact / contact-us, about / about-us. A slug like about-our-products is gated.
  • Pages you tick under Public pages.
  • The WordPress admin and login, WooCommerce API callbacks (?wc-api=…, used by payment notifications), and the Compliance Scanner's signed feed.
  • The REST index (GET /wp-json/), the WooCommerce app's sign-in by QR code (/wp-json/wc-admin/mobile-app/qr-login-…) and one payment extension's webhook, which its provider calls without a gate cookie.
  • The REST namespaces wc/v1 to wc/v3 (they require WooCommerce API keys) and contact-form-7/v1, and the AJAX actions heartbeat, wpforms_submit, fluentform_submit, nf_ajax_submit and elementor_pro_forms_send_form, so contact forms work on public pages.

To open another REST namespace, a single REST route or an AJAX action to visitors who have not passed (a form plugin on your contact page, or another service's webhook, say), add it with a filter. A route is its method and path, as in POST /my-forms/v1/submit; GET also opens HEAD. The Store API and WooCommerce's and OnCharge's cart and payment actions can never be opened. The settings screen lists the REST namespaces other plugins added that the gate keeps closed.

functions.php
add_filter( 'oncharge_shopper_gate_public_rest_namespaces', fn( $namespaces ) => array_merge( $namespaces, array( 'my-forms/v1' ) ) );
add_filter( 'oncharge_shopper_gate_public_rest_routes', fn( $routes ) => array_merge( $routes, array( 'POST /my-service/v1/webhook' ) ) );
add_filter( 'oncharge_shopper_gate_public_actions', fn( $actions ) => array_merge( $actions, array( 'my_form_submit' ) ) );

Files in wp-content/uploads (product images) are sent by your web server without running WordPress, so the plugin cannot gate them. Gated pages do not link to them; if your images must not be reachable by address, protect that folder in your web server or CDN.

Who passes#

  • Shoppers whose oncharge_gate cookie holds a valid completion token for your store (and, when new terms ask again, for the current terms version).
  • Signed-in staff: users who can edit posts, manage WooCommerce or manage the site.
  • The reviewer account chosen in the Compliance Scanner, so payment and card-network reviewers can see the catalog.
  • OnCharge's compliance bot, on GET and HEAD requests with a valid OnCharge-Scan signature for one of your store's websites (with or without www.), as the plugin reads them from OnCharge; until it has read them, your WordPress site's own host. To add a host name that is not one of your store's websites, use the filter oncharge_shopper_gate_own_hosts. A user agent alone never passes.

Caches#

Every response the gate governs (the gate page, and real pages for shoppers who passed) is sent with Cache-Control: private, no-store, CDN and proxy equivalents, Vary: Cookie and OnCharge-Gate: v1, and is marked not to be cached for page-cache plugins (DONOTCACHEPAGE, LiteSpeed). When the gate turns on, the plugin clears the page caches it can, and the settings screen shows which it cleared and which to clear by hand. While one is not cleared, the plugin tries again with each check (daily, and when you select Check now). Check now fetches your home page and a product page as a new visitor would, twice each, and reports a cache that still answers with a stored copy. If your host or CDN caches HTML and ignores these headers, set it not to cache HTML pages for this site.

Snippet#

Add this to every page, in the <head>:

Snippet
<script src="https://app.oncharge.io/gate/v1/gate.js" data-store="<your store id>" async></script>

It works in one of two modes:

  • Inline: when the page has an element with data-oncharge-gate="v1", the snippet shows the gate inside it. Use this on a gate page your server serves (see the server check).
  • Overlay: otherwise, the snippet first reads your store's gate settings. If the store does not ask shoppers to verify, it leaves the page alone. If the browser holds a current completion token, the page shows. Anyone else gets a full-screen gate.

When the shopper finishes, the snippet stores the token in the oncharge_gate cookie (first-party, SameSite=Lax, Secure on https, lasting until the token expires) and reloads the page.

AttributeMeaning
data-storeRequired: your store ID.
data-reload"false" to stay on the page after completion and handle the oncharge-gate:complete event yourself.
data-cookie-domainCookie domain, to share the completion between subdomains (for example .example.com).
Event (on document)When
oncharge-gate:completeThe shopper finished; event.detail.token is the token.
oncharge-gate:passedOverlay mode: the browser already had a current token.
oncharge-gate:inactiveOverlay mode: the store does not ask shoppers to verify.

window.OnChargeGate has store, active (true, false, or null until known), completed, token() (the token in this browser, or null) and reset() (forget the completion and show the gate again).

If your site sends a Content Security Policy, allow script-src https://app.oncharge.io, frame-src https://app.oncharge.io and connect-src https://app.oncharge.io.

Shopify#

On a Shopify Online Store theme, add the snippet to layout/theme.liquid inside <head>. That gives you an overlay, which is fine for an optional gate. It is not enough for an RUO store: the theme cannot run code on Shopify's servers, and Shopify's own endpoints (for example /products.json, collection feeds and the sitemap) stay readable. An RUO store on Shopify needs a headless storefront (Hydrogen, or Next.js with the Storefront API) with the server check in front of every request.

Server check#

On a custom storefront, check every request on the server before you render anything:

  1. Paths that stay public: your legal and contact pages, static assets (CSS, JavaScript, fonts), and machine endpoints with their own authentication (payment webhooks, the compliance feed). Everything else is governed, including API routes that return catalog data.
  2. If the gate is off for your store (active: false in its config), show the page.
  3. If the request carries OnCharge-Scan and it is a GET or HEAD with a valid signature for one of your own host names, show the page, without starting a session or setting a cookie.
  4. If the oncharge_gate cookie holds a valid token for your store, show the page. If your store asks again on new terms and the token's tv is lower than the current terms version, treat it as no token. Until you have a copy of the store's settings (OnCharge could not be reached since your server started), treat every token as no token: you cannot tell which terms the store asks for.
  5. Otherwise serve the gate page at the same URL with HTTP 200: your store's name, an element with data-oncharge-gate="v1", the snippet, and links to your public pages. No products, prices or images.
  6. Add these headers to every governed response (the gate page and real pages): Cache-Control: private, no-store, Vary: Cookie, OnCharge-Gate: v1, and OnCharge-Gate-Scan: <result> when the request carried OnCharge-Scan.

The module below does steps 2 to 6. It uses only Web Crypto, so it runs in Node.js 20 and later, Next.js middleware on the Node.js runtime, Deno, Bun and Cloudflare Workers, and it passes every test vector. It keeps OnCharge's public keys for an hour and the store's settings for a minute; if OnCharge cannot be reached and nothing is kept yet, the gate stays up, completion tokens included.

lib/oncharge-gate.mjs
// OnCharge shopper gate: check completion tokens and the compliance bot's OnCharge-Scan header on your server.
// Web Crypto only (Ed25519), so it runs in Node.js 20+, Next.js middleware on the Node.js runtime, Deno, Bun and
// Cloudflare Workers. Passes every case in https://oncharge.io/docs/files/shopper-gate/test-vectors.json.

const APP = 'https://app.oncharge.io';
export const GATE_COOKIE = 'oncharge_gate';
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
const encoder = new TextEncoder();

function base64url(value) {
  const binary = atob(value.replace(/-/g, '+').replace(/_/g, '/') + '==='.slice((value.length + 3) % 4));
  return Uint8Array.from(binary, (c) => c.charCodeAt(0));
}

function jsonPart(part) {
  if (!/^[A-Za-z0-9_-]+$/.test(part)) return null;
  try {
    const value = JSON.parse(new TextDecoder().decode(base64url(part)));
    return value && typeof value === 'object' && !Array.isArray(value) ? value : null;
  } catch {
    return null;
  }
}

const findKey = (keys, kid) => (Array.isArray(keys) ? keys.find((k) => k && typeof k === 'object' && k.kid === kid) : undefined);

async function importKey(jwk) {
  if (!jwk || jwk.kty !== 'OKP' || jwk.crv !== 'Ed25519' || typeof jwk.x !== 'string' || !/^[A-Za-z0-9_-]{43}$/.test(jwk.x)) return null;
  try {
    return await crypto.subtle.importKey('jwk', { kty: 'OKP', crv: 'Ed25519', x: jwk.x }, { name: 'Ed25519' }, false, ['verify']);
  } catch {
    return null;
  }
}

const verifyEd25519 = (key, signature, message) => crypto.subtle.verify({ name: 'Ed25519' }, key, signature, encoder.encode(message));

/**
 * Check a completion token (the oncharge_gate cookie). `keys` is the `keys` array of
 * https://app.oncharge.io/.well-known/oncharge-gate-keys.json. Answers { valid: true, claims } or
 * { valid: false, reason }, reason one of malformed, unknown_key, bad_signature, wrong_issuer, wrong_store,
 * not_yet_valid, expired.
 */
export async function verifyGateToken(token, { store, keys, now = Math.floor(Date.now() / 1000), issuer = APP } = {}) {
  const fail = (reason) => ({ valid: false, reason });
  if (typeof token !== 'string' || token.length > 2048) return fail('malformed');
  const parts = token.split('.');
  if (parts.length !== 3) return fail('malformed');
  const [headerPart, payloadPart, signaturePart] = parts;
  const header = jsonPart(headerPart);
  const c = jsonPart(payloadPart);
  if (!header || !c || header.alg !== 'EdDSA' || typeof header.kid !== 'string') return fail('malformed');
  if (!/^[A-Za-z0-9_-]{86}$/.test(signaturePart)) return fail('malformed');
  const key = await importKey(findKey(keys, header.kid));
  if (!key) return fail('unknown_key');
  if (!(await verifyEd25519(key, base64url(signaturePart), `${headerPart}.${payloadPart}`))) return fail('bad_signature');
  const wellFormed =
    typeof c.iss === 'string' && UUID.test(c.aud) && UUID.test(c.sub) && Number.isInteger(c.iat) && Number.isInteger(c.exp) &&
    Number.isInteger(c.tv) && c.tv >= 1 && c.gate === 'v1' && typeof c.th === 'string' && /^[0-9a-f]{64}$/.test(c.th);
  if (!wellFormed) return fail('malformed');
  if (c.iss !== issuer) return fail('wrong_issuer');
  if (store && c.aud.toLowerCase() !== store.toLowerCase()) return fail('wrong_store');
  if (c.iat > now + 60) return fail('not_yet_valid');
  if (c.exp <= now) return fail('expired');
  return { valid: true, claims: { iss: c.iss, aud: c.aud, sub: c.sub, iat: c.iat, exp: c.exp, gate: c.gate, tv: c.tv, th: c.th } };
}

/** `OnCharge-Scan: v=1; t=<unix seconds>; kid=<key id>; sig=<base64url Ed25519 signature>`, or null. */
export function parseScanHeader(value) {
  if (typeof value !== 'string' || value.length > 1024) return null;
  const params = new Map();
  for (const piece of value.split(';')) {
    const trimmed = piece.trim();
    if (!trimmed) continue;
    const eq = trimmed.indexOf('=');
    if (eq <= 0) return null;
    const name = trimmed.slice(0, eq).trim().toLowerCase();
    if (params.has(name)) return null;
    params.set(name, trimmed.slice(eq + 1).trim());
  }
  if (params.get('v') !== '1') return null;
  const t = params.get('t') ?? '';
  const kid = params.get('kid') ?? '';
  const sig = params.get('sig') ?? '';
  if (!/^\d{1,12}$/.test(t) || !/^[A-Za-z0-9._:-]{1,64}$/.test(kid) || !/^[A-Za-z0-9_-]{86}$/.test(sig)) return null;
  return { t: Number(t), kid, sig: base64url(sig) };
}

/** The Host header as signed: lower case, no trailing dot, the port only when it is not the scheme's default. */
export function scanHost(host, scheme = 'https') {
  const value = String(host).trim().toLowerCase();
  const match = value.match(/^(\[[^\]]+\]|[^:]*)(?::(\d+))?$/);
  if (!match) return value;
  const name = (match[1] ?? '').replace(/\.$/, '');
  let port = match[2] ?? '';
  if ((scheme === 'https' && port === '443') || (scheme === 'http' && port === '80')) port = '';
  return port ? `${name}:${port}` : name;
}

/** The request target as sent: the raw path (`/` when empty) and `?query` only when the query is not empty. */
export function scanPath(target) {
  let value = String(target ?? '');
  const hash = value.indexOf('#');
  if (hash >= 0) value = value.slice(0, hash);
  if (/^[a-z][a-z0-9+.-]*:\/\//i.test(value)) {
    const afterScheme = value.indexOf('//') + 2;
    const slash = value.indexOf('/', afterScheme);
    const query = value.indexOf('?', afterScheme);
    const start = slash >= 0 && (query < 0 || slash < query) ? slash : query;
    value = start >= 0 ? value.slice(start) : '';
  }
  if (value.startsWith('?')) value = `/${value}`;
  if (value.endsWith('?')) value = value.slice(0, -1);
  return value === '' ? '/' : value;
}

/**
 * Check the compliance bot's header. `keys` is the `keys` array of
 * https://app.oncharge.io/.well-known/oncharge-scan-keys.json, or null when it could not be loaded; `refresh`
 * (optional) fetches it again for an unknown key id. Answers pass, stale, bad-signature, unknown-key,
 * keys-unavailable or malformed. Only `pass` lets the request through.
 */
export async function verifyScanHeader({ header, host, path, scheme = 'https', keys, refresh, now = Math.floor(Date.now() / 1000) }) {
  const parsed = parseScanHeader(header);
  if (!parsed || typeof host !== 'string' || !host.trim() || typeof path !== 'string') return 'malformed';
  if (Math.abs(now - parsed.t) > 300) return 'stale';
  let list = keys;
  let jwk = findKey(list, parsed.kid);
  if (!jwk && refresh) {
    const fresh = await refresh();
    if (fresh) {
      list = fresh;
      jwk = findKey(fresh, parsed.kid);
    }
  }
  if (!list) return 'keys-unavailable';
  const key = await importKey(jwk);
  if (!key) return 'unknown-key';
  const message = `v1\n${parsed.t}\n${scanHost(host, scheme)}\n${scanPath(path)}`;
  return (await verifyEd25519(key, parsed.sig, message)) ? 'pass' : 'bad-signature';
}

/** A JWKS URL, kept for an hour and fetched again for an unknown key id at most every 5 minutes. */
export function jwks(url) {
  let cached = null;
  let lastRefresh = 0;
  const load = async () => {
    try {
      const response = await fetch(url, { signal: AbortSignal.timeout(3000) });
      const body = response.ok ? await response.json() : null;
      if (!body || !Array.isArray(body.keys)) return null;
      cached = { keys: body.keys, at: Date.now() };
      return body.keys;
    } catch {
      return null;
    }
  };
  return {
    async get() {
      if (cached && Date.now() - cached.at < 3_600_000) return cached.keys;
      return (await load()) ?? cached?.keys ?? null;
    },
    async refresh() {
      if (Date.now() - lastRefresh < 300_000) return null;
      lastRefresh = Date.now();
      return load();
    },
  };
}

/** Headers for every response the gate governs, so no cache keeps a page for the wrong visitor. */
export const GATE_HEADERS = { 'Cache-Control': 'private, no-store', 'OnCharge-Gate': 'v1', Vary: 'Cookie' };

/**
 * The gate for one store. `hosts` lists the host names your storefront answers on, as in the Host header (for example
 * ['shop.example']); each also counts with `www.` or without it. `check()` takes what your framework gives you about a request and answers
 * { pass, headers }: show the page when `pass` is true, otherwise serve gatePage() at the same URL with HTTP 200.
 * Add `headers` to the response either way.
 */
export function createGate({ store, hosts, app = APP }) {
  if (!UUID.test(store ?? '')) throw new Error('createGate: store must be your OnCharge store ID.');
  if (!Array.isArray(hosts) || hosts.length === 0 || !hosts.every((host) => typeof host === 'string' && host.trim() !== '')) {
    throw new Error('createGate: hosts must list the host names your storefront answers on.');
  }
  // The bot signs every request it makes, so a header from its visit to another site is valid for that site's host.
  // Only your own host names count (with or without `www.`, as the bot may ask either before you redirect it), in case
  // your server answers for any Host.
  const bare = (name) => name.replace(/^www\./, '');
  const ownHost = (host, scheme) => hosts.some((own) => bare(scanHost(own, scheme)) === bare(scanHost(host, scheme)));
  const tokenKeys = jwks(`${app}/.well-known/oncharge-gate-keys.json`);
  const scanKeys = jwks(`${app}/.well-known/oncharge-scan-keys.json`);
  let config = null;

  // Whether the gate is on and the current terms version, kept for a minute. Unknown (OnCharge unreachable and no
  // earlier copy) counts as on, and then no completion token counts: the store may ask for newer terms.
  async function loadConfig() {
    if (config && Date.now() - config.at < 60_000) return config.value;
    try {
      const response = await fetch(`${app}/api/gate/v1/stores/${store}/config`, { signal: AbortSignal.timeout(3000) });
      const value = response.ok ? await response.json() : null;
      if (value && typeof value.active === 'boolean') {
        config = { value, at: Date.now() };
        return value;
      }
    } catch {
      // Keep the last copy.
    }
    return config?.value ?? null;
  }

  return {
    /** method, host (the Host header), path (path and query as sent), scheme, cookie (oncharge_gate), scanHeader (OnCharge-Scan). */
    async check({ method = 'GET', host, path, scheme = 'https', cookie, scanHeader }) {
      const settings = await loadConfig();
      if (settings && !settings.active) return { pass: true, headers: {} };
      const headers = { ...GATE_HEADERS };

      if (scanHeader != null) {
        let result = await verifyScanHeader({ header: scanHeader, host, path, scheme, keys: await scanKeys.get(), refresh: scanKeys.refresh });
        if (result === 'pass' && !ownHost(host, scheme)) result = 'bad-signature';
        headers['OnCharge-Gate-Scan'] = result;
        if (result === 'pass' && (method === 'GET' || method === 'HEAD')) return { pass: true, headers };
      }

      if (settings && typeof cookie === 'string' && cookie !== '') {
        let check = await verifyGateToken(cookie, { store, keys: await tokenKeys.get(), issuer: app });
        if (!check.valid && check.reason === 'unknown_key') {
          const fresh = await tokenKeys.refresh();
          if (fresh) check = await verifyGateToken(cookie, { store, keys: fresh, issuer: app });
        }
        const version = settings.terms?.version;
        const askAgain = settings.reask_on_terms_change && version && check.valid && check.claims.tv < version;
        if (check.valid && !askAgain) return { pass: true, headers };
      }
      return { pass: false, headers };
    },
  };
}

const escapeHtml = (value) =>
  String(value).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);

/**
 * The gate page: your store's name, the hosted gate and links to your public legal pages. No products, prices or
 * images. `links` is a list of [label, url] pairs.
 */
export function gatePage({ store, storeName, links = [], app = APP }) {
  const nav = links.map(([label, url]) => `<a href="${escapeHtml(url)}">${escapeHtml(label)}</a>`).join(' · ');
  return `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="robots" content="noindex, nofollow">
<meta name="oncharge-gate" content="v1">
<title>${escapeHtml(storeName)}</title>
<style>body{margin:0;background:#f6f7f9;color:#111827;font:16px/1.5 system-ui,sans-serif}main{max-width:560px;margin:0 auto;padding:32px 16px}h1{font-size:22px;text-align:center;margin:0 0 6px}p,nav{text-align:center;color:#4b5563}</style>
</head>
<body>
<main>
<h1>${escapeHtml(storeName)}</h1>
<p>To see this store, verify your email address and accept its terms.</p>
<div data-oncharge-gate="v1"><noscript><p>Turn on JavaScript to continue.</p></noscript></div>
<nav>${nav}</nav>
</main>
<script src="${escapeHtml(app)}/gate/v1/gate.js" data-store="${escapeHtml(store)}" async></script>
</body>
</html>`;
}

Next.js#

middleware.ts at the root of your app (or in src/), with the module above saved as lib/oncharge-gate.mjs. Running middleware on the Node.js runtime needs Next.js 15.5 or later.

middleware.ts
import { NextResponse, type NextRequest } from 'next/server';
import { createGate, gatePage, GATE_COOKIE } from './lib/oncharge-gate.mjs';

const STORE = process.env.ONCHARGE_STORE_ID!;
// The host names this storefront answers on; each also counts with or without `www.`.
const gate = createGate({ store: STORE, hosts: ['shop.example'] });

// Exact paths anyone may open, and prefixes for machine endpoints with their own authentication.
const PUBLIC_PATHS = new Set(['/terms', '/privacy', '/refund-policy', '/shipping-policy', '/contact', '/about', '/robots.txt', '/favicon.ico']);
const PUBLIC_PREFIXES = ['/api/webhooks/', '/.well-known/'];

export const config = {
  runtime: 'nodejs',
  matcher: ['/((?!_next/static/|_next/image).*)'],
};

export async function middleware(request: NextRequest) {
  const url = new URL(request.url);
  if (PUBLIC_PATHS.has(url.pathname) || PUBLIC_PREFIXES.some((prefix) => url.pathname.startsWith(prefix))) {
    return NextResponse.next();
  }
  const result = await gate.check({
    method: request.method,
    host: request.headers.get('host') ?? url.host,
    path: url.pathname + url.search,
    scheme: url.protocol === 'http:' ? 'http' : 'https',
    cookie: request.cookies.get(GATE_COOKIE)?.value,
    scanHeader: request.headers.get('oncharge-scan'),
  });
  const response = result.pass
    ? NextResponse.next()
    : new NextResponse(
        gatePage({ store: STORE, storeName: 'Your store', links: [['Terms', '/terms'], ['Privacy', '/privacy'], ['Contact', '/contact']] }),
        { status: 200, headers: { 'Content-Type': 'text/html; charset=utf-8' } },
      );
  for (const [name, value] of Object.entries(result.headers)) response.headers.set(name, value);
  return response;
}

Match public pages by their exact path, never by prefix, so a page like /about-our-products stays gated. hosts lists the host names the storefront answers on, each with or without www.: a signed bot request passes only for them. ONCHARGE_STORE_ID is your store ID; it is not a secret, but keep it out of NEXT_PUBLIC_ variables like your other OnCharge settings. API routes are governed too, so a client-side fetch to your catalog API from the gate page gets the gate instead of data.

Hydrogen and other servers#

  • Hydrogen: run gate.check() at the top of the request handler in server.ts, before handleRequest, and return new Response(gatePage(...), { status: 200, headers }) for visitors who have not passed.
  • Express, Fastify, Koa: the same as a middleware registered before your routes; pass req.headers.host, req.originalUrl and the cookie.
  • Other languages: implement the same checks, and let a bot header through only for your own host names. A token is a compact JWS (header.payload.signature, base64url): alg must be EdDSA; verify the Ed25519 signature over header.payload with the key whose kid matches in the JWKS; then check iss is https://app.oncharge.io, aud is your store ID (case-insensitive), gate is "v1", iat is at most 60 seconds in the future and exp is in the future. Run the test vectors to be sure. For PHP, the WordPress plugin's OnCharge_Shopper_Gate_Verifier class does both checks with sodium.
  • Without Ed25519: call POST /api/gate/v1/tokens/verify and POST /api/gate/v1/scan/verify (with your store) instead, and keep the answer for each token for a minute.

Markers#

The compliance review looks for these to confirm the gate is installed:

InstallMarker
Every install<meta name="oncharge-gate" content="v1"> in the gate page's <head> (the snippet adds it when missing).
Every installdata-oncharge-gate="v1" on the element the gate is shown in.
SnippetA script from https://app.oncharge.io/gate/v1/.
IframeAn iframe from https://app.oncharge.io/gate/v1/frame/<store id>.
Server check, pluginThe response header OnCharge-Gate: v1 on every governed response.

The gate page is served in place (same URL, no redirect) with HTTP 200 and Cache-Control: private, no-store, and shows no store content: only your store's name and links to your public legal and contact pages.

Bot pass-through#

OnCharge's compliance bot reads your catalog as a shopper who passed the gate would see it. It signs each GET or HEAD request:

Text
OnCharge-Scan: v=1; t=<unix seconds>; kid=<key id>; sig=<base64url Ed25519 signature>
  • Parameters are ;-separated name=value pairs in any order, with optional spaces; unknown parameters are ignored; v must be 1.
  • The signed message (UTF-8) is "v1\n" + t + "\n" + host + "\n" + pathAndQuery:
    • host is the Host header as received, in lower case, without a trailing dot, with the port only when it is not the scheme's default;
    • pathAndQuery is the request target exactly as received: the raw path (percent-encoding as sent, / when empty), plus ? and the query when the query is not empty.
  • sig is base64url without padding of the 64-byte signature, made with a key from https://app.oncharge.io/.well-known/oncharge-scan-keys.json.
  • Accept it when |now − t| ≤ 300 seconds.
  • Accept it only when host is one of your store's own host names (with or without www.), and answer bad-signature otherwise. The bot signs every request it makes, so a header from its visit to another site is valid for that site's host, and a server that answers for any Host must not let it through.

A request with a valid signature gets the real page, without a gate session or cookie, with Cache-Control: private, no-store and OnCharge-Gate: v1. Anything else (no header, a stale or bad signature, an unknown key, keys that cannot be loaded) gets the gate page. Never let a request through because of its user agent.

On every response to a request that carried OnCharge-Scan, add OnCharge-Gate-Scan: <result> (pass, stale, bad-signature, unknown-key, keys-unavailable or malformed), so the review can tell a clock or key problem from a missing gate.

Keys#

KeysURLCache
Completion tokenshttps://app.oncharge.io/.well-known/oncharge-gate-keys.jsonUp to an hour
Compliance bothttps://app.oncharge.io/.well-known/oncharge-scan-keys.jsonUp to an hour; fetch again for an unknown kid, at most every 5 minutes

Both are JWKS (RFC 8037): use only entries with kty OKP and crv Ed25519, matched on kid.

JSON
{ "keys": [{ "kty": "OKP", "crv": "Ed25519", "kid": "<key id>", "x": "<base64url public key>", "use": "sig", "alg": "EdDSA" }] }

Completion token#

A compact JWS signed by OnCharge with Ed25519 (alg EdDSA). Shoppers cannot make or change one: it needs OnCharge's private key.

ClaimValue
isshttps://app.oncharge.io
audYour store ID
subThe gate session ID (look it up with the merchant API)
iat, expIssued and expiry times, in Unix seconds
gate"v1"
tvThe terms version the shopper signed
thSHA-256 (hex) of the terms text the shopper signed

Iframe#

To show the hosted gate yourself, frame:

Text
https://app.oncharge.io/gate/v1/frame/<store id>?origin=<your page's origin>&n=<nonce>
  • origin must be one of your store's websites (for example https://shop.example.com); the frame answers 403 for any other.
  • n is a fresh random value of 16 to 64 characters (A-Z a-z 0-9 _ -) for each frame.
  • The frame's Content-Security-Policy allows only your store's websites to frame it.

The frame and your page exchange messages of the form { source: "oncharge-gate", v: 1, type, … }:

From → totypeFieldsMeaning
Frame → pagereadyThe frame is listening. Answer with hello.
Page → framehellononceThe n you put in the frame URL. The frame only sends the token after this.
Frame → pageresizeheightContent height in CSS pixels.
Frame → pagecompletetoken, expires_at, nonceThe shopper finished. Check that nonce is yours.

The frame posts only to the origin it was opened for. On your side, accept a message only when event.origin is https://app.oncharge.io and event.source is the frame's window.

Iframe
<div id="oncharge-gate" data-oncharge-gate="v1"></div>
<script>
  const APP = 'https://app.oncharge.io';
  const STORE = '<your store id>';
  const nonce = crypto.randomUUID().replaceAll('-', '');
  const frame = document.createElement('iframe');
  frame.src = `${APP}/gate/v1/frame/${STORE}?origin=${encodeURIComponent(location.origin)}&n=${nonce}`;
  frame.title = 'Verify to continue';
  frame.style.cssText = 'display:block;width:100%;max-width:520px;height:560px;margin:0 auto;border:0';
  document.getElementById('oncharge-gate').appendChild(frame);

  window.addEventListener('message', (event) => {
    if (event.origin !== APP || event.source !== frame.contentWindow) return;
    const data = event.data;
    if (!data || data.source !== 'oncharge-gate' || data.v !== 1) return;
    if (data.type === 'ready') frame.contentWindow.postMessage({ source: 'oncharge-gate', v: 1, type: 'hello', nonce }, APP);
    if (data.type === 'resize') frame.style.height = `${Math.min(2000, Math.max(300, Math.ceil(data.height)))}px`;
    if (data.type === 'complete' && data.nonce === nonce) {
      const maxAge = Math.max(60, Math.floor((Date.parse(data.expires_at) - Date.now()) / 1000));
      document.cookie = `oncharge_gate=${data.token}; Path=/; Max-Age=${maxAge}; SameSite=Lax; Secure`;
      location.reload();
    }
  });
</script>

Gate API#

Base URL: https://app.oncharge.io/api/gate/v1. Every answer is JSON and not cached, except the store config (one minute). Errors are { "error": "<code>", "message": "<text>" }.

RequestAuthAnswer
GET /stores/{store}/configNone{ gate, store, active, required, enabled, session_days, reask_on_terms_change, terms: { version, sha256, title }, hosts, issuer, keys_url, frame_url, script_url, cookie }. terms is null when the gate is off. hosts lists your store's websites as lower-case host names without www. (each also counts with www.).
POST /sessions { store }From the shopper's browser on one of your websites (CORS)201 { session: { id, step, secret, … }, store: { id, name, required }, terms: { version, sha256, title, body } }. The secret (gs_…) is shown once; a session lasts an hour.
POST /sessions/{id}/code { email }Authorization: Bearer <session secret>{ sent, email, expires_in_seconds }: a 6-digit code, valid 10 minutes, emailed to the shopper. email comes back masked.
POST /sessions/{id}/verify { code }Session secret{ verified, step: "terms" }
POST /sessions/{id}/terms { event, terms_sha256 }Session secret{ step }. Send event: "shown" when the terms appear and "reviewed" when the shopper has scrolled to the end, at least 1.5 seconds later, with the sha256 from the session.
POST /sessions/{id}/signature { image, terms_sha256 }Session secret{ step: "done", token, expires_at }. image is a PNG data URL of at most 300 KB and 1,000,000 pixels with a drawn signature. A session may send 10 images. Sending it again answers the same token.
GET /sessions/{id}Session secret{ session }, and token and expires_at once completed.
POST /tokens/verify { token, store }None{ valid, reason?, claims?, terms_current }. terms_current is false when the store asks again on new terms and the token is for an older version.
POST /scan/verify { header, host, path, scheme?, store? }None{ valid, result }, result as in Bot pass-through. Send host and path exactly as your server received them, and your store: with it, a header signed for a host that is not one of your store's websites answers bad-signature.
PUT /stores/{store}/terms { title, body, source_url? }Authorization: Bearer <gate key>{ version, sha256, created }. body is plain text, paragraphs separated by blank lines, at most 100,000 characters. The same title and body as the current version change nothing.
POST /stores/{store}/reportGate keyTell the dashboard how the gate is installed: { integration: "custom", mode: "server" | "snippet" | "iframe", version?, self_check?: { ok, detail } }. Answers the store's config.

A session's steps run in order: email → terms → signature → done. Steps cannot be skipped or repeated.

StatusCodes
400invalid_store, invalid_email, invalid_code, wrong_code, no_code, code_used_up, invalid_event, invalid_signature, invalid_request
401unauthorized (missing or wrong gate key)
403origin_required, origin_not_allowed (not one of your websites), store_unavailable (your store is suspended, or your account is suspended or closed; the gate stays on, so the store stays closed)
404not_found (no such store, or no session with that ID and secret)
409gate_off, wrong_step, terms_not_shown, too_fast, terms_changed
410session_closed (finished, or past its hour: start again)
429too_many_codes, locked, too_many_attempts, rate_limited, with retry_after_seconds
502email_failed
503unavailable, busy (code emails are queued up: try again after retry_after_seconds)

Limits#

To stop abuse of code emails and guessing:

LimitValue
Codes per session3 per 10 minutes
Codes per email addressFor one store, 5 an hour from one network and 10 an hour; 15 an hour and 40 a day across stores. Each network's first 2 codes an hour to an address are never refused by the address's other limits, so codes asked for elsewhere cannot use up a shopper's own. Above all of these, one inbox gets at most 100 codes a day from anywhere. These limits hold every shopper alike, so an answer never tells whether an address is one of your customers. An address counts as one however it is written: case, +tags, dots in Gmail addresses, dots, hyphens and underscores in Proton addresses, and googlemail.com, protonmail.com, pm.me, me.com, mac.com, ya.ru, narod.ru or other Yandex domains for gmail.com, proton.me, icloud.com or yandex.ru make no new address, and neither does anything@you.fastmail.com for you@fastmail.com.
Codes per email domain200 an hour from your stores to one domain, except big free mail providers (Gmail, Outlook, Yahoo and the like)
Codes per store30 an hour from one network. 3,000 an hour once OnCharge has reviewed your store, 100 an hour before that; your stores share these. Before review, while new stores across OnCharge are very busy, a merchant whose stores sent 20 or more codes in the hour may also have to wait. The hourly ceilings (not the 30 per network) don't hold a shopper who completed your gate before with the same address, so a flood of sign-ups doesn't lock out your customers, and codes sent to such shoppers don't count toward them. They do count toward the 30 per network and the 200 per domain.
Guesses5 per code, 10 per session (then the session is locked)
Signatures10 images per session
Per IP addressStart 20 and code emails 5 per 10 minutes (30 a day), code checks 20 per 10 minutes, other steps 60 per 10 minutes, token checks 300 and scan checks 120 per minute. Each counts per store, and three times as much across all stores; an IPv6 address counts by its /64.

A session is only started when the shopper submits their email, so page views create nothing. A code is only sent to an address whose domain can receive email.

Merchant API#

Read the gate with your API keys, signed like every merchant API request:

RequestAnswer
GET /api/v1/gate?limit=20Whether the gate is required, on and working (health: working, installed, not_installed, needs_attention or off, explained under Dashboard status), the current terms, the last storefront check, the plugin's last report, counts, and the most recent completions (limit 1 to 100).
GET /api/v1/gate/sessions/{id}One completed session's evidence: email, email_verified_at, terms (version, SHA-256, title, text, shown_at, reviewed_at), signature (SHA-256, bytes, signed_at, image_url valid for 5 minutes), ip, user_agent, started_at, completed_at, token_expires_at and every step in events with its time, IP address and user agent.

The token's sub is the session ID, so a token from a shopper's cookie leads to their evidence.

Dashboard status#

Integrations → Shopper gate shows whether the gate is required, on or off, and its health:

HealthMeaning
WorkingInstalled, and shoppers completed it in the last 30 days or your server checked tokens in the last 7.
InstalledThe markers were found (or the plugin reported in), but no shopper has completed it in the last 30 days.
Not installedThe gate is on, but the storefront check did not find it.
Needs attentionIt worked before and the last storefront check could not find it; or the gate page can be kept by a cache (it is not sent with Cache-Control: private, no-store); or your store is in the RUO program and the gate runs only in the browser (snippet or frame), not on your server.
OffThe gate is off for this store.

Check my storefront now fetches your home page as a new visitor, looks for the markers and reads the gate page's Cache-Control. With a gate key, the WordPress plugin also reports its settings and its own check once a day.

Caches and CDNs#

A gated response and an ungated one must never be served to the wrong visitor. Send Cache-Control: private, no-store and Vary: Cookie on the gate page and on every real page a shopper sees after passing, and do not let a CDN or reverse proxy cache HTML pages for a gated store (caching images, CSS and JavaScript is fine). If your host offers a full-page cache, turn it off for HTML or exclude every page the gate governs. The gate's own pages and API on app.oncharge.io are never cached, except the store config (one minute) and the keys (one hour).

Test vectors#

/docs/files/shopper-gate/test-vectors.json has 22 OnCharge-Scan cases and 16 completion-token cases, each with the expected result, and test keys (each seed is the SHA-256 of a public label). OnCharge's own checks, the WordPress plugin and the module on this page all give these results; run them against your own code.

Troubleshooting#

ProblemFix
"This verification can only be shown on … own website"Add the site to your store's websites (Security → Domains), with https and no port.
The gate does not appear, or stays blankIf your site sends a Content Security Policy, allow https://app.oncharge.io in script-src, frame-src and connect-src.
Shoppers are asked again on every pageThe cookie is set on one host and read on another (www and the bare domain): set data-cookie-domain. Also check a cache is not answering with a stored gate page.
"Your browser did not keep the cookie this store needs"The shopper's browser blocks cookies for your site.
The code email does not arriveIt comes from OnCharge; ask the shopper to check spam. A new code can be sent after a short wait (see Limits).
OnCharge-Gate-Scan: staleYour server's clock is off by more than 5 minutes.
OnCharge-Gate-Scan: keys-unavailableYour server cannot reach app.oncharge.io.
The dashboard says "Not installed"Open your home page in a private window: you should see the gate, and the page source should have the markers. Then select Check my storefront now.

Build it with AI#

The AI prompt library has a prompt that has Claude, ChatGPT or Cursor add the gate to a Next.js, Hydrogen, Shopify or other storefront, with the server check and tests.