การรวมวิดเจ็ต
รวมวิดเจ็ต ChatHub เข้ากับเว็บไซต์ของคุณเพื่อให้การสนับสนุนแชทแบบเรียลไทม์แก่ลูกค้าของคุณ
ภาพรวม
วิดเจ็ต ChatHub เป็นคอมโพเนนต์ JavaScript ที่:
- ฝังลงในเว็บไซต์ใดก็ได้
- ให้ส่วนติดต่อแชทแบบเรียลไทม์
- เชื่อมต่อผู้ใช้กับผู้ปฏิบัติงาน
- ต้องการโทเค็นการยืนยันตัวผู้ปฏิบัติงาน
- โหลดเป็นโมดูล ES
เริ่มต้นอย่างรวดเร็ว
1. รับโทเค็นผู้ปฏิบัติงาน
ขั้นแรก ให้รับโทเค็นผู้ปฏิบัติงานตาม กระบวนการยืนยันตัว:
// 1. Get company token
const companyToken = await getCompanyToken(login, password);
// 2. Get organization
const organizations = await getOrganizations(companyToken);
const orgId = organizations[0].id;
// 3. Get operator
const operators = await getOperators(companyToken, orgId);
const operatorId = operators[0].id;
// 4. Generate operator token
const operatorToken = await getOperatorToken(
companyToken,
operatorId,
expiresAt
);
// 5. Validate token
const isValid = await validateToken(companyToken, operatorToken);
2. ฝังวิดเจ็ต
เพิ่มสคริปต์วิดเจ็ตลงใน HTML ของคุณ:
<!DOCTYPE html>
<html>
<head>
<title>Your Website</title>
</head>
<body>
<!-- Your website content -->
<!-- ChatHub Widget -->
<script type="module" id="operator-chat-panel-script"
src="https://widget.smsbat.com/operator-chat-panel/widget-script.js"
token="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."></script>
</body>
</html>
พารามิเตอร์สคริปต์
| คุณลักษณะ | ค่า | จำเป็น | คำอธิบาย |
|---|---|---|---|
type | module | Yes | ประเภทโมดูล ES |
id | operator-chat-panel-script | Yes | ตัวระบุสคริปต์ที่ไม่ซ้ำ |
src | Widget URL | Yes | ตำแหน่งสคริปต์วิดเจ็ต |
token | JWT token | Yes | โทเค็นการยืนยันตัวผู้ปฏิบัติงาน |
วิธีการบูรณาการ
HTML แบบคงที่
สำหรับเว็บไซต์แบบคงที่ ให้ฝังโดยตรงใน HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>My Website</title>
</head>
<body>
<h1>Welcome to My Website</h1>
<!-- ChatHub Widget -->
<script type="module" id="operator-chat-panel-script"
src="https://widget.smsbat.com/operator-chat-panel/widget-script.js"
token="YOUR_OPERATOR_TOKEN"></script>
</body>
</html>
การแทรกแบบไดนามิก (JavaScript)
สำหรับแอปพลิเคชันหน้าเดียว ให้แทรกแบบไดนามิก:
function loadChatHubWidget(operatorToken) {
// Check if widget already loaded
const existing = document.getElementById('operator-chat-panel-script');
if (existing) {
existing.remove();
}
// Create script element
const script = document.createElement('script');
script.type = 'module';
script.id = 'operator-chat-panel-script';
script.src = 'https://widget.smsbat.com/operator-chat-panel/widget-script.js';
script.setAttribute('token', operatorToken);
// Append to body
document.body.appendChild(script);
}
// Usage
const token = await getOperatorToken();
loadChatHubWidget(token);
React
import { useEffect } from 'react';
function ChatHubWidget({ operatorToken }) {
useEffect(() => {
if (!operatorToken) return;
// Load widget
const script = document.createElement('script');
script.type = 'module';
script.id = 'operator-chat-panel-script';
script.src = 'https://widget.smsbat.com/operator-chat-panel/widget-script.js';
script.setAttribute('token', operatorToken);
document.body.appendChild(script);
// Cleanup on unmount
return () => {
const existing = document.getElementById('operator-chat-panel-script');
if (existing) {
existing.remove();
}
};
}, [operatorToken]);
return null;
}
// Usage
function App() {
const [token, setToken] = useState('');
useEffect(() => {
async function init() {
const operatorToken = await fetchOperatorToken();
setToken(operatorToken);
}
init();
}, []);
return (
<div>
<h1>My App</h1>
<ChatHubWidget operatorToken={token} />
</div>
);
}
Vue.js
<template>
<div id="app">
<h1>My App</h1>
</div>
</template>
<script>
export default {
name: 'App',
data() {
return {
operatorToken: ''
};
},
async mounted() {
// Get operator token
this.operatorToken = await this.fetchOperatorToken();
// Load widget
this.loadWidget();
},
methods: {
async fetchOperatorToken() {
// Your token fetching logic
const response = await fetch('/api/chathub/token');
return response.text();
},
loadWidget() {
if (!this.operatorToken) return;
const script = document.createElement('script');
script.type = 'module';
script.id = 'operator-chat-panel-script';
script.src = 'https://widget.smsbat.com/operator-chat-panel/widget-script.js';
script.setAttribute('token', this.operatorToken);
document.body.appendChild(script);
}
},
beforeUnmount() {
const script = document.getElementById('operator-chat-panel-script');
if (script) {
script.remove();
}
}
};
</script>
Angular
import { Component, OnInit, OnDestroy } from '@angular/core';
@Component({
selector: 'app-root',
template: '<h1>My App</h1>'
})
export class AppComponent implements OnInit, OnDestroy {
private operatorToken: string = '';
async ngOnInit() {
// Get operator token
this.operatorToken = await this.fetchOperatorToken();
// Load widget
this.loadWidget();
}
ngOnDestroy() {
const script = document.getElementById('operator-chat-panel-script');
if (script) {
script.remove();
}
}
private async fetchOperatorToken(): Promise<string> {
const response = await fetch('/api/chathub/token');
return response.text();
}
private loadWidget() {
if (!this.operatorToken) return;
const script = document.createElement('script');
script.type = 'module';
script.id = 'operator-chat-panel-script';
script.src = 'https://widget.smsbat.com/operator-chat-panel/widget-script.js';
script.setAttribute('token', this.operatorToken);
document.body.appendChild(script);
}
}
การจัดการโทเคน
การสร้างโทเคนฝั่งเซิร์ฟเวอร์
ห้ามเปิดเผยข้อมูลรับรองของบริษัทในโค้ดฝั่งไคลเอนต์. สร้างโทเคนบนเซิร์ฟเวอร์ของคุณ:
// Node.js Express example
const express = require('express');
const app = express();
app.get('/api/chathub/token', async (req, res) => {
try {
// Authenticate your user first
const userId = req.session.userId;
if (!userId) {
return res.status(401).json({ error: 'Unauthorized' });
}
// Get company token (stored securely on server)
const companyToken = process.env.CHATHUB_COMPANY_TOKEN;
// Get operator ID for this user
const operatorId = await getOperatorIdForUser(userId);
// Generate operator token
const operatorToken = await generateOperatorToken(
companyToken,
operatorId
);
res.json({ token: operatorToken });
} catch (error) {
res.status(500).json({ error: 'Failed to generate token' });
}
});
async function generateOperatorToken(companyToken, operatorId) {
const expiresAt = new Date(Date.now() + 24 * 60 * 60 * 1000); // 24 hours
const response = await fetch(
'https://chatapi.smsbat.com/api/operator/get-token',
{
method: 'POST',
headers: {
'Authorization': `Bearer ${companyToken}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
id: operatorId,
expiresAt: expiresAt.toISOString()
})
}
);
return response.text();
}
การรีเฟรชโทเคน
ดำเนินการรีเฟรชโทเคนอัตโนมัติ:
class WidgetTokenManager {
constructor() {
this.token = null;
this.expiresAt = null;
this.refreshInterval = null;
}
async initialize() {
await this.refreshToken();
// Refresh token 1 hour before expiration
this.refreshInterval = setInterval(
() => this.checkAndRefresh(),
60 * 60 * 1000 // Check every hour
);
}
async refreshToken() {
const response = await fetch('/api/chathub/token');
const data = await response.json();
this.token = data.token;
this.expiresAt = new Date(data.expiresAt);
this.reloadWidget();
}
async checkAndRefresh() {
const oneHour = 60 * 60 * 1000;
const timeUntilExpiry = this.expiresAt - Date.now();
if (timeUntilExpiry < oneHour) {
await this.refreshToken();
}
}
reloadWidget() {
// Remove old widget
const existing = document.getElementById('operator-chat-panel-script');
if (existing) {
existing.remove();
}
// Load new widget with fresh token
const script = document.createElement('script');
script.type = 'module';
script.id = 'operator-chat-panel-script';
script.src = 'https://widget.smsbat.com/operator-chat-panel/widget-script.js';
script.setAttribute('token', this.token);
document.body.appendChild(script);
}
destroy() {
if (this.refreshInterval) {
clearInterval(this.refreshInterval);
}
}
}
// Usage
const widgetManager = new WidgetTokenManager();
await widgetManager.initialize();
หลายองค์กร
โหลดวิดเจ็ตที่แตกต่างสำหรับแต่ละองค์กร:
function loadWidgetForOrganization(organizationId) {
return new Promise((resolve, reject) => {
// Get operator for this organization
fetch(`/api/chathub/token?org=${organizationId}`)
.then(response => response.json())
.then(data => {
const script = document.createElement('script');
script.type = 'module';
script.id = `operator-chat-panel-script-${organizationId}`;
script.src = 'https://widget.smsbat.com/operator-chat-panel/widget-script.js';
script.setAttribute('token', data.token);
script.onload = () => resolve();
script.onerror = () => reject(new Error('Failed to load widget'));
document.body.appendChild(script);
})
.catch(reject);
});
}
// Usage
await loadWidgetForOrganization('sales');
await loadWidgetForOrganization('support');
แนวทางปฏิบัติที่ดีที่สุด
ความปลอดภัย
- ✅ สร้างโทเคนฝั่งเซิร์ฟเวอร์
- ✅ ห้ามเปิดเผยข้อมูลรับรองของบริษัทในโค้ดไคลเอนต์
- ✅ ใช้ HTTPS สำหรับคำขอ API ทั้งหมด
- ✅ ดำเนินการหมดอายุของโทเคน
- ✅ ตรวจสอบความถูกต้องของโทเคนก่อนใช้งาน
- ❌ อย่าเก็บโทเคนใน localStorage โดยไม่มีการเข้ารหัส
- ❌ อย่าคอมมิตโทเคนไปยังระบบควบคุมเวอร์ชัน
ประสิทธิภาพ
- ✅ โหลดวิดเจ็ตแบบอะซิงโครนัส
- ✅ ใช้ ES modules (เบราว์เซอร์สมัยใหม่)
- ✅ ดำเนินการแคชโทเคน
- ✅ จัดการข้อผิดพลาดอย่างราบรื่น
- ❌ อย่าบล็อกการโหลดหน้าเว็บ
ประสบการณ์ผู้ใช้
- ✅ แสดงสถานะการโหลดขณะวิดเจ็ตเริ่มต้น
- ✅ จัดการข้อผิดพลาดเครือข่าย
- ✅ ให้วิธีติดต่อสำรอง
- ✅ ทดสอบบนเบราว์เซอร์และอุปกรณ์ต่าง ๆ
การจัดการข้อผิดพลาด
async function loadWidgetSafely(operatorToken) {
try {
// Validate token first
const isValid = await validateToken(operatorToken);
if (!isValid) {
console.error('Invalid operator token');
showFallbackContact();
return;
}
// Load widget
await loadWidget(operatorToken);
} catch (error) {
console.error('Failed to load chat widget:', error);
showFallbackContact();
}
}
function showFallbackContact() {
// Show alternative contact method
const fallback = document.createElement('div');
fallback.innerHTML = `
<div class="chat-fallback">
<p>Chat is temporarily unavailable.</p>
<p>Contact us: <a href="mailto:support@example.com">support@example.com</a></p>
</div>
`;
document.body.appendChild(fallback);
}
การแก้ไขปัญหา
วิดเจ็ตไม่โหลด
- ตรวจสอบว่าโทเคนของผู้ให้บริการถูกต้อง
- ยืนยันว่าโทเคนยังไม่หมดอายุ
- ตรวจสอบให้แน่ใจว่า URL ของสคริปต์ถูกต้อง
- ตรวจสอบคอนโซลของเบราว์เซอร์เพื่อหาข้อผิดพลาด
- ยืนยันการเชื่อมต่อเครือข่าย
Token หมดอายุ
// Detect expired token and refresh
window.addEventListener('error', async (event) => {
if (event.message.includes('token expired')) {
console.log('Token expired, refreshing...');
await refreshWidgetToken();
}
});
ตัวอย่าง Widget หลายตัว
ตรวจสอบให้โหลด widget เพียงหนึ่งตัวในแต่ละครั้ง:
function loadWidgetOnce(token) {
// Remove any existing widgets
const existingScripts = document.querySelectorAll(
'script[id^="operator-chat-panel-script"]'
);
existingScripts.forEach(script => script.remove());
// Load new widget
loadWidget(token);
}
ปัญหา Cross-Origin
ตรวจสอบให้โดเมนของคุณอยู่ในรายการอนุญาต ติดต่อฝ่ายสนับสนุนหากพบข้อผิดพลาด CORS.
การทดสอบ
การพัฒนาในเครื่อง
// Use test token for development
const isDevelopment = process.env.NODE_ENV === 'development';
const token = isDevelopment
? 'test-token-for-development'
: await getProductionToken();
loadWidget(token);
การทดสอบการบูรณาการ
describe('ChatHub Widget', () => {
it('should load widget with valid token', async () => {
const token = await getTestToken();
loadWidget(token);
await waitFor(() => {
const widget = document.getElementById('operator-chat-panel-script');
expect(widget).toBeTruthy();
});
});
it('should handle invalid token', async () => {
const invalidToken = 'invalid-token';
try {
await loadWidget(invalidToken);
} catch (error) {
expect(error.message).toContain('Invalid token');
}
});
});
ขั้นตอนต่อไป
- การรับรองตัวตน - จัดการ token
- ผู้ปฏิบัติการ - ตั้งค่าผู้ปฏิบัติการ
- องค์กร - กำหนดค่าองค์กร