Skip to main content

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://localhost works 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:

  1. API Keys: create a key pair if you have none, and copy the secret key.
  2. Configuration → Verification: check the verification mode and challenge age. Your sessions use these unless you deliberately override them.
  3. Configuration → Domains (recommended): add your site's domain. While the list is not empty, return URLs on other domains are refused. Add localhost while you test locally.
  4. 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:

.env (never commit this file)
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 verificationMode or challengeAge unless you mean to override your Dashboard settings for this session.
  • Store the sessionId with 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.
// ── 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);
});
You should see
  • Create Session returns HTTP 201 with sessionId, verifyUrl and expiresAt.
  • 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:

  1. Check that sessionId is the session this user started.
  2. Call Validate Session with your secret key.
  3. Grant access only if the response has accessGranted: true and the externalUserId you expect.
  4. 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.

// ── 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));
});
Validate Session resultWhat it meansWhat to do
200, accessGranted: trueVerifiedRecord it against the user and grant access.
200, status: "pending"Not finished: the user left early, or the result is seconds awayOffer Continue verification (the same session) and Check again.
200, status: "cancelled"The user cancelledOffer a new attempt.
200, status: "failed"The session ended in an unrecoverable error (rare)Offer a new attempt.
400 Session has expiredThe 10-minute session ended unfinishedOffer a new attempt.
401Publishable key used, or the secret key is revokedFix the configuration. Users cannot fix this.
404 Session not foundUnknown ID, or a session from a different accountDo not grant access. Check that you use one account's keys throughout.
429, 5xx or no responseRate limit or temporary problemDo 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.

You should see

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.

// ── 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);
}

Payloads, retries, deduplication and the Test button are described in Webhooks.

You should see
  • 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 401 and 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.

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
// 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}`));

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.

ParameterValuesEffect
langen, de, es, fr, pt, itShow the page in this language instead of the browser's language.
skip_introtrueSkip the introduction screen and go straight to the camera.
auto_returntrueReturn 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​

  1. Test your integration: successful, unsuccessful, interrupted and expired journeys.
  2. Work through the go-live checklist.
  3. Keep Troubleshooting handy.

Reference: Sessions API · Webhooks