Auth for Chat
Implementation Examples
Code examples in different languages
cURL
curl -X POST https://api.performchat.com/rest/v1/auth/token \
-H "Content-Type: application/json" \
-d '{
"keyId": "pk_your_key_id",
"keySecret": "sk_your_secret_key",
"userId": "user_123",
"agentId": "agent_abc",
"expiresIn": "1h"
}'With custom expiration (7 days):
curl -X POST https://api.performchat.com/rest/v1/auth/token \
-H "Content-Type: application/json" \
-d '{
"keyId": "pk_your_key_id",
"keySecret": "sk_your_secret_key",
"userId": "user_123",
"agentId": "agent_abc",
"expiresIn": "7d"
}'Response:
{
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"user": {
"id": "cuid_internal_id",
"externalId": "user_123",
"companyId": "company_xyz",
"agentId": "agent_abc"
},
"agent": {
"id": "agent_abc",
"name": "Support Agent",
"active": true
}
}JavaScript (Node.js)
const fetch = require('node-fetch');
async function generateChatToken(userId, expiresIn = '24h') {
try {
const response = await fetch('https://api.performchat.com/rest/v1/auth/token', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
keyId: process.env.PERFORMCHAT_KEY_ID,
keySecret: process.env.PERFORMCHAT_KEY_SECRET,
userId: userId,
agentId: 'your-agent-id',
expiresIn: expiresIn // Optional - defaults to '24h'
})
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
// ⚠️ IMPORTANT: Store user.id for token invalidation
return {
token: data.token,
userId: data.user.id, // Save this in your database!
externalId: data.user.externalId
};
} catch (error) {
console.error('Error generating token:', error);
throw error;
}
}
// Usage in your Express.js API
app.post('/api/chat/token', async (req, res) => {
try {
const userId = req.user.id;
const { token, userId: performChatUserId } = await generateChatToken(userId);
// Store performChatUserId in your database for later invalidation
await db.users.update({
where: { id: userId },
data: { performChatUserId }
});
res.json({ token });
} catch (error) {
res.status(500).json({ error: 'Failed to generate chat token' });
}
});Python (FastAPI)
import os
import httpx
from fastapi import FastAPI, HTTPException, Depends
app = FastAPI()
PERFORMCHAT_API_URL = "https://api.performchat.com/rest/v1/auth/token"
async def generate_chat_token(user_id: str, agent_id: str = None) -> str:
async with httpx.AsyncClient() as client:
payload = {
"keyId": os.getenv("PERFORMCHAT_KEY_ID"),
"keySecret": os.getenv("PERFORMCHAT_KEY_SECRET"),
"userId": user_id,
}
if agent_id:
payload["agentId"] = agent_id
response = await client.post(PERFORMCHAT_API_URL, json=payload)
if response.status_code != 200:
raise HTTPException(status_code=500, detail="Failed to generate token")
return response.json()["token"]
@app.post("/api/chat/token")
async def create_chat_token(current_user: dict = Depends(get_current_user)):
token = await generate_chat_token(user_id=current_user["id"])
return {"token": token}Ruby (Rails)
require 'net/http'
require 'json'
class ChatTokenService
PERFORMCHAT_API_URL = 'https://api.performchat.com/rest/v1/auth/token'
def self.generate_token(user_id, agent_id = nil)
uri = URI(PERFORMCHAT_API_URL)
request = Net::HTTP::Post.new(uri)
request['Content-Type'] = 'application/json'
request.body = {
keyId: ENV['PERFORMCHAT_KEY_ID'],
keySecret: ENV['PERFORMCHAT_KEY_SECRET'],
userId: user_id,
agentId: agent_id
}.compact.to_json
response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|
http.request(request)
end
if response.is_a?(Net::HTTPSuccess)
JSON.parse(response.body)['token']
else
raise "Failed to generate token: #{response.code}"
end
end
endPHP (Laravel)
<?php
namespace App\Services;
use Illuminate\Support\Facades\Http;
class ChatTokenService
{
private const API_URL = 'https://api.performchat.com/rest/v1/auth/token';
public static function generateToken(string $userId, ?string $agentId = null): string
{
$payload = [
'keyId' => env('PERFORMCHAT_KEY_ID'),
'keySecret' => env('PERFORMCHAT_KEY_SECRET'),
'userId' => $userId,
];
if ($agentId) {
$payload['agentId'] = $agentId;
}
$response = Http::post(self::API_URL, $payload);
if ($response->failed()) {
throw new \Exception('Failed to generate token');
}
return $response->json()['token'];
}
}