Files
crm-ai/web/ai-snippet.js

88 lines
2.8 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* Yehwang LibreDesk widget 接入脚本(新栈)
*
* 用法:页面里先设置 window.YehwangChatConfig,再引入本脚本。
*
* <script>
* window.YehwangChatConfig = {
* baseURL: 'http://localhost:9000',
* inboxID: '10fd5207-d235-4c49-beaa-a65eed0ddd0e',
* identityURL: 'http://localhost:4100/identity',
* siteJWT: window.__SITE_JWT__ || null // 站点登录后注入
* };
* </script>
* <script async src="/ai-snippet.js"></script>
*
* 有 siteJWT:走 bridge /identity 验签换 LibreDesk widget JWT(生产路径)。
* 无 siteJWT:匿名访客。
*/
(function () {
var cfg = window.YehwangChatConfig || {};
var baseURL = String(cfg.baseURL || 'http://localhost:9000').replace(/\/+$/, '');
var inboxID = cfg.inboxID || '10fd5207-d235-4c49-beaa-a65eed0ddd0e';
var identityURL = cfg.identityURL || 'http://localhost:4100/identity';
var state = { loaded: false, userJWT: null };
function loadWidget() {
if (state.loaded) return;
state.loaded = true;
window.LibredeskSettings = { baseURL: baseURL, inboxID: inboxID };
if (state.userJWT) window.LibredeskSettings.userJWT = state.userJWT;
var s = document.createElement('script');
s.async = true;
s.src = baseURL + '/widget.js';
document.head.appendChild(s);
}
function postIdentity(body) {
return fetch(identityURL, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
}).then(function (res) {
if (!res.ok) throw new Error('identity HTTP ' + res.status);
return res.json();
});
}
async function resolveUserJWT() {
if (cfg.userJWT) return cfg.userJWT;
if (cfg.siteJWT) {
var out = await postIdentity({ token: cfg.siteJWT });
return out.userJWT;
}
// 仅开发联调:直接传 email(需要 bridge IDENTITY_DEV_MODE=true)
if (cfg.demoEmail) {
var dev = await postIdentity({
email: cfg.demoEmail,
externalUserId: cfg.demoExternalId || cfg.demoEmail,
firstName: cfg.demoFirstName || 'Customer',
lastName: cfg.demoLastName || '',
});
return dev.userJWT;
}
return null;
}
async function boot() {
if (cfg.siteJWT || cfg.demoEmail || cfg.userJWT) {
try {
state.userJWT = await resolveUserJWT();
} catch (e) {
// 身份失败不阻塞 widget,降级为匿名会话
console.warn('[YehwangChat] identity failed, fallback to anonymous:', e.message);
}
}
loadWidget();
}
window.YehwangChat = {
/** 页面登录状态变化后可调用:重新设置 JWT 并重载(简单做法:刷新页面) */
setSiteJWT: function (jwt) { cfg.siteJWT = jwt; },
isLoggedIn: function () { return Boolean(state.userJWT); },
};
boot();
})();