WordPress
This guide adds SafePassage age verification to a WordPress site with one custom code file. Visitors see a Verify my age button in place of restricted content; after they verify, WordPress confirms the result with SafePassage and shows the content.
There is no SafePassage plugin to install from the WordPress plugin
directory. You will copy one PHP file to your server and add two lines to
wp-config.php. If you are comfortable doing that with your host's file
manager, SFTP or a deployment tool, you can follow this guide. If not, send
your developer or host the developer handoff at the end
of this page.
What the code does
- Adds the shortcode
[safepassage_age_gate]…[/safepassage_age_gate]. Content inside it is shown only to verified visitors. - Starts a verification only when the visitor clicks the button. Viewing a page never creates a session, and a visitor who comes back to an unfinished verification continues the same session instead of starting a new one.
- Confirms every result on the server with your secret key before showing
content. The
statusin the return address is ignored. - Remembers verified visitors: signed-in users stay verified on their account; visitors who are not signed in stay verified for 30 days in that browser.
- Receives webhooks (messages SafePassage sends to your site) at
/wp-json/safepassage/v1/webhook, and rejects any message without a valid signature. Webhooks record a result even when a visitor closes the tab before coming back to your site, for example after finishing on their phone. Without them, those visitors have to click the button again.
Before you start
- WordPress 5.9 or later on PHP 7.4 or later, served over HTTPS.
- Access to
wp-config.phpand thewp-contentfolder. - Pretty permalinks turned on: in WordPress, Settings → Permalinks set to anything except "Plain". The webhook address needs it.
- Owner or Admin access to the SafePassage Dashboard.
Step 1: Configure SafePassage
In the Dashboard:
- API Keys: create a key pair if you have none, and copy the secret key (
sk_…). - Configuration → Verification: choose your verification mode and challenge age. Read Age policy and verification modes first.
- Configuration → Domains: add your site's domain, for example
example.com. - Configuration → Webhooks → Add Endpoint: enter
https://your-site.example/wp-json/safepassage/v1/webhook(with your domain), select verification.completed, and save. Copy the signing secret now; it is shown only once.
Step 2: Add your keys to wp-config.php
Add these lines above /* That's all, stop editing! */, using your values:
define('SAFEPASSAGE_SECRET_KEY', 'sk_your_secret_key');
define('SAFEPASSAGE_WEBHOOK_SECRET', 'your_webhook_signing_secret');
Never put these values in a theme file, page content or JavaScript.
Step 3: Add the code file
- In
wp-content, create a folder namedmu-pluginsif it does not exist. Code in this folder (WordPress calls it a "must-use plugin") runs automatically and cannot be switched off by mistake from the Plugins screen. - Create a file named
safepassage-age-verification.phpin that folder, and paste in the code below exactly as shown. Use the copy button at the top right of the code.
Show or hide the code to copy (safepassage-age-verification.php)
<?php
/**
* Plugin Name: SafePassage age verification (site code)
* Description: Server-side SafePassage age verification for this site: an age-gate shortcode, session
* creation, result confirmation and signed webhooks. From the SafePassage WordPress guide.
*
* Install as wp-content/mu-plugins/safepassage-age-verification.php and add to wp-config.php:
* define('SAFEPASSAGE_SECRET_KEY', 'sk_your_secret_key');
* define('SAFEPASSAGE_WEBHOOK_SECRET', 'your_webhook_signing_secret');
*/
if (!defined('ABSPATH')) {
exit;
}
const SAFEPASSAGE_API_URL = 'https://api.safepassageapp.com/api/v1';
const SAFEPASSAGE_VISITOR_COOKIE = 'safepassage_visitor';
const SAFEPASSAGE_VERIFIED_DAYS = 30; // how long a visitor (not signed in) stays verified
// ── Who is verifying ─────────────────────────────────────────────────────────
// Signed-in users are identified by their user ID. Visitors who are not signed
// in get a random token in an HttpOnly cookie; only a hash of it is stored or
// sent to SafePassage.
function safepassage_subject(bool $create = false): ?string {
if (is_user_logged_in()) {
return 'wp-user-' . get_current_user_id();
}
$token = $_COOKIE[SAFEPASSAGE_VISITOR_COOKIE] ?? '';
if (!preg_match('/^[a-f0-9]{64}$/', $token)) {
if (!$create) {
return null;
}
$token = bin2hex(random_bytes(32));
setcookie(SAFEPASSAGE_VISITOR_COOKIE, $token, [
'expires' => time() + SAFEPASSAGE_VERIFIED_DAYS * DAY_IN_SECONDS,
'path' => COOKIEPATH ?: '/',
'secure' => is_ssl(),
'httponly' => true,
'samesite' => 'Lax', // sent when the user returns from the verification page
]);
}
return 'visitor-' . substr(hash('sha256', $token), 0, 40);
}
function safepassage_get_state(string $subject): array {
if (preg_match('/^wp-user-(\d+)$/', $subject, $m)) {
return (array) (get_user_meta((int) $m[1], 'safepassage_verification', true) ?: []);
}
return (array) (get_transient('safepassage_' . $subject) ?: []);
}
function safepassage_set_state(string $subject, array $state): void {
if (preg_match('/^wp-user-(\d+)$/', $subject, $m)) {
update_user_meta((int) $m[1], 'safepassage_verification', $state);
return;
}
set_transient('safepassage_' . $subject, $state, SAFEPASSAGE_VERIFIED_DAYS * DAY_IN_SECONDS);
}
/** Use in templates: if (!safepassage_is_verified()) { ... } */
function safepassage_is_verified(): bool {
$subject = safepassage_subject();
return $subject !== null && !empty(safepassage_get_state($subject)['verifiedSessionId']);
}
// ── SafePassage API ─────────────────────────────────────────────────────────
/** Returns [HTTP status, decoded body]. Status 0 means the request did not complete. */
function safepassage_api(string $path, array $payload): array {
$response = wp_remote_post(SAFEPASSAGE_API_URL . $path, [
'headers' => [
'Authorization' => 'Bearer ' . (defined('SAFEPASSAGE_SECRET_KEY') ? constant('SAFEPASSAGE_SECRET_KEY') : ''),
'Content-Type' => 'application/json',
],
'body' => wp_json_encode($payload),
'timeout' => 15,
]);
if (is_wp_error($response)) {
error_log('SafePassage API request failed: ' . $response->get_error_message());
return [0, []];
}
return [(int) wp_remote_retrieve_response_code($response), json_decode(wp_remote_retrieve_body($response), true) ?: []];
}
function safepassage_message(string $title, string $html, int $status = 200): void {
wp_die($html, esc_html($title), ['response' => $status, 'back_link' => false]);
}
function safepassage_start_form(string $label, string $redirectTo): string {
// No nonce: starting a verification is harmless, and gated pages are often
// cached, which would serve expired nonces.
return '<form method="post" action="' . esc_url(admin_url('admin-post.php')) . '">'
. '<input type="hidden" name="action" value="safepassage_verify_start">'
. '<input type="hidden" name="redirect_to" value="' . esc_attr($redirectTo) . '">'
. '<button type="submit">' . esc_html($label) . '</button></form>';
}
// ── Age gate shortcode ───────────────────────────────────────────────────────
// [safepassage_age_gate]Restricted content[/safepassage_age_gate]
// Shows the content to verified users and a button to everyone else. Viewing a
// page never creates a verification session; clicking the button does.
add_shortcode('safepassage_age_gate', function ($atts, $content = '') {
if (safepassage_is_verified()) {
return do_shortcode((string) $content);
}
$here = set_url_scheme('http://' . ($_SERVER['HTTP_HOST'] ?? '') . wp_unslash($_SERVER['REQUEST_URI'] ?? '/'));
return '<div class="safepassage-age-gate"><p>' . esc_html__('You must verify your age to view this content.') . '</p>'
. safepassage_start_form(__('Verify my age'), $here) . '</div>';
});
// ── Create a session (or reuse an unfinished one) and send the user ─────────
add_action('admin_post_safepassage_verify_start', 'safepassage_verify_start');
add_action('admin_post_nopriv_safepassage_verify_start', 'safepassage_verify_start');
function safepassage_verify_start(): void {
$redirectTo = wp_validate_redirect(wp_unslash($_POST['redirect_to'] ?? ''), home_url('/'));
$subject = safepassage_subject(true);
$state = safepassage_get_state($subject);
if (!empty($state['verifiedSessionId'])) {
wp_safe_redirect($redirectTo, 303);
exit;
}
// Reuse the unfinished session instead of creating a new one per click.
$pending = $state['pending'] ?? null;
if ($pending && time() < $pending['expiresAt'] - 60) {
[$status, $body] = safepassage_api('/sessions/validate', ['sessionId' => $pending['sessionId']]);
if ($status === 200 && ($body['status'] ?? '') === 'pending') {
wp_redirect($pending['verifyUrl'], 303); // SafePassage's hosted page
exit;
}
if ($status === 0 || $status >= 500) {
// API unreachable: answer now rather than wait for a second request to time out.
safepassage_message(__('Verification is unavailable'), '<p>' . esc_html__('Please try again in a few minutes.') . '</p>', 503);
}
}
// No verificationMode or challengeAge: the session uses your Dashboard settings.
[$status, $body] = safepassage_api('/sessions/create', [
'returnUrl' => admin_url('admin-post.php?action=safepassage_verify_return'),
'externalUserId' => $subject,
]);
if ($status < 200 || $status >= 300 || empty($body['verifyUrl'])) {
error_log('SafePassage session creation failed: ' . $status . ' ' . ($body['code'] ?? wp_json_encode($body['message'] ?? '')));
safepassage_message(__('Verification is unavailable'), '<p>' . esc_html__('Please try again in a few minutes.') . '</p>', 503);
}
$state['pending'] = [
'sessionId' => $body['sessionId'],
'verifyUrl' => $body['verifyUrl'],
'expiresAt' => strtotime($body['expiresAt']),
'redirectTo' => $redirectTo,
];
safepassage_set_state($subject, $state);
wp_redirect($body['verifyUrl'], 303);
exit;
}
// ── Confirm the result when the user returns, before granting access ──────
add_action('admin_post_safepassage_verify_return', 'safepassage_verify_return');
add_action('admin_post_nopriv_safepassage_verify_return', 'safepassage_verify_return');
function safepassage_verify_return(): void {
$subject = safepassage_subject();
$state = $subject ? safepassage_get_state($subject) : [];
$pending = $state['pending'] ?? null;
if (!empty($state['verifiedSessionId']) || !$pending) {
wp_safe_redirect($pending['redirectTo'] ?? home_url('/'), 303);
exit;
}
// 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 = sanitize_text_field(wp_unslash($_GET['sessionId'] ?? $pending['sessionId']));
if (!hash_equals($pending['sessionId'], $sessionId)) {
safepassage_message(__('We could not match this verification'), safepassage_start_form(__('Start again'), $pending['redirectTo']), 400);
}
[$status, $body] = safepassage_api('/sessions/validate', ['sessionId' => $sessionId]);
$checkAgain = '<p><a href="' . esc_url(add_query_arg('sessionId', $sessionId, admin_url('admin-post.php?action=safepassage_verify_return'))) . '">' . esc_html__('Check again') . '</a></p>';
if ($status === 200 && ($body['accessGranted'] ?? false) === true && ($body['externalUserId'] ?? null) === $subject) {
$state['verifiedSessionId'] = $sessionId;
unset($state['pending']);
safepassage_set_state($subject, $state);
wp_safe_redirect($pending['redirectTo'], 303);
exit;
}
if ($status === 200 && ($body['status'] ?? '') === 'pending') {
// Not finished: the user left early, or the result is a few seconds away.
safepassage_message(__('Your verification is not finished'), '<p>' . esc_html__('If you have just finished, wait a moment and check again.') . '</p>'
. safepassage_start_form(__('Continue verification'), $pending['redirectTo']) . $checkAgain);
}
if ($status === 200 || $status === 400) {
// cancelled, failed, or 400 "Session has expired": offer a new attempt.
unset($state['pending']);
safepassage_set_state($subject, $state);
$title = ($body['status'] ?? '') === 'cancelled' ? __('Verification cancelled') : __('Verification not completed');
safepassage_message($title, '<p>' . esc_html__('You can try again. Use a valid photo ID in good light if asked.') . '</p>'
. safepassage_start_form(__('Try again'), $pending['redirectTo']));
}
// 401, 404, 429, 5xx or no response: a configuration or temporary problem.
error_log('SafePassage session validation failed: ' . $status . ' ' . wp_json_encode($body['message'] ?? ''));
safepassage_message(__('We could not confirm your verification'), '<p>' . esc_html__('Please try again shortly.') . '</p>' . $checkAgain, 502);
}
// ── Webhooks ─────────────────────────────────────────────────────────────────
// Endpoint URL for the Dashboard: https://your-site.example/wp-json/safepassage/v1/webhook
add_action('rest_api_init', function () {
register_rest_route('safepassage/v1', '/webhook', [
'methods' => 'POST',
'callback' => 'safepassage_webhook',
'permission_callback' => '__return_true', // authenticated by the signature below
]);
});
function safepassage_webhook(WP_REST_Request $request): WP_REST_Response {
$secret = defined('SAFEPASSAGE_WEBHOOK_SECRET') ? (string) constant('SAFEPASSAGE_WEBHOOK_SECRET') : '';
$rawBody = $request->get_body(); // the exact bytes that were signed
$signature = (string) $request->get_header('x-safepassage-signature');
$expected = 'sha256=' . hash_hmac('sha256', $rawBody, $secret);
if ($secret === '' || $signature === '' || !hash_equals($expected, $signature)) {
// Missing or wrong signature: reject without changing anything.
return new WP_REST_Response(['error' => 'invalid signature'], 401);
}
$event = json_decode($rawBody, true);
$data = $event['data'] ?? [];
$subject = (string) ($data['externalUserId'] ?? '');
if (!empty($event['test'])) {
error_log('SafePassage test webhook received: ' . ($event['event'] ?? '')); // never changes access
} elseif (($event['event'] ?? '') === 'verification.completed' && ($data['verified'] ?? false) === true
&& preg_match('/^(wp-user-\d+|visitor-[a-f0-9]{40})$/', $subject)) {
// Recording the same verified session twice is harmless, so retries are safe.
$state = safepassage_get_state($subject);
$state['verifiedSessionId'] = $data['sessionId'];
if (($state['pending']['sessionId'] ?? null) === $data['sessionId']) {
unset($state['pending']);
}
safepassage_set_state($subject, $state);
}
return new WP_REST_Response(['received' => true], 200);
}
- In WordPress, open Plugins → Must-Use. You should see "SafePassage age verification (site code)". If you see an error page instead, the file was not copied completely; paste it again.
Step 4: Protect your content
Wrap restricted content in the shortcode, in the block editor's Shortcode block or the classic editor:
[safepassage_age_gate]
This content is only shown to verified visitors.
[/safepassage_age_gate]
In a theme or plugin template, use the helper:
<?php if (safepassage_is_verified()) : ?>
<?php the_content(); ?>
<?php else : ?>
<?php echo do_shortcode('[safepassage_age_gate][/safepassage_age_gate]'); // shows the button ?>
<?php endif; ?>
To require verification before a WooCommerce checkout, add this to the same code file, and put the shortcode on your cart page so customers can verify first:
add_action('woocommerce_after_checkout_validation', function ($data, $errors) {
if (!safepassage_is_verified()) {
$errors->add('safepassage_age', __('Please verify your age before checking out.'));
}
}, 10, 2);
Caching plugins and hosts can store one visitor's page and show it to others.
If a page containing the gate is cached after a verified visitor views it,
unverified visitors may see the restricted content. Exclude gated pages from
full-page caching, or configure your cache to bypass pages for browsers that
have the safepassage_visitor cookie or are signed in. Check your cache
plugin's "never cache these URLs" or "cookie exclusions" settings.
Step 5: Check that it works
Use a private browser window, so you start as a new visitor.
-
Open a page with the gate. You should see the message and a Verify my age button, not the content.
-
Click the button. You should see the SafePassage verification page. Use your own face and ID. While your account is in its free sandbox, nothing is charged; see Test your integration.
-
Complete the verification. You should return to the same page, now showing the content.
-
In the Dashboard, open Configuration → Webhooks and click Test on your endpoint. You should see a success result. That is enough to know webhooks work. (Optional, for developers: with
WP_DEBUG_LOGenabled,wp-content/debug.logcontainsSafePassage test webhook received.) -
Optional, for developers or your host: check that requests without a valid signature are refused. From a terminal, send an unsigned request. You should see
401, and nothing changes on the site:curl -i -X POST https://your-site.example/wp-json/safepassage/v1/webhook \-H 'Content-Type: application/json' -d '{"event":"verification.completed"}'
Then work through the other journeys in Test your integration and the go-live checklist.
WordPress troubleshooting
| What you see | Likely cause and fix |
|---|---|
| "Verification is unavailable" after clicking the button | Session creation failed. With WP_DEBUG_LOG on, the log shows the HTTP status and code. 401: check the secret key in wp-config.php. 400 Return URL domain not allowed: add your domain under Configuration → Domains. 403 with a code: see plan and billing limits. |
| The SafePassage page says verification is blocked | Your account has reached its sandbox, plan or subscription limit. See Troubleshooting. |
| "Your verification is not finished" after returning | The visitor left before finishing, or returned a few seconds early. Continue verification resumes the same session; Check again re-checks the result. |
| Back on the page but the content is still hidden | A cached copy of the page is being shown, or cookies are blocked. Exclude the page from caching and try again. |
| Webhook Test fails with 404 | Pretty permalinks are off, or the code file is not in mu-plugins. Open https://your-site.example/wp-json/ to confirm the REST API responds. |
| Webhook Test fails with 401 | The signing secret in wp-config.php does not match the endpoint. Regenerate the secret in the Dashboard and update wp-config.php. |
| Webhook Test fails with 403 or a challenge page | A security plugin or firewall blocks the request. Allow POST requests to /wp-json/safepassage/v1/webhook. |
More symptoms are covered in Troubleshooting.
Developer handoff
If someone else will do the work, send them this page and:
- your site's address, and which pages or products need age verification;
- the verification mode and challenge age you have chosen;
- Admin access to the SafePassage Dashboard, or the secret key and webhook signing secret through a password manager (never by email or chat);
- this request: "Install the code file from the SafePassage WordPress guide, protect these pages with the age-gate shortcode, exclude them from page caching, and complete the checks in Step 5 and the go-live checklist."
Developers using another approach can follow the general Server integration guide; the same rules apply.