Server integration
This is the recommended way to add SafePassage age verification to a website. Your server creates each verification session, sends the user to the hosted SafePassage page, and confirms the result with your secret key before granting access. No SafePassage code runs in the browser.
You need a developer who can add a few routes to your site's server-side code. The examples below are complete programs in Node.js and PHP; the same two API calls work from any language.
Before you start
- A SafePassage account with access to the Dashboard. Creating keys and changing configuration or webhooks needs the Owner or Admin role.
- A secret key (
sk_…) from Dashboard → API Keys. It stays on your server. - A page on your site that users return to (the return URL). In production
it must use HTTPS;
http://localhostworks for local testing. - Recommended: a public HTTPS address for webhooks.
- Read How verification works, and choose your verification mode and challenge age.
What you will build: a "Verify my age" button, a return page that confirms the result and unlocks a members area, and a webhook receiver that rejects anything without a valid signature.
Step 1: Configure your account
In the Dashboard:
- API Keys: create a key pair if you have none, and copy the secret key.
- Configuration → Verification: check the verification mode and challenge age. Your sessions use these unless you deliberately override them.
- Configuration → Domains (recommended): add your site's domain. While
the list is not empty, return URLs on other domains are refused. Add
localhostwhile you test locally. - Configuration → Webhooks (recommended): add your webhook URL and copy its signing secret, which is shown only once. See Webhooks.
Store the values as environment variables on your server, for example in your
hosting control panel or process manager. For local testing you can put them in
a .env file and start Node.js with node --env-file=.env server.mjs
(Node.js 20.6 or later), or export them as shown in the complete example:
SAFEPASSAGE_SECRET_KEY=sk_your_secret_key
SAFEPASSAGE_WEBHOOK_SECRET=your_webhook_signing_secret
BASE_URL=http://localhost:3000
Step 2: Create a session and send the user to it
When the user asks to verify, your server calls Create Session with your
secret key and redirects the browser to the returned verifyUrl.
- Send
externalUserId, your own ID for the signed-in user, so the result can be matched to them later. - Do not send
verificationModeorchallengeAgeunless you mean to override your Dashboard settings for this session. - Store the
sessionIdwith the user's record or server-side session. You use it to check that the user who returns is the user who started. - If the user already has an unfinished session, send them back to it instead of creating another one each time they click.
- Node.js
- PHP
- cURL
// ── Create a session (or reuse an unfinished one) and send the user ─────────
app.post('/verify/start', async (req, res) => {
const user = getUser(req.userId);
if (user.verified) return res.redirect(303, '/members');
// Reuse this user's unfinished session instead of creating a new one per click.
if (user.pending && Date.now() < user.pending.expiresAt - 60_000) {
const check = await callApi('/sessions/validate', { sessionId: user.pending.sessionId });
if (check.status === 200 && check.body.status === 'pending') return res.redirect(303, user.pending.verifyUrl);
if (check.status === 0 || check.status >= 500) {
// API unreachable: answer now rather than wait for a second request to time out.
console.error('Session validation failed', check.status, check.body.message);
return res.status(503).send(page('Verification is unavailable', '<p>Please try again in a few minutes.</p>'));
}
}
// No verificationMode or challengeAge: the session uses your Dashboard settings.
const { status, body } = await callApi('/sessions/create', {
returnUrl: `${BASE_URL}/verify/return`,
externalUserId: req.userId,
});
if (status < 200 || status >= 300) {
console.error('Session creation failed', status, body.code ?? body.message);
return res.status(503).send(page('Verification is unavailable', '<p>Please try again in a few minutes.</p>'));
}
user.pending = { sessionId: body.sessionId, verifyUrl: body.verifyUrl, expiresAt: Date.parse(body.expiresAt) };
res.redirect(303, body.verifyUrl);
});
<?php
// start.php: create a session (or reuse an unfinished one) and send the user.
require __DIR__ . '/config.php';
$userId = current_user_id();
if (is_verified($userId)) { header('Location: /members.php', true, 303); exit; }
// Reuse this user's unfinished session instead of creating a new one per click.
$pending = $_SESSION['pending'] ?? null;
if ($pending && time() < $pending['expiresAt'] - 60) {
[$status, $body] = call_api('/sessions/validate', ['sessionId' => $pending['sessionId']]);
if ($status === 200 && ($body['status'] ?? '') === 'pending') {
header('Location: ' . $pending['verifyUrl'], true, 303);
exit;
}
if ($status === 0 || $status >= 500) {
// API unreachable: answer now. A second 15-second call would exceed PHP's default 30-second time limit.
error_log('Session validation failed: ' . $status);
http_response_code(503);
page('Verification is unavailable', '<p>Please try again in a few minutes.</p>');
exit;
}
}
// No verificationMode or challengeAge: the session uses your Dashboard settings.
[$status, $body] = call_api('/sessions/create', [
'returnUrl' => BASE_URL . '/return.php',
'externalUserId' => $userId,
]);
if ($status < 200 || $status >= 300) {
error_log('Session creation failed: ' . $status . ' ' . ($body['code'] ?? json_encode($body['message'] ?? '')));
http_response_code(503);
page('Verification is unavailable', '<p>Please try again in a few minutes.</p>');
exit;
}
$_SESSION['pending'] = [
'sessionId' => $body['sessionId'],
'verifyUrl' => $body['verifyUrl'],
'expiresAt' => strtotime($body['expiresAt']),
];
header('Location: ' . $body['verifyUrl'], true, 303);
curl -X POST "https://api.safepassageapp.com/api/v1/sessions/create" \
-H "Authorization: Bearer $SAFEPASSAGE_SECRET_KEY" \
-H "Content-Type: application/json" \
-d '{"returnUrl": "http://localhost:3000/verify/return", "externalUserId": "user_12345"}'
- Create Session returns HTTP
201withsessionId,verifyUrlandexpiresAt. - The browser opens the SafePassage verification page.
If not: 401 means the key is missing, wrong or revoked.
400 Return URL domain not allowed means the return URL's domain is not in your
allowed domains. 403 with a code, or a response containing billingBlock,
means your account cannot start verifications right now. See
Troubleshooting.
Step 3: Confirm the result when the user returns
After a successful verification, SafePassage sends the user to your return
URL with sessionId, status=verified and timestamp added. Ignore
status: anyone can edit it. Instead:
- Check that
sessionIdis the session this user started. - Call Validate Session with your secret key.
- Grant access only if the response has
accessGranted: trueand theexternalUserIdyou expect. - Handle every other outcome, and always send a response.
Users who do not pass stay on the hosted page, where they can try again. If
they choose Return to site before finishing, they arrive at your
cancelUrl (or, if you did not set one, your return URL) without any
parameters, while their session stays open until it expires. Your return page
should therefore also work without a sessionId, by checking the session the
user started, as the examples do.
- Node.js
- PHP
- cURL
// ── Confirm the result when the user returns, before granting access ──────
app.get('/verify/return', async (req, res) => {
const user = getUser(req.userId);
if (user.verified) return res.redirect(303, '/members');
if (!user.pending) return res.redirect(303, '/'); // nothing in progress
// Ignore the status parameter. A user who leaves the hosted page without
// finishing comes back with no parameters, so fall back to their own session.
const sessionId = String(req.query.sessionId ?? user.pending.sessionId);
if (sessionId !== user.pending.sessionId) {
return res.status(400).send(page('We could not match this verification', startButton('Start again')));
}
const { status, body } = await callApi('/sessions/validate', { sessionId });
const checkAgain = `<p><a href="/verify/return?sessionId=${encodeURIComponent(sessionId)}">Check again</a></p>`;
if (status === 200 && body.accessGranted === true && body.externalUserId === req.userId) {
user.verified = true;
user.verifiedSessionId = sessionId;
delete user.pending;
return res.redirect(303, '/members');
}
if (status === 200 && body.status === 'pending') {
// Not finished: the user left early, or the result is a few seconds away.
return res.send(page('Your verification is not finished', '<p>If you have just finished, wait a moment and check again.</p>' +
startButton('Continue verification') + checkAgain));
}
if (status === 200 || status === 400) {
// failed, cancelled, or 400 "Session has expired": offer a new attempt.
delete user.pending;
const title = body.status === 'cancelled' ? 'Verification cancelled' : 'Verification not completed';
return res.send(page(title, '<p>You can try again. Use a valid photo ID in good light if asked.</p>' + startButton('Try again')));
}
// 401, 404, 429, 5xx or network error: a configuration or temporary problem.
console.error('Session validation failed', status, body.message);
res.status(502).send(page('We could not confirm your verification', '<p>Please try again shortly.</p>' + checkAgain));
});
<?php
// return.php: the user returns. Confirm the result before granting access.
require __DIR__ . '/config.php';
$userId = current_user_id();
if (is_verified($userId)) { header('Location: /members.php', true, 303); exit; }
$pending = $_SESSION['pending'] ?? null;
if (!$pending) { header('Location: /', true, 303); exit; } // nothing in progress
// Ignore the status parameter. A user who leaves the hosted page without
// finishing comes back with no parameters, so fall back to their own session.
$sessionId = (string) ($_GET['sessionId'] ?? $pending['sessionId']);
if (!hash_equals($pending['sessionId'], $sessionId)) {
http_response_code(400);
page('We could not match this verification', start_button('Start again'));
exit;
}
[$status, $body] = call_api('/sessions/validate', ['sessionId' => $sessionId]);
$checkAgain = '<p><a href="/return.php?sessionId=' . urlencode($sessionId) . '">Check again</a></p>';
if ($status === 200 && ($body['accessGranted'] ?? false) === true && ($body['externalUserId'] ?? null) === $userId) {
mark_verified($userId, $sessionId);
unset($_SESSION['pending']);
header('Location: /members.php', true, 303);
exit;
}
if ($status === 200 && ($body['status'] ?? '') === 'pending') {
// Not finished: the user left early, or the result is a few seconds away.
page('Your verification is not finished', '<p>If you have just finished, wait a moment and check again.</p>'
. start_button('Continue verification') . $checkAgain);
exit;
}
if ($status === 200 || $status === 400) {
// failed, cancelled, or 400 "Session has expired": offer a new attempt.
unset($_SESSION['pending']);
$title = ($body['status'] ?? '') === 'cancelled' ? 'Verification cancelled' : 'Verification not completed';
page($title, '<p>You can try again. Use a valid photo ID in good light if asked.</p>' . start_button('Try again'));
exit;
}
// 401, 404, 429, 5xx or network error: a configuration or temporary problem.
error_log('Session validation failed: ' . $status . ' ' . json_encode($body['message'] ?? ''));
http_response_code(502);
page('We could not confirm your verification', '<p>Please try again shortly.</p>' . $checkAgain);
curl -X POST "https://api.safepassageapp.com/api/v1/sessions/validate" \
-H "Authorization: Bearer $SAFEPASSAGE_SECRET_KEY" \
-H "Content-Type: application/json" \
-d '{"sessionId": "550e8400-e29b-41d4-a716-446655440000"}'
| Validate Session result | What it means | What to do |
|---|---|---|
200, accessGranted: true | Verified | Record it against the user and grant access. |
200, status: "pending" | Not finished: the user left early, or the result is seconds away | Offer Continue verification (the same session) and Check again. |
200, status: "cancelled" | The user cancelled | Offer a new attempt. |
200, status: "failed" | The session ended in an unrecoverable error (rare) | Offer a new attempt. |
400 Session has expired | The 10-minute session ended unfinished | Offer a new attempt. |
401 | Publishable key used, or the secret key is revoked | Fix the configuration. Users cannot fix this. |
404 Session not found | Unknown ID, or a session from a different account | Do not grant access. Check that you use one account's keys throughout. |
429, 5xx or no response | Rate limit or temporary problem | Do not grant access yet. Let the user check again shortly. |
Calling Validate Session again for the same session returns the same result. It does not create another verification, charge or webhook. Validation is limited to 100 calls per minute per account, so record a verified result in your own database instead of validating on every page view, and rely on webhooks rather than polling for busy sites.
After a successful verification your return page redirects to the members
area. Change status=verified to status=failed (or the reverse) in the
address bar and reload: nothing changes, because the decision comes from
Validate Session.
Step 4: Receive webhooks
Webhooks tell your server about results even when the user never comes back to your site, for example after closing the tab or finishing on a phone. They are optional but recommended.
Every webhook is signed. Your receiver must reject any request without a valid signature before it reads or acts on the body.
- Node.js
- PHP
// ── Webhooks ─────────────────────────────────────────────────────────────────
// Registered before any JSON parser: the signature covers the raw body bytes.
app.post('/webhooks/safepassage', express.raw({ type: '*/*', limit: '100kb' }), (req, res) => {
const signature = req.get('x-safepassage-signature');
if (!WEBHOOK_SECRET || !signature || !Buffer.isBuffer(req.body) || !isValidSignature(req.body, signature)) {
// Missing or wrong signature: reject without changing anything.
return res.status(401).json({ error: 'invalid signature' });
}
const event = JSON.parse(req.body.toString('utf8'));
const dedupeKey = event.eventId ?? `${event.event}:${event.data?.sessionId}`;
if (processedEvents.has(dedupeKey)) return res.json({ received: true, duplicate: true });
if (event.test) {
console.log(`Test event received: ${event.event}`); // Dashboard test: never changes access
} else if (event.event === 'verification.completed' && event.data?.verified === true) {
const user = users.get(event.data.externalUserId);
if (user) {
user.verified = true;
user.verifiedSessionId = event.data.sessionId;
if (user.pending?.sessionId === event.data.sessionId) delete user.pending;
}
}
processedEvents.add(dedupeKey);
res.json({ received: true });
});
function isValidSignature(rawBody, header) {
const expected = 'sha256=' + crypto.createHmac('sha256', WEBHOOK_SECRET).update(rawBody).digest('hex');
const a = Buffer.from(header);
const b = Buffer.from(expected);
return a.length === b.length && crypto.timingSafeEqual(a, b);
}
<?php
// webhook.php: receive SafePassage webhooks. The signature is required.
require __DIR__ . '/config.php';
$rawBody = file_get_contents('php://input'); // the exact bytes that were signed
$headerKey = 'HTTP_' . strtoupper(str_replace('-', '_', 'x-safepassage-signature'));
$signature = $_SERVER[$headerKey] ?? '';
$expected = 'sha256=' . hash_hmac('sha256', $rawBody, WEBHOOK_SECRET);
if (WEBHOOK_SECRET === '' || $signature === '' || !hash_equals($expected, $signature)) {
// Missing or wrong signature: reject without changing anything.
http_response_code(401);
header('Content-Type: application/json');
exit(json_encode(['error' => 'invalid signature']));
}
$event = json_decode($rawBody, true);
$data = $event['data'] ?? [];
if (!empty($event['test'])) {
error_log('Test event received: ' . ($event['event'] ?? '')); // Dashboard test: never changes access
} elseif (($event['event'] ?? '') === 'verification.completed' && ($data['verified'] ?? false) === true
&& !empty($data['externalUserId'])) {
// Recording the same verified session twice is harmless, so retries are safe.
mark_verified($data['externalUserId'], $data['sessionId']);
}
header('Content-Type: application/json');
echo json_encode(['received' => true]);
Payloads, retries, deduplication and the Test button are described in Webhooks.
- Configuration → Webhooks → Test on your endpoint succeeds, and your
server logs
Test event received. Test events never change access. - A request without a valid signature gets
401and changes nothing:curl -i -X POST http://localhost:3000/webhooks/safepassage -d '{}'
Complete example
Both versions implement steps 2 to 4 with a demo sign-in and simple storage. Replace those parts with your own login and database.
- Node.js
- PHP
Requires Node.js 18 or later.
npm install express
export SAFEPASSAGE_SECRET_KEY=sk_your_secret_key
export SAFEPASSAGE_WEBHOOK_SECRET=your_webhook_signing_secret
node server.mjs # then open http://localhost:3000
server.mjs
// server.mjs: a complete SafePassage server integration (Node.js 18+, Express).
// Run: npm install express && node server.mjs
import crypto from 'node:crypto';
import express from 'express';
const API_URL = 'https://api.safepassageapp.com/api/v1';
const SECRET_KEY = process.env.SAFEPASSAGE_SECRET_KEY;
const WEBHOOK_SECRET = process.env.SAFEPASSAGE_WEBHOOK_SECRET;
const BASE_URL = process.env.BASE_URL || 'http://localhost:3000';
if (!SECRET_KEY?.startsWith('sk_')) throw new Error('Set SAFEPASSAGE_SECRET_KEY to your secret key (sk_...)');
// Demo storage. Use your database in production.
const users = new Map(); // userId -> { verified, verifiedSessionId, pending }
const processedEvents = new Set();
const getUser = (id) => users.get(id) ?? users.set(id, { verified: false }).get(id);
const app = express();
// Call the SafePassage API with the secret key. Returns { status, body }.
async function callApi(path, payload) {
try {
const response = await fetch(`${API_URL}${path}`, {
method: 'POST',
headers: { Authorization: `Bearer ${SECRET_KEY}`, 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
signal: AbortSignal.timeout(15000),
});
return { status: response.status, body: await response.json().catch(() => ({})) };
} catch (error) {
return { status: 0, body: { message: error.message } }; // network error or timeout
}
}
// ── Webhooks ─────────────────────────────────────────────────────────────────
// Registered before any JSON parser: the signature covers the raw body bytes.
app.post('/webhooks/safepassage', express.raw({ type: '*/*', limit: '100kb' }), (req, res) => {
const signature = req.get('x-safepassage-signature');
if (!WEBHOOK_SECRET || !signature || !Buffer.isBuffer(req.body) || !isValidSignature(req.body, signature)) {
// Missing or wrong signature: reject without changing anything.
return res.status(401).json({ error: 'invalid signature' });
}
const event = JSON.parse(req.body.toString('utf8'));
const dedupeKey = event.eventId ?? `${event.event}:${event.data?.sessionId}`;
if (processedEvents.has(dedupeKey)) return res.json({ received: true, duplicate: true });
if (event.test) {
console.log(`Test event received: ${event.event}`); // Dashboard test: never changes access
} else if (event.event === 'verification.completed' && event.data?.verified === true) {
const user = users.get(event.data.externalUserId);
if (user) {
user.verified = true;
user.verifiedSessionId = event.data.sessionId;
if (user.pending?.sessionId === event.data.sessionId) delete user.pending;
}
}
processedEvents.add(dedupeKey);
res.json({ received: true });
});
function isValidSignature(rawBody, header) {
const expected = 'sha256=' + crypto.createHmac('sha256', WEBHOOK_SECRET).update(rawBody).digest('hex');
const a = Buffer.from(header);
const b = Buffer.from(expected);
return a.length === b.length && crypto.timingSafeEqual(a, b);
}
// ── Demo sign-in ─────────────────────────────────────────────────────────────
// Gives each browser a random user ID in a cookie. Use your real login instead.
app.use((req, res, next) => {
const match = /(?:^|;\s*)demo_uid=([\w-]+)/.exec(req.headers.cookie || '');
req.userId = match ? match[1] : crypto.randomUUID();
if (!match) res.append('Set-Cookie', `demo_uid=${req.userId}; Path=/; HttpOnly; SameSite=Lax`);
next();
});
const page = (title, body) =>
`<!doctype html><meta name="viewport" content="width=device-width"><title>${title}</title><h1>${title}</h1>${body}`;
const startButton = (label) => `<form method="post" action="/verify/start"><button>${label}</button></form>`;
app.get('/', (req, res) => {
if (getUser(req.userId).verified) return res.redirect('/members');
res.send(page('Age verification required', startButton('Verify my age')));
});
app.get('/members', (req, res) => {
if (!getUser(req.userId).verified) return res.redirect('/');
res.send(page('Members area', '<p>You are verified.</p>'));
});
// ── Create a session (or reuse an unfinished one) and send the user ─────────
app.post('/verify/start', async (req, res) => {
const user = getUser(req.userId);
if (user.verified) return res.redirect(303, '/members');
// Reuse this user's unfinished session instead of creating a new one per click.
if (user.pending && Date.now() < user.pending.expiresAt - 60_000) {
const check = await callApi('/sessions/validate', { sessionId: user.pending.sessionId });
if (check.status === 200 && check.body.status === 'pending') return res.redirect(303, user.pending.verifyUrl);
if (check.status === 0 || check.status >= 500) {
// API unreachable: answer now rather than wait for a second request to time out.
console.error('Session validation failed', check.status, check.body.message);
return res.status(503).send(page('Verification is unavailable', '<p>Please try again in a few minutes.</p>'));
}
}
// No verificationMode or challengeAge: the session uses your Dashboard settings.
const { status, body } = await callApi('/sessions/create', {
returnUrl: `${BASE_URL}/verify/return`,
externalUserId: req.userId,
});
if (status < 200 || status >= 300) {
console.error('Session creation failed', status, body.code ?? body.message);
return res.status(503).send(page('Verification is unavailable', '<p>Please try again in a few minutes.</p>'));
}
user.pending = { sessionId: body.sessionId, verifyUrl: body.verifyUrl, expiresAt: Date.parse(body.expiresAt) };
res.redirect(303, body.verifyUrl);
});
// ── Confirm the result when the user returns, before granting access ──────
app.get('/verify/return', async (req, res) => {
const user = getUser(req.userId);
if (user.verified) return res.redirect(303, '/members');
if (!user.pending) return res.redirect(303, '/'); // nothing in progress
// Ignore the status parameter. A user who leaves the hosted page without
// finishing comes back with no parameters, so fall back to their own session.
const sessionId = String(req.query.sessionId ?? user.pending.sessionId);
if (sessionId !== user.pending.sessionId) {
return res.status(400).send(page('We could not match this verification', startButton('Start again')));
}
const { status, body } = await callApi('/sessions/validate', { sessionId });
const checkAgain = `<p><a href="/verify/return?sessionId=${encodeURIComponent(sessionId)}">Check again</a></p>`;
if (status === 200 && body.accessGranted === true && body.externalUserId === req.userId) {
user.verified = true;
user.verifiedSessionId = sessionId;
delete user.pending;
return res.redirect(303, '/members');
}
if (status === 200 && body.status === 'pending') {
// Not finished: the user left early, or the result is a few seconds away.
return res.send(page('Your verification is not finished', '<p>If you have just finished, wait a moment and check again.</p>' +
startButton('Continue verification') + checkAgain));
}
if (status === 200 || status === 400) {
// failed, cancelled, or 400 "Session has expired": offer a new attempt.
delete user.pending;
const title = body.status === 'cancelled' ? 'Verification cancelled' : 'Verification not completed';
return res.send(page(title, '<p>You can try again. Use a valid photo ID in good light if asked.</p>' + startButton('Try again')));
}
// 401, 404, 429, 5xx or network error: a configuration or temporary problem.
console.error('Session validation failed', status, body.message);
res.status(502).send(page('We could not confirm your verification', '<p>Please try again shortly.</p>' + checkAgain));
});
// ── Start the server ─────────────────────────────────────────────────────────
app.listen(3000, () => console.log(`Listening on ${BASE_URL}`));
Requires PHP 7.4 or later with the curl extension. Put the six files in one folder.
export SAFEPASSAGE_SECRET_KEY=sk_your_secret_key
export SAFEPASSAGE_WEBHOOK_SECRET=your_webhook_signing_secret
php -S 127.0.0.1:8000 # then open http://127.0.0.1:8000
config.php, index.php and members.php
<?php
// config.php: shared helpers for the SafePassage PHP example (PHP 7.4+ with the curl extension).
const API_URL = 'https://api.safepassageapp.com/api/v1';
define('SECRET_KEY', getenv('SAFEPASSAGE_SECRET_KEY') ?: '');
define('WEBHOOK_SECRET', getenv('SAFEPASSAGE_WEBHOOK_SECRET') ?: '');
define('BASE_URL', getenv('BASE_URL') ?: 'http://127.0.0.1:8000');
define('VERIFIED_STORE', __DIR__ . '/verified-users.json'); // demo storage: use your database
if (strpos(SECRET_KEY, 'sk_') !== 0) {
http_response_code(500);
exit('Set SAFEPASSAGE_SECRET_KEY to your secret key (sk_...)');
}
// Call the SafePassage API with the secret key. Returns [status, body].
function call_api(string $path, array $payload): array {
$ch = curl_init(API_URL . $path);
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 15,
CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . SECRET_KEY, 'Content-Type: application/json'],
CURLOPT_POSTFIELDS => json_encode($payload),
]);
$raw = curl_exec($ch);
$status = $raw === false ? 0 : curl_getinfo($ch, CURLINFO_RESPONSE_CODE); // 0 = network error
curl_close($ch);
return [$status, json_decode((string) $raw, true) ?: []];
}
function verified_users(): array {
return is_file(VERIFIED_STORE) ? (json_decode((string) file_get_contents(VERIFIED_STORE), true) ?: []) : [];
}
function mark_verified(string $userId, string $sessionId): void {
$users = verified_users();
$users[$userId] = $sessionId;
file_put_contents(VERIFIED_STORE, json_encode($users), LOCK_EX);
}
function current_user_id(): string {
if (session_status() !== PHP_SESSION_ACTIVE) session_start();
// Demo sign-in: a random user ID per browser session. Use your real login instead.
return $_SESSION['uid'] ??= bin2hex(random_bytes(16));
}
function is_verified(string $userId): bool {
return isset(verified_users()[$userId]);
}
function page(string $title, string $body): void {
echo '<!doctype html><meta name="viewport" content="width=device-width"><title>' . $title . '</title><h1>' . $title . '</h1>' . $body;
}
function start_button(string $label): string {
return '<form method="post" action="/start.php"><button>' . $label . '</button></form>';
}
<?php
require __DIR__ . '/config.php';
if (is_verified(current_user_id())) { header('Location: /members.php'); exit; }
page('Age verification required', start_button('Verify my age'));
<?php
require __DIR__ . '/config.php';
if (!is_verified(current_user_id())) { header('Location: /'); exit; }
page('Members area', '<p>You are verified.</p>');
start.php, return.php and webhook.php are shown in full in steps 2 to 4.
For the PHP version, set BASE_URL=http://127.0.0.1:8000, and add 127.0.0.1 to your allowed domains while testing.
To receive webhooks on your computer, expose the local server through an HTTPS
tunnel (for example ngrok http 3000 or cloudflared tunnel --url http://localhost:3000)
and use the tunnel's HTTPS address for the endpoint in the Dashboard. Webhook
addresses must be public HTTPS URLs.
Optional: customise the hosted page
You can add these parameters to verifyUrl before redirecting. Do not change
or remove anything else in the URL.
| Parameter | Values | Effect |
|---|---|---|
lang | en, de, es, fr, pt, it | Show the page in this language instead of the browser's language. |
skip_intro | true | Skip the introduction screen and go straight to the camera. |
auto_return | true | Return to your site immediately after a successful verification, without the success screen. |
const url = new URL(body.verifyUrl);
url.searchParams.set('lang', 'es');
res.redirect(303, url.toString());
To open verification in a new tab or popup instead of redirecting, open the
verifyUrl with window.open(). If you pass a cancelUrl when creating the
session, a user who closes the window before finishing is sent there with
status=cancelled.
Next steps
- Test your integration: successful, unsuccessful, interrupted and expired journeys.
- Work through the go-live checklist.
- Keep Troubleshooting handy.
Reference: Sessions API · Webhooks