Identify signed-in customers in the web chat
Let the web chat know which customer signed in on your site: the conversation arrives linked to their record instead of as an anonymous visitor. Includes server examples for Node, Next.js, PHP, Python, WordPress, Rails and Laravel.
By default, whoever writes through the web chat is an anonymous visitor ("Visitor #1a2b"). If your site has customer accounts, you can tell the chat who they are: the conversation is linked to their customer record (by phone or email) and your team sees their name and details from the first message.
This guide is for whoever builds the site. First: install the web chat.
How it works (no jargon)
The customer's browser can't be trusted (anyone could type "I'm Ana"). That's why the identity is signed by your server, which does know who signed in:
Signed-in customer Your server Turnflow
─────────────────── ─────────────────── ───────────────────
1. opens a page ──────► 2. who is signed in?
3. signs "v1|phone|email|name|time"
with the SECRET (known only to
your server and Turnflow)
4. receives {name, email, ◄──
phone, time, signature}
5. writes in the chat ──────────────────────────────────────► 6. recomputes the signature
(the chat sends that data) with the same secret:
✔ matches and is recent
→ links to their record
✘ mismatch / expired
→ anonymous visitor
- The secret is a key known only to your server and Turnflow. It never goes in the browser, in the HTML, or in your site's JavaScript.
- If the signature is missing, forged or expired, the message still arrives: it just stays an anonymous visitor.
- Writing through the chat does not give marketing consent: a linked customer is not signed up for campaigns just for having written.
Step 1: generate the secret
- Go to Settings → General and scroll to Chat for signed-in customers.
- Click Generate secret and copy it right then: it is shown only once and stored encrypted.
- Keep it in your server's private variables (for example
TURNFLOW_CHAT_SECRET). If you lose it, generate a new one: the old one stops working and you must update it on your server.
Step 2: what is signed
Your server hands the browser these five values: name, email, phone, ts and sig.
ts: the current time in seconds (Unix time, UTC).sig: the hexadecimal result (64 characters) of HMAC-SHA256 with your secret over this exact text:
v1|<phone>|<email>|<name>|<ts>
Important rules:
- Sign exactly the same texts you send, letter by letter (
emailandnameas you send them, with capitals and accents). If you change anything after signing, the signature no longer matches. - If you don't have a value, use empty text (
v1||maria@mail.com|María|1700000000). There must be at least a valid phone or email. - UTF-8 text (the norm in all the languages below).
- The phone includes the country code. Turnflow strips everything that isn't a digit. A Colombian mobile of 10 digits starting with 3 (for example
3001112233) is completed with57automatically; any other number must carry its country code (573001112233,14155550123). It must end up between 8 and 15 digits. You can sign the number as you send it or already with the57; both work.
Step 3: how long the signature lasts
The signature is valid for 30 minutes from ts, backwards and forwards. Consequences:
- Your server clock must be correct (use NTP). A server more than 30 minutes ahead or behind makes every signature get rejected.
- Request the signature right when the page loads; don't cache it or leave it written in cached HTML.
- If the customer leaves the page open for over 30 minutes and writes again, that message arrives without a fresh identity, but the conversation that was already linked stays linked. For pages left open for hours, request the signature again every ~20 minutes and replace
window.TurnflowChat.identity.
Step 4: on the page
The chat reads window.TurnflowChat.identity every time the visitor sends a message. So it is enough to ask your server for the identity and store it there. Put this in your template, before or after the chat code:
<script>
window.TurnflowChat = window.TurnflowChat || {};
fetch('/turnflow-identity', { credentials: 'same-origin' })
.then(function (r) { return r.ok ? r.json() : null; })
.then(function (id) { if (id) window.TurnflowChat.identity = id; })
.catch(function () {});
</script>
<script src="https://app.turnflow.com.co/widget.js" data-brand="YOUR_KEY" async></script>
If the customer is not signed in, your server answers with an error (401/403) and the chat keeps working as an anonymous visitor.
Your endpoint must: require the customer's session, answer with
Cache-Control: no-storeand return JSON{ name, email, phone, ts, sig }. Never return the secret.
Server examples
In all of them, TURNFLOW_CHAT_SECRET is the secret from step 1, and user is the customer signed in to your system. The signature calculation in the Node, Python, PHP and Ruby examples was tested against Turnflow's verifier (including names with accents and 10-digit mobiles). The framework parts (routes, session) you must adapt to your project.
Node.js / Express
import crypto from "node:crypto";
export function turnflowIdentity(user, secret) {
const ts = Math.floor(Date.now() / 1000);
const phone = user.phone || "", email = user.email || "", name = user.name || "";
const sig = crypto.createHmac("sha256", secret)
.update(`v1|${phone}|${email}|${name}|${ts}`).digest("hex");
return { name, email, phone, ts, sig };
}
// requireLogin is your session middleware (for example Passport)
app.get("/turnflow-identity", requireLogin, (req, res) => {
res.set("Cache-Control", "no-store");
res.json(turnflowIdentity(req.user, process.env.TURNFLOW_CHAT_SECRET));
});
Next.js (route handler)
File app/turnflow-identity/route.ts. It uses the turnflowIdentity function above and your way of reading the session (getSession is an example: replace it with Auth.js, Clerk, your own cookie, etc.).
import { NextResponse } from "next/server";
import { turnflowIdentity } from "@/lib/turnflow"; // the function from the Node example
import { getSession } from "@/lib/auth"; // yours
export const dynamic = "force-dynamic";
export async function GET() {
const session = await getSession();
if (!session?.user) return new NextResponse(null, { status: 401 });
const { name, email, phone } = session.user;
return NextResponse.json(
turnflowIdentity({ name, email, phone }, process.env.TURNFLOW_CHAT_SECRET!),
{ headers: { "Cache-Control": "no-store" } },
);
}
PHP
<?php
function turnflow_identity(array $user, string $secret): array {
$ts = time();
$phone = $user['phone'] ?? ''; $email = $user['email'] ?? ''; $name = $user['name'] ?? '';
$sig = hash_hmac('sha256', "v1|$phone|$email|$name|$ts", $secret);
return ['name' => $name, 'email' => $email, 'phone' => $phone, 'ts' => $ts, 'sig' => $sig];
}
// turnflow-identity.php
session_start();
if (empty($_SESSION['user'])) { http_response_code(401); exit; }
header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store');
echo json_encode(turnflow_identity($_SESSION['user'], getenv('TURNFLOW_CHAT_SECRET')), JSON_UNESCAPED_UNICODE);
Python (Flask and FastAPI)
import hashlib, hmac, os, time
def turnflow_identity(user, secret):
ts = int(time.time())
phone, email, name = user.get("phone") or "", user.get("email") or "", user.get("name") or ""
sig = hmac.new(secret.encode(), f"v1|{phone}|{email}|{name}|{ts}".encode(), hashlib.sha256).hexdigest()
return {"name": name, "email": email, "phone": phone, "ts": ts, "sig": sig}
Flask (with Flask-Login):
from flask import jsonify
from flask_login import current_user, login_required
@app.get("/turnflow-identity")
@login_required
def turnflow_identity_route():
r = jsonify(turnflow_identity(
{"name": current_user.name, "email": current_user.email, "phone": current_user.phone},
os.environ["TURNFLOW_CHAT_SECRET"]))
r.headers["Cache-Control"] = "no-store"
return r
FastAPI (get_current_user is your session dependency):
from fastapi import Depends
from fastapi.responses import JSONResponse
@app.get("/turnflow-identity")
def turnflow_identity_route(user=Depends(get_current_user)):
return JSONResponse(
turnflow_identity({"name": user.name, "email": user.email, "phone": user.phone},
os.environ["TURNFLOW_CHAT_SECRET"]),
headers={"Cache-Control": "no-store"})
WordPress (functions.php)
Keep the secret in wp-config.php (outside the theme folder): define('TURNFLOW_CHAT_SECRET', 'paste-your-secret-here');. Then, in your child theme's functions.php:
// Only answers signed-in users; admin-ajax.php is not stored in page caches.
add_action('wp_ajax_turnflow_identity', function () {
$u = wp_get_current_user();
$name = $u->display_name;
$email = $u->user_email;
$phone = get_user_meta($u->ID, 'billing_phone', true); // exists if you use WooCommerce; otherwise leave it empty
$ts = time();
$sig = hash_hmac('sha256', "v1|$phone|$email|$name|$ts", TURNFLOW_CHAT_SECRET);
nocache_headers();
wp_send_json(['name' => $name, 'email' => $email, 'phone' => (string) $phone, 'ts' => $ts, 'sig' => $sig]);
});
On the page, the step 4 fetch points to /wp-admin/admin-ajax.php?action=turnflow_identity. If the visitor isn't signed in, WordPress answers with an error and the chat stays anonymous. Don't put the signature directly in the page HTML: caching plugins could serve one customer's identity to another.
Ruby on Rails
# app/controllers/turnflow_identity_controller.rb
class TurnflowIdentityController < ApplicationController
before_action :authenticate_user! # Devise, or your own session filter
def show
ts = Time.now.to_i
phone, email, name = current_user.phone.to_s, current_user.email.to_s, current_user.name.to_s
sig = OpenSSL::HMAC.hexdigest("SHA256", ENV.fetch("TURNFLOW_CHAT_SECRET"), "v1|#{phone}|#{email}|#{name}|#{ts}")
response.headers["Cache-Control"] = "no-store"
render json: { name: name, email: email, phone: phone, ts: ts, sig: sig }
end
end
# config/routes.rb: get "/turnflow-identity", to: "turnflow_identity#show"
Laravel
// routes/web.php
use Illuminate\Http\Request;
Route::get('/turnflow-identity', function (Request $request) {
$u = $request->user();
$phone = $u->phone ?? ''; $email = $u->email ?? ''; $name = $u->name ?? '';
$ts = time();
$sig = hash_hmac('sha256', "v1|$phone|$email|$name|$ts", config('services.turnflow.chat_secret'));
return response()->json(compact('name', 'email', 'phone', 'ts', 'sig'))
->header('Cache-Control', 'no-store');
})->middleware('auth');
In config/services.php add 'turnflow' => ['chat_secret' => env('TURNFLOW_CHAT_SECRET')] and the value in your .env.
Platforms without your own server (Shopify, Wix, Webflow, Squarespace)
These platforms don't give you a server of your own where the secret can be kept safely, and the signature can't be computed in the browser (the secret would be visible to everyone). Honest alternatives:
- Don't identify. The chat works the same: visitors arrive as anonymous and your team can ask for their name or phone inside the conversation. It is the simplest option and perfectly valid.
- A small separate service (your own hosting or a serverless function) that signs, only if it can safely verify who is signed in (for example by validating a session or token issued by the platform). If there is no way to verify it, don't sign: signing what the browser claims is the same as letting anyone impersonate another customer.
Turnflow does not currently offer a pre-chat form that asks the visitor for their details.
Common errors
| Symptom | Likely cause |
|---|---|
| The customer still appears as "Visitor" | Signature mismatch: wrong secret (or an old one after regenerating), a value changed after signing, an expired signature (server clock, more than 30 minutes) or a sig that isn't 64-character hexadecimal (for example base64). |
| Works on my computer, not in production | The production secret is different, or the environment variable isn't loaded. |
| Works for a few minutes then stops | The page was left open and the signature expired; renew it every ~20 minutes. |
| Works for some people and not others | The endpoint is cached (CDN, caching plugin): exclude /turnflow-identity from the cache. |
| The signature is right but it doesn't link | There is no usable value: the phone doesn't end up with 8 to 15 digits (is the country code missing?) and the email isn't valid. |
| Odd characters in the name | The signature was computed over a different text than the one sent (another encoding). Use UTF-8 on both sides. |
name is shortened |
Turnflow keeps up to 80 characters of the name. |
Security in a few lines
- The secret lives only on your server. If you suspect it leaked, generate another in Settings and update it.
- Never sign data that comes from the browser: sign only what your system knows about the session.
- A stolen signature only works for that customer and for 30 minutes at most.