'webfon_sanitize_exclude']);
register_setting('webfon_widget', 'webfon_events', ['type' => 'array', 'default' => [], 'sanitize_callback' => 'webfon_sanitize_events']);
register_setting('webfon_advanced', 'webfon_provider_id', ['sanitize_callback' => 'webfon_sanitize_provider_id']);
register_setting('webfon_advanced', 'webfon_secret_key', ['sanitize_callback' => 'sanitize_text_field']);
register_setting('webfon_advanced', 'webfon_api_url', ['sanitize_callback' => 'webfon_sanitize_api_url']);
// Its field shows with WooCommerce alone; registered without it, saving the page would clear it.
if (class_exists('WooCommerce')) {
register_setting('webfon_advanced', 'webfon_tool_secret', ['sanitize_callback' => 'webfon_sanitize_tool_secret']);
}
});
/** The settings page's tab: connection (the default), widget or advanced. */
function webfon_tab(): string
{
$tab = sanitize_key(wp_unslash($_GET['tab'] ?? '')); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
return in_array($tab, ['widget', 'advanced'], true) ? $tab : 'connection';
}
add_filter('plugin_action_links_' . plugin_basename(__FILE__), function ($links) {
return ['settings' => '' . esc_html__('Settings', 'webfon') . ''] + $links;
});
// The AI agent's tools on a WooCommerce store; they read its orders through WooCommerce's own API alone (HPOS).
add_action('plugins_loaded', function () {
if (class_exists('WooCommerce')) {
require __DIR__ . '/tools.php';
}
});
add_action('before_woocommerce_init', function () {
if (class_exists(\Automattic\WooCommerce\Utilities\FeaturesUtil::class)) {
\Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility('custom_order_tables', __FILE__, true);
\Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility('cart_checkout_blocks', __FILE__, true);
}
});
function webfon_sanitize_provider_id($value)
{
$value = trim((string) $value);
if ('' === $value || wp_is_uuid($value)) {
return $value;
}
add_settings_error('webfon_provider_id', 'invalid', __('The Provider ID is a UUID: copy it from the Webfon panel.', 'webfon'));
return get_option('webfon_provider_id', '');
}
/** An http(s) address, kept without the trailing slash: the widget appends /v1/… to it. */
function webfon_sanitize_api_url($value)
{
$value = untrailingslashit(trim((string) $value));
$url = wp_parse_url($value);
if ('' === $value || (in_array($url['scheme'] ?? '', ['http', 'https'], true) && !empty($url['host']))) {
return esc_url_raw($value);
}
add_settings_error('webfon_api_url', 'invalid', __('The API URL is an http(s) address, such as https://api.webfon.io.', 'webfon'));
return get_option('webfon_api_url', '');
}
/** The AI agent's signing secret as the Webfon panel shows it: whsec_ and the key in base64. */
function webfon_sanitize_tool_secret($value)
{
$value = trim((string) $value);
if ('' === $value || (0 === strpos($value, 'whsec_') && base64_decode(substr($value, 6), true))) {
return $value;
}
add_settings_error('webfon_tool_secret', 'invalid', __('The signing secret starts with whsec_: copy it from the Webfon panel.', 'webfon'));
return get_option('webfon_tool_secret', '');
}
/** The widget's events (docs.webfon.io guide/events): their WebfonConfig key, and when they fire with what `event` holds. */
function webfon_events()
{
return [
'open' => ['onOpen', __('The widget opens. Carries nothing.', 'webfon')],
'close' => ['onClose', __('The widget closes. Carries nothing.', 'webfon')],
'conversation_started' => ['onConversationStarted', __('The visitor\'s message starts a conversation: event.conversation_id.', 'webfon')],
'call_answered' => ['onCallAnswered', __('A call connects: event.call_id, and event.initiator, customer (the visitor called) or agent.', 'webfon')],
'call_ended' => ['onCallEnded', __('A connected call ends: event.call_id, event.initiator and event.duration, in seconds.', 'webfon')],
'message' => ['onMessage', __('A message arrives from your team or your AI agent: event.content, event.sender_type (agent, ai_agent or system) and more.', 'webfon')],
'login' => ['onLogin', __('A visitor signs in inside the widget, with a social account or a code: event.method (google, phone, email…). A user your site signs in fires none.', 'webfon')],
'logout' => ['onLogout', __('The member signs out in the widget. Carries nothing.', 'webfon')],
];
}
/**
* Ready code for analytics tools, a line for each event worth counting, for a tool already on the site. Not message:
* its content is the visitor's chat.
*/
function webfon_event_presets()
{
$tools = [
'Google Tag Manager' => "(window.dataLayer = window.dataLayer || []).push(Object.assign({event: 'webfon_%s'}, event));",
'Google Analytics' => "if (window.gtag) gtag('event', 'webfon_%s', event || {});",
'Meta Pixel' => "if (window.fbq) fbq('trackCustom', 'webfon_%s', event || {});",
'Matomo' => "(window._paq = window._paq || []).push(['trackEvent', 'Webfon', '%s']);",
'Plausible' => "if (window.plausible) plausible('webfon_%s', {props: event || {}});",
];
$presets = [];
foreach ($tools as $tool => $line) {
foreach (['open', 'conversation_started', 'call_answered', 'call_ended', 'login'] as $event) {
$presets[$tool][$event] = sprintf($line, $event);
}
}
return $presets;
}
/** Each event's JavaScript, saved only by a user who may put scripts on the site (unfiltered_html: not a multisite's site admins). */
function webfon_sanitize_events($value)
{
if (!current_user_can('unfiltered_html')) {
return get_option('webfon_events', []);
}
$value = is_array($value) ? $value : [];
$events = [];
foreach (array_keys(webfon_events()) as $event) {
$code = trim((string) ($value[$event] ?? ''));
if ('' !== $code) {
$events[$event] = $code;
}
}
return $events;
}
/** One path per line; a pasted address keeps only its path. */
function webfon_sanitize_exclude($value)
{
$paths = [];
foreach (preg_split('/\R/', (string) $value) as $line) {
if ('' !== trim($line)) {
$paths[] = webfon_path(trim($line));
}
}
return implode("\n", array_unique($paths));
}
/** An address's path, decoded (/ürün, not /%C3%BCr%C3%BCn): what the exclusion list holds and compares. */
function webfon_path($url)
{
return '/' . ltrim(sanitize_text_field(rawurldecode((string) wp_parse_url($url, PHP_URL_PATH))), '/');
}
/** Whether this page is on the exclusion list: * matches anything, a trailing slash is ignored. */
function webfon_excluded()
{
// esc_url_raw, not sanitize_text_field: that strips %XX, so /%C3%BCr%C3%BCn would no longer be /ürün.
$path = untrailingslashit(webfon_path(esc_url_raw(wp_unslash($_SERVER['REQUEST_URI'] ?? ''))));
foreach (array_filter(explode("\n", (string) get_option('webfon_exclude'))) as $pattern) {
$pattern = untrailingslashit($pattern);
if (fnmatch($pattern, $path) || fnmatch($pattern, $path . '/')) {
return true;
}
}
return false;
}
add_action('admin_menu', function () {
add_options_page('Webfon', 'Webfon', 'manage_options', 'webfon', 'webfon_settings_page');
});
add_action('admin_enqueue_scripts', function ($hook) {
if ('settings_page_webfon' !== $hook) {
return;
}
wp_enqueue_style('webfon-admin', plugins_url('admin.css', __FILE__), [], (string) filemtime(__DIR__ . '/admin.css'));
// Reconnect's call under the connection card: a tool ticked or unticked here and not yet sent, beside what the page
// found (data-stale: Webfon changed; data-drift: the tools moved on since the last connection).
if ('connection' === webfon_tab() && class_exists('WooCommerce')) {
wp_register_script('webfon-sync', false, [], null, true);
wp_enqueue_script('webfon-sync');
wp_add_inline_script('webfon-sync', <<<'JS'
(function () {
var form = document.getElementById('webfon-connect'), notice = form && form.querySelector('.webfon-sync');
if (!notice) return;
var tools = notice.querySelector('[data-tools]'), button = form.querySelector('[type=submit]');
form.addEventListener('change', function () {
var dirty = [].some.call(form.querySelectorAll('[name="webfon_tools[]"]'), function (box) { return box.checked !== box.defaultChecked; });
var due = dirty || !!notice.dataset.drift;
tools.hidden = !due;
notice.hidden = !(due || notice.dataset.stale);
button.classList.toggle('button-primary', due || !!notice.dataset.stale);
});
})();
JS
);
}
if ('widget' !== webfon_tab() || !current_user_can('unfiltered_html')) {
return;
}
// The events' boxes in WordPress's code editor, plain ones for a user who turned syntax highlighting off. No lint:
// its rules (single quotes, braces, every global declared) would flag the presets' own lines.
$editor = wp_enqueue_code_editor(['type' => 'text/javascript', 'codemirror' => ['lint' => false, 'gutters' => [], 'styleActiveLine' => false]]);
wp_register_script('webfon-events', false, $editor ? ['code-editor'] : [], null, true);
wp_enqueue_script('webfon-events');
wp_add_inline_script('webfon-events', sprintf(<<<'JS'
(function (settings) {
var card = document.querySelector('.webfon-events'), boxes = {};
if (!card) return;
var presets = card.querySelectorAll('[data-tool]');
// A box's code as blocks a blank line apart; a preset's block starts with the comment "// ".
function blocks(event) {
return boxes[event].get().split(/\n\s*\n/).map(function (block) { return block.trim(); }).filter(Boolean);
}
function isTool(block, tool) { return block.split('\n')[0].trim() === '// ' + tool; }
function lines(button) { return JSON.parse(button.dataset.lines); }
function isOn(button) {
return Object.keys(lines(button)).some(function (event) {
return blocks(event).some(function (block) { return isTool(block, button.dataset.tool); });
});
}
function refresh() { presets.forEach(function (button) { button.setAttribute('aria-pressed', isOn(button)); }); }
card.querySelectorAll('textarea[data-event]').forEach(function (box) {
var editor = settings && wp.codeEditor.initialize(box, settings).codemirror;
boxes[box.dataset.event] = {
get: function () { return editor ? editor.getValue() : box.value; },
set: function (value) { if (editor) { editor.setValue(value); } else { box.value = value; } }
};
if (editor) {
editor.on('change', refresh);
} else {
box.addEventListener('input', refresh);
}
});
// A preset adds its tool's block to its events' boxes, under their code; pressed again it takes it out of them.
card.querySelector('.webfon-presets').addEventListener('click', function (e) {
var button = e.target.closest('button');
if (button && button.hasAttribute('data-clear')) Object.keys(boxes).forEach(function (event) { boxes[event].set(''); });
if (button && button.dataset.tool) {
var tool = button.dataset.tool, on = isOn(button), code = lines(button);
Object.keys(code).forEach(function (event) {
var kept = blocks(event).filter(function (block) { return !isTool(block, tool); });
boxes[event].set(kept.concat(on ? [] : ['// ' + tool + '\n' + code[event]]).join('\n\n'));
});
}
refresh();
});
refresh();
})(%s);
JS
, wp_json_encode($editor ?: null)));
});
function webfon_panel_url()
{
return untrailingslashit(apply_filters('webfon_panel_url', 'https://panel.webfon.io'));
}
/**
* The panel's Kurulum page for this site: its address and this settings page to come back to; with WooCommerce, the
* ticked AI agent tools (webfon_tools_sent()) as the base64url of their JSON in the fragment, which reaches no server,
* so its length meets no server's limit.
*/
function webfon_connect_url()
{
$url = webfon_panel_url() . '/client/connect?' . http_build_query([
'site' => home_url('/'),
'return' => admin_url('options-general.php?page=webfon'),
'state' => wp_create_nonce('webfon_connect'),
]);
$fragment = webfon_connect_fragment();
return $fragment ? $url . '#' . http_build_query($fragment) : $url;
}
/** With WooCommerce, every tool: the ticked ones to put on the AI agent, the others' names for the panel to take off it. */
function webfon_connect_fragment(): array
{
if (!class_exists('WooCommerce')) {
return [];
}
$tools = webfon_tools_sent();
return array_filter([
'tools' => $tools ? rtrim(strtr(base64_encode(wp_json_encode($tools, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)), '+/', '-_'), '=') : '',
'remove' => implode(',', array_diff(array_column(webfon_tools(), 'name'), webfon_tools_ticked())),
]);
}
/** The fragment's MD5: kept as webfon_tools_synced when a code comes back, so the page tells when the tools moved on. */
function webfon_connect_fragment_hash(): string
{
return md5(http_build_query(webfon_connect_fragment()));
}
// Connect and Reconnect: the AI agent tools ticked are kept (their routes alone answer), then the panel opens with them.
// By the page, not a Location header: with the tools the address runs past 10 KB, past nginx's default FastCGI buffer.
add_action('admin_post_webfon_connect', function () {
if (!current_user_can('manage_options')) {
wp_die(esc_html__('You cannot connect this site to Webfon.', 'webfon'), 403);
}
check_admin_referer('webfon_connect_tools', 'webfon_connect_nonce');
if (class_exists('WooCommerce')) {
$ticked = array_map('sanitize_key', (array) wp_unslash($_POST['webfon_tools'] ?? []));
update_option('webfon_tools', array_values(array_intersect(array_column(webfon_tools(), 'name'), $ticked)));
}
nocache_headers();
printf(
'Webfon
',
esc_url(webfon_connect_url()),
esc_html__('Continue to the Webfon panel', 'webfon')
);
exit;
});
/**
* Kurulum's code, from the panel: wfn_ and the base64url of a JSON object, the provider (`pid`), its secret key (`sk`),
* the AI agent's signing secret when the agent took this site's tools (`ts`) and the API's address (`api`, kept empty
* when it is the widget's own default).
*/
function webfon_apply_code(string $code): bool
{
$data = 0 === strpos($code, 'wfn_') ? json_decode((string) base64_decode(strtr(substr($code, 4), '-_', '+/')), true) : null;
if (!is_array($data) || !wp_is_uuid((string) ($data['pid'] ?? ''))) {
return false;
}
update_option('webfon_provider_id', $data['pid']);
update_option('webfon_secret_key', sanitize_text_field((string) ($data['sk'] ?? '')));
// The widget's AI agent's signing secret: an empty one when it has none (the one held goes), none when the panel's
// user may not see it (the one held stays).
if (array_key_exists('ts', $data)) {
'' === (string) $data['ts'] ? delete_option('webfon_tool_secret') : update_option('webfon_tool_secret', sanitize_text_field((string) $data['ts']));
}
$api = untrailingslashit(esc_url_raw((string) ($data['api'] ?? '')));
update_option('webfon_api_url', 'https://api.webfon.io' === $api ? '' : $api);
return true;
}
// The code back from the panel (its return, GET) or pasted (POST), on this page alone; the state is the Kurulum
// button's nonce, so no link another sends connects the site to their provider. Redirected so the code leaves the
// address: to the page alone when taken (the card shows the connection), with a notice when not.
add_action('admin_init', function () {
if ('webfon' !== sanitize_key(wp_unslash($_GET['page'] ?? '')) || !isset($_REQUEST['webfon_code']) || !current_user_can('manage_options')) {
return;
}
$state = sanitize_text_field(wp_unslash($_REQUEST['state'] ?? ''));
$done = wp_verify_nonce($state, 'webfon_connect') && webfon_apply_code(sanitize_text_field(wp_unslash($_REQUEST['webfon_code'])));
if ($done) {
update_option('webfon_tools_synced', webfon_connect_fragment_hash(), false);
}
wp_safe_redirect(admin_url('options-general.php?page=webfon' . ($done ? '' : '&webfon_connected=0')));
exit;
}, 20);
// Disconnect: the connection's values go (the widget, custom login and the AI agent's tools with them); Hide on pages
// is the site's own and stays for a reconnect.
add_action('admin_init', function () {
if ('webfon' !== sanitize_key(wp_unslash($_GET['page'] ?? '')) || !isset($_POST['webfon_disconnect']) || !current_user_can('manage_options')) {
return;
}
check_admin_referer('webfon_disconnect', 'webfon_disconnect');
foreach (['webfon_provider_id', 'webfon_secret_key', 'webfon_tool_secret', 'webfon_api_url', 'webfon_tools_synced'] as $option) {
delete_option($option);
}
wp_safe_redirect(admin_url('options-general.php?page=webfon&webfon_connected=off'));
exit;
}, 20);
/**
* Whether the connection is still Webfon's, asked on each visit of the settings page: the provider, and the secret key
* and signing secret held, sent as their SHA-256 alone. False: Webfon has no active provider of that ID. Null: Webfon did
* not answer. Else ['name' => the provider's, 'secret_key' => current, 'agent' => the widget has an AI agent,
* 'tool_secret' => current].
*/
function webfon_connection()
{
$hash = fn($option) => '' === ($value = (string) get_option($option, '')) ? '' : hash('sha256', $value);
$response = wp_remote_post((get_option('webfon_api_url') ?: 'https://api.webfon.io') . '/v1/public/provider/' . rawurlencode((string) get_option('webfon_provider_id')) . '/connection', [
'timeout' => 5,
'headers' => ['Content-Type' => 'application/json'],
'body' => wp_json_encode(['sk' => $hash('webfon_secret_key'), 'ts' => $hash('webfon_tool_secret')]),
]);
$status = wp_remote_retrieve_response_code($response);
if (404 === $status) {
return false;
}
$data = 200 === $status ? (json_decode(wp_remote_retrieve_body($response), true)['data'] ?? null) : null;
return is_array($data) ? $data : null;
}
/** A line of the connection card: what works on the site, and how. $text is HTML, a link at most; a $wide line takes the row. */
function webfon_check(string $state, string $title, string $text, bool $wide = false)
{
printf(
'
%3$s%4$s
',
esc_attr($state),
esc_attr(['on' => 'yes-alt', 'off' => 'remove', 'warning' => 'warning'][$state]),
esc_html($title),
wp_kses($text, ['a' => ['href' => [], 'target' => [], 'rel' => []]]),
$wide ? ' is-wide' : ''
);
}
/** Connect's and Reconnect's form: with WooCommerce, the AI agent tools it sends, ticked as last kept; the Gravatar box. */
function webfon_connect_fields()
{
echo '';
wp_nonce_field('webfon_connect_tools', 'webfon_connect_nonce');
if (class_exists('WooCommerce')) {
webfon_tools_fields();
}
// Saved as it is ticked (wp_ajax_webfon_gravatar): it never goes to the Webfon panel, so it waits for no Connect.
?>
['error', __('The connection code was not taken: connect again, or paste the code the Webfon panel shows.', 'webfon')],
'off' => ['success', __('Disconnected from Webfon: the widget is off the site.', 'webfon')],
][$connected] ?? null;
?>
Webfon
' . esc_html__('View site', 'webfon') . '');
if (!get_option('webfon_secret_key')) {
webfon_check('off', __('Signed-in users', 'webfon'), esc_html__('Chat as anonymous visitors: no secret key is set.', 'webfon'));
} elseif (is_array($check) && !$check['secret_key']) {
$stale = true;
webfon_check('warning', __('Signed-in users', 'webfon'), esc_html__('The provider\'s secret key changed in Webfon: signed-in users cannot chat as themselves until you reconnect.', 'webfon'));
} else {
webfon_check('on', __('Signed-in users', 'webfon'), esc_html__('Chat as themselves: their name, email and profile go to Webfon.', 'webfon'));
}
if (class_exists('WooCommerce')) {
if (!get_option('webfon_tool_secret') && is_array($check) && $check['agent']) {
$stale = true;
webfon_check('warning', __('AI agent', 'webfon'), esc_html__('This site\'s provider has an AI agent now: reconnect to link it.', 'webfon'));
} elseif (!get_option('webfon_tool_secret')) {
webfon_check('off', __('AI agent', 'webfon'), esc_html__('Not linked. Reconnect once this site\'s provider has an AI agent in the Webfon panel.', 'webfon'));
} elseif (is_array($check) && !$check['tool_secret']) {
$stale = true;
webfon_check('warning', __('AI agent', 'webfon'), $check['agent']
? esc_html__('The provider\'s AI agent or its signing secret changed in Webfon: its calls are refused until you reconnect.', 'webfon')
: esc_html__('This site\'s provider has no AI agent any more: reconnect.', 'webfon'));
} else {
webfon_check('on', __('AI agent', 'webfon'), esc_html__('Answers with the tools ticked below; reconnect after changing them.', 'webfon'));
}
}
?>
$provider_id, 'apiUrl' => get_option('webfon_api_url')])) . ";\n";
// Signed-out pages get no getToken: the widget then drops a member token it cached, so a sign-out
// shows on the next page.
if (get_option('webfon_secret_key') && is_user_logged_in()) {
$config .= sprintf(
<<<'JS'
WebfonConfig.getToken = async ({jkt}) => {
const res = await fetch(%s, {
method: 'POST',
headers: {'Content-Type': 'application/json', 'X-WP-Nonce': %s},
body: JSON.stringify({jkt}),
});
if (res.status >= 500) throw new Error('webfon token: ' + res.status); // a failure, not a sign-out
return res.ok ? (await res.json()).token : null;
};
JS,
wp_json_encode(rest_url('webfon/v1/token')),
wp_json_encode(wp_create_nonce('wp_rest'))
);
}
// The config, then each event's code, each a script of its own, all before sdk.js, which reads WebfonConfig's
// callbacks once at its start: a mistake in one event's code stops that script alone.
wp_register_script('webfon-config', false, [], null);
wp_add_inline_script('webfon-config', $config);
$deps = ['webfon-config'];
$events = (array) get_option('webfon_events', []);
foreach (webfon_events() as $event => [$key]) {
if ('' !== (string) ($events[$event] ?? '')) {
$handle = 'webfon-on-' . str_replace('_', '-', $event);
wp_register_script($handle, false, ['webfon-config'], null);
// would end the tag early; <\/script> is the same text inside a JS string.
wp_add_inline_script($handle, "WebfonConfig.$key = function (event) {\n" . str_ireplace(' 'async']);
});
// The X-WP-Nonce above is what admits the user here: WordPress answers REST requests from any origin
// with credentials, and without the nonce it treats the request as signed out.
add_action('rest_api_init', function () {
register_rest_route('webfon/v1', '/token', [
'methods' => 'POST',
'callback' => 'webfon_token',
'permission_callback' => 'is_user_logged_in',
]);
});
/** The signed-in user as a Webfon member: the socket token the widget connects with (custom login). */
function webfon_token(WP_REST_Request $request)
{
$secret = (string) get_option('webfon_secret_key');
$jkt = (string) $request->get_param('jkt');
if ('' === $secret || !preg_match('/^[A-Za-z0-9_-]{43}$/', $jkt)) {
return new WP_Error('webfon_bad_request', 'Bad request', ['status' => 400]);
}
$user = wp_get_current_user();
$now = time();
$claims = array_filter([
'pid' => get_option('webfon_provider_id'),
'uid' => (string) $user->ID, // the AI agent's tools find the user by it ({external_id})
'type' => 'user',
'cnf' => ['jkt' => $jkt],
'name' => $user->display_name ?: $user->user_login,
'email' => $user->user_email,
'phone' => get_user_meta($user->ID, 'billing_phone', true), // WooCommerce; Webfon keeps only + numbers
'avatar' => webfon_avatar($user->ID),
'language' => explode('_', get_user_locale($user))[0],
'iat' => $now,
'exp' => $now + 2 * HOUR_IN_SECONDS,
]);
return ['token' => webfon_jwt($claims, $secret)];
}
/**
* The user's avatar, or null when Gravatar has none: WordPress's address always draws a placeholder. None while the
* site shows no avatars (Settings → Discussion), nor from Gravatar until the owner turns Gravatar photos on
* under Settings → Webfon. Gravatar's answer is kept a day in the user's meta, as the token is asked for on every page.
*/
function webfon_avatar(int $user_id): ?string
{
if (!get_option('show_avatars')) {
return null;
}
$url = get_avatar_url($user_id, ['default' => '404', 'scheme' => 'https']);
if (!$url || false === strpos($url, 'gravatar.com/')) {
return $url ?: null; // a local-avatar plugin's own file
}
if (!get_option('webfon_gravatar')) {
return null;
}
$seen = get_user_meta($user_id, 'webfon_avatar', true);
if (!is_array($seen) || $seen['url'] !== $url || $seen['at'] < time() - DAY_IN_SECONDS) {
$found = 200 === wp_remote_retrieve_response_code(wp_remote_head($url, ['timeout' => 3]));
$seen = ['url' => $url, 'found' => $found, 'at' => time()];
update_user_meta($user_id, 'webfon_avatar', $seen);
}
return $seen['found'] ? $url : null;
}
/** HS256 JWT. */
function webfon_jwt(array $claims, string $secret): string
{
$b64 = fn(string $data): string => rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
$unsigned = $b64('{"alg":"HS256","typ":"JWT"}') . '.' . $b64(wp_json_encode($claims));
return $unsigned . '.' . $b64(hash_hmac('sha256', $unsigned, $secret, true));
}