API Reference
Securely pass authenticated user identity to the ChatSpark widget using HMAC-SHA256 signatures. This ensures users cannot impersonate others.
When your site has logged-in users, you can pass their identity (e.g. user ID, email) to the widget so the AI has context and conversations are attributed correctly. To prevent spoofing, you must sign the user data with a secret only your server knows.
Create a signature by hashing the user identifier with your secret. The identifier should be a stable, unique value (e.g. user ID or email). Use the same format consistently:
javascript
// Node.js
const crypto = require('crypto');
function generateIdentityHash(userId, secret) {
return crypto
.createHmac('sha256', secret)
.update(userId)
.digest('hex');
}
const userId = 'user_12345';
const secret = process.env.CHATSPARK_IDENTITY_SECRET;
const hash = generateIdentityHash(userId, secret);
// Pass hash and userId to the clientOn page load, fetch the signed identity from your backend and pass it via the widget data prop:
// Client-side: fetch from your API, then init widget
fetch('/api/chatspark-identity')
.then(res => res.json())
.then(({ userId, hash, email, name }) => {
const instance = ChatSpark({
chatbotId: 'YOUR_ID',
data: {
userId,
hash,
email,
name
}
});
instance.render('body');
});javascript
// app/api/chatspark-identity/route.js
import { createHmac } from 'crypto';
import { getServerSession } from 'next-auth';
export async function GET() {
const session = await getServerSession();
if (!session?.user) {
return Response.json({ error: 'Unauthorized' }, { status: 401 });
}
const secret = process.env.CHATSPARK_IDENTITY_SECRET;
const userId = session.user.id;
const hash = createHmac('sha256', secret).update(userId).digest('hex');
return Response.json({
userId,
hash,
email: session.user.email,
name: session.user.name
});
}javascript
const crypto = require('crypto');
app.get('/api/chatspark-identity', authMiddleware, (req, res) => {
const secret = process.env.CHATSPARK_IDENTITY_SECRET;
const userId = req.user.id;
const hash = crypto
.createHmac('sha256', secret)
.update(userId)
.digest('hex');
res.json({
userId,
hash,
email: req.user.email,
name: req.user.name
});
});text
import hmac
import hashlib
from flask import jsonify
from your_auth import get_current_user
@app.route('/api/chatspark-identity')
@require_auth
def chatspark_identity():
user = get_current_user()
secret = os.environ['CHATSPARK_IDENTITY_SECRET'].encode()
message = user.id.encode()
hash_result = hmac.new(secret, message, hashlib.sha256).hexdigest()
return jsonify({
'userId': user.id,
'hash': hash_result,
'email': user.email,
'name': user.name
})Always sign identity on the server. A malicious user could modify client-side values; the hash proves the identity was issued by your backend.