Skip to main content

WordPress

The easy way: a header/footer plugin​

  1. Install a plugin that adds code to the footer, such as WPCode (previously "Insert Headers and Footers").
  2. In its Footer box, paste your snippet from Widget & SDK:
<script src="https://api.mysarthi.tech/widget/v1.js" data-site-key="ws_acme_7f3a9c" async></script>
  1. Save, open your site in a private window, and click the bubble.

Remember to add your site's address (https://yoursite.com, and https://www.yoursite.com if you serve both) under Allowed websites in the console.

Without a plugin: a child theme​

If you maintain a child theme, hook the script into wp_footer:

functions.php
add_action('wp_footer', function () {
echo '<script src="https://api.mysarthi.tech/widget/v1.js" data-site-key="ws_acme_7f3a9c" async></script>';
});

WooCommerce: signed-in customers​

A logged-in WooCommerce customer can be recognised, so Sarthi can answer about their orders. Your site signs a short token for them; the widget asks for it. Add a tiny REST route and a different snippet:

functions.php
// 1. A route that returns a fresh token for the logged-in user.
add_action('rest_api_init', function () {
register_rest_route('saarthi/v1', '/token', [
'methods' => 'GET',
'permission_callback' => 'is_user_logged_in',
'callback' => function () {
$user = wp_get_current_user();
$now = time();
$b64 = fn($s) => rtrim(strtr(base64_encode($s), '+/', '-_'), '=');
$header = $b64(json_encode(['alg' => 'HS256', 'typ' => 'JWT']));
$payload = $b64(json_encode([
'user_id' => (string) $user->ID,
'name' => $user->display_name,
'email' => $user->user_email,
'iat' => $now,
'exp' => $now + 900, // 15 minutes, the maximum
'nonce' => $b64(random_bytes(24)),
]));
$secret = getenv('SARTHI_SDK_SECRET'); // sk_live_… from Widget & SDK, never in a page
$sig = $b64(hash_hmac('sha256', "$header.$payload", $secret, true));
return ['token' => "$header.$payload.$sig"];
},
]);
});

// 2. The snippet: no data-site-key; logged-in visitors get a token, others chat anonymously.
add_action('wp_footer', function () {
$init = is_user_logged_in()
? "{ siteKey: 'ws_acme_7f3a9c', getEndUserToken: () => fetch('/wp-json/saarthi/v1/token', { credentials: 'same-origin' }).then(r => r.json()).then(d => d.token) }"
: "{ siteKey: 'ws_acme_7f3a9c' }";
echo '<script src="https://api.mysarthi.tech/widget/v1.js" async></script>';
echo "<script>window.Sarthi = { q: [['init', $init]] };</script>";
});

Put the secret in wp-config.php with putenv('SARTHI_SDK_SECRET=sk_live_…'); or in your hosting panel's environment variables. The rules a token must follow are in Signing the token on your server.

Caching plugins​

WP Rocket, LiteSpeed Cache and similar may try to delay or combine scripts. The snippet is already async and needs nothing from them; if a plugin offers to "delay JavaScript until interaction", exclude widget/v1.js so the bubble shows on page load.