विजेट एकीकरण
अपने वेबसाइट में ChatHub विजेट को एकीकृत करें ताकि अपने ग्राहकों को रीयल‑टाइम चैट समर्थन प्रदान किया जा सके।
अवलोकन
ChatHub विजेट एक JavaScript घटक है जो:
- किसी भी वेबसाइट में एम्बेड होता है
- रीयल‑टाइम चैट इंटरफ़ेस प्रदान करता है
- ग्राहकों को ऑपरेटरों से जोड़ता है
- ऑपरेटर प्रमाणीकरण टोकन की आवश्यकता होती है
- ES मॉड्यूल के रूप में लोड होता है
त्वरित प्रारंभ
1. ऑपरेटर टोकन प्राप्त करें
पहले, authentication flow के अनुसार ऑपरेटर टोकन प्राप्त करें:
// 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 | हाँ | ES मॉड्यूल प्रकार |
id | operator-chat-panel-script | हाँ | अद्वितीय स्क्रिप्ट पहचानकर्ता |
src | Widget URL | हाँ | विजेट स्क्रिप्ट स्थान |
token | JWT token | हाँ | ऑपरेटर प्रमाणीकरण टोकन |
एकीकरण विधियाँ
स्थैतिक 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');
सर्वोत्तम प्रथाएँ
सुरक्षा
- ✅ टोकन सर्वर-साइड जेनरेट करें
- ✅ क्लाइंट कोड में कंपनी क्रेडेंशियल्स कभी न दिखाएँ
- ✅ सभी API अनुरोधों के लिए HTTPS उपयोग करें
- ✅ टोकन समाप्ति लागू करें
- ✅ उपयोग से पहले टोकन सत्यापित करें
- ❌ टोकन को बिना एन्क्रिप्शन के localStorage में न रखें
- ❌ टोकन को संस्करण नियंत्रण में कमिट न करें
प्रदर्शन
- ✅ विजेट को असिंक्रोनस रूप से लोड करें
- ✅ ES मॉड्यूल (आधुनिक ब्राउज़र) का उपयोग करें
- ✅ टोकन कैशिंग लागू करें
- ✅ त्रुटियों को सुगमता से संभालें
- ❌ पेज लोड को ब्लॉक न करें
उपयोगकर्ता अनुभव
- ✅ विजेट के प्रारंभ होने पर लोडिंग स्थिति दिखाएँ
- ✅ नेटवर्क त्रुटियों को संभालें
- ✅ वैकल्पिक संपर्क विधि प्रदान करें
- ✅ विभिन्न ब्राउज़र और डिवाइस पर परीक्षण करें
त्रुटि प्रबंधन
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 सही है यह सुनिश्चित करें
- ब्राउज़र कंसोल में त्रुटियों की जाँच करें
- नेटवर्क कनेक्टिविटी सत्यापित करें
टोकन समाप्त हो गया
// Detect expired token and refresh
window.addEventListener('error', async (event) => {
if (event.message.includes('token expired')) {
console.log('Token expired, refreshing...');
await refreshWidgetToken();
}
});
कई विजेट इंस्टेंस
एक समय में केवल एक विजेट लोड हो, यह सुनिश्चित करें:
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);
}
क्रॉस-ऑरिजिन समस्याएँ
सुनिश्चित करें कि आपका डोमेन व्हाइटलिस्टेड है। यदि आपको 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');
}
});
});
अगले कदम
- Authentication - टोकन प्रबंधित करें
- Operators - ऑपरेटर सेट अप करें
- Organizations - संगठनों को कॉन्फ़िगर करें