shareAiKfChat.html 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648
  1. <!DOCTYPE html>
  2. <html lang="zh-CN">
  3. <head>
  4. <meta charset="utf-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover">
  6. <meta name="format-detection" content="telephone=no">
  7. <title>与AI客服对话</title>
  8. <meta property="og:title" content="和AI客服的对话">
  9. <meta property="og:description" content="点击查看对话内容">
  10. <meta property="og:site_name" content="U店在哪">
  11. <meta name="application-name" content="U店在哪">
  12. <link rel="icon" type="image/png" href="https://alien-volume.oss-cn-beijing.aliyuncs.com/icon/ubao.png">
  13. <link rel="apple-touch-icon" href="https://alien-volume.oss-cn-beijing.aliyuncs.com/icon/ubao.png">
  14. <style>
  15. :root {
  16. --bg: #f4f6fb;
  17. --text: #151515;
  18. --muted: #aaaaaa;
  19. --orange: #f47d1f;
  20. --safe-bottom: env(safe-area-inset-bottom, 0px);
  21. }
  22. * {
  23. margin: 0;
  24. padding: 0;
  25. box-sizing: border-box;
  26. }
  27. html {
  28. height: 100%;
  29. -webkit-tap-highlight-color: transparent;
  30. overflow: hidden;
  31. }
  32. body {
  33. font-family: -apple-system, BlinkMacSystemFont, "PingFang SC", "Microsoft YaHei", sans-serif;
  34. background: var(--bg);
  35. color: var(--text);
  36. height: 100vh;
  37. display: flex;
  38. flex-direction: column;
  39. overflow: hidden;
  40. }
  41. #main {
  42. flex: 1;
  43. min-height: 0;
  44. overflow-x: hidden;
  45. overflow-y: auto;
  46. -webkit-overflow-scrolling: touch;
  47. padding-bottom: calc(100px + var(--safe-bottom));
  48. }
  49. .hero {
  50. padding: 16px 15px 0;
  51. }
  52. .hero__title {
  53. font-size: 20px;
  54. font-weight: 700;
  55. line-height: 1.4;
  56. word-break: break-word;
  57. }
  58. .hero__meta {
  59. margin-top: 8px;
  60. font-size: 12px;
  61. color: var(--muted);
  62. line-height: 1.4;
  63. }
  64. .hero__divider {
  65. margin-top: 14px;
  66. height: 1px;
  67. background: rgba(170, 170, 170, 0.25);
  68. }
  69. .conversation {
  70. padding: 14px 15px 8px;
  71. }
  72. .scroll-spacer {
  73. height: calc(72px + var(--safe-bottom));
  74. flex-shrink: 0;
  75. }
  76. .conversation .row:last-child {
  77. margin-bottom: 0;
  78. }
  79. .row {
  80. display: flex;
  81. margin-bottom: 12px;
  82. }
  83. .row--user {
  84. justify-content: flex-end;
  85. }
  86. .row--ai {
  87. justify-content: flex-start;
  88. }
  89. .user-bubble {
  90. position: relative;
  91. max-width: 78%;
  92. padding: 10px 14px;
  93. background: var(--orange);
  94. border-radius: 8px 8px 2px 8px;
  95. color: #fff;
  96. font-size: 15px;
  97. font-weight: 500;
  98. line-height: 1.5;
  99. white-space: pre-wrap;
  100. word-break: break-word;
  101. }
  102. .user-bubble::after {
  103. content: "";
  104. position: absolute;
  105. right: -6px;
  106. bottom: 8px;
  107. width: 0;
  108. height: 0;
  109. border-style: solid;
  110. border-width: 6px 0 6px 7px;
  111. border-color: transparent transparent transparent var(--orange);
  112. }
  113. .ai-card {
  114. width: 100%;
  115. padding: 14px 13px;
  116. background: #fff;
  117. border-radius: 12px;
  118. box-shadow: 0 1px 6px rgba(0, 0, 0, 0.04);
  119. }
  120. .ai-card__text {
  121. font-size: 14px;
  122. line-height: 1.65;
  123. white-space: pre-wrap;
  124. word-break: break-word;
  125. text-align: left;
  126. }
  127. .ai-card::after {
  128. content: "本回答由AI生成,内容仅供参考,请仔细甄别";
  129. display: block;
  130. margin-top: 8px;
  131. font-size: 12px;
  132. line-height: 1.5;
  133. color: #999999;
  134. text-align: left;
  135. font-style: italic;
  136. }
  137. .ai-card__image {
  138. display: block;
  139. max-width: 100%;
  140. height: auto;
  141. margin: 8px 0;
  142. border-radius: 6px;
  143. }
  144. .user-bubble__image {
  145. display: block;
  146. max-width: 180px;
  147. border-radius: 4px;
  148. }
  149. .fallback-card {
  150. margin: 14px 15px 0;
  151. padding: 14px 13px;
  152. background: #fff;
  153. border-radius: 8px;
  154. box-shadow: 0 1px 6px rgba(0, 0, 0, 0.04);
  155. }
  156. .fallback-card .ai-card__text {
  157. font-size: 14px;
  158. line-height: 1.65;
  159. white-space: pre-wrap;
  160. word-break: break-word;
  161. text-align: left;
  162. }
  163. .empty {
  164. padding: 48px 20px;
  165. text-align: center;
  166. color: var(--muted);
  167. font-size: 14px;
  168. }
  169. .fab-wrap {
  170. position: fixed;
  171. left: 0;
  172. right: 0;
  173. bottom: 0;
  174. z-index: 200;
  175. padding: 12px 24px calc(12px + var(--safe-bottom));
  176. background: linear-gradient(to top, rgba(255, 255, 255, 0.98) 70%, transparent);
  177. pointer-events: none;
  178. }
  179. .fab-dock__slot {
  180. width: 100%;
  181. max-width: 280px;
  182. height: 48px;
  183. margin: 0 auto;
  184. pointer-events: auto;
  185. }
  186. #openApp.fab {
  187. padding: 0 10px;
  188. -webkit-font-smoothing: antialiased;
  189. text-rendering: optimizeLegibility;
  190. }
  191. .fab__brand-clip {
  192. display: block;
  193. flex-shrink: 0;
  194. line-height: 0;
  195. }
  196. .fab__brand-img {
  197. display: block;
  198. height: 20px;
  199. width: auto;
  200. max-width: 90%;
  201. pointer-events: none;
  202. -webkit-user-drag: none;
  203. }
  204. .fab__label {
  205. font-size: 15px;
  206. line-height: 1;
  207. letter-spacing: 0.04em;
  208. white-space: nowrap;
  209. }
  210. #launch-btn {
  211. display: none;
  212. width: 100%;
  213. height: 48px;
  214. min-height: 48px;
  215. border-radius: 999px;
  216. overflow: hidden;
  217. opacity: 1;
  218. }
  219. body.is-wechat.wx-jssdk-ready #launch-btn {
  220. display: block;
  221. }
  222. body.is-wechat.wx-jssdk-ready #openApp {
  223. display: none !important;
  224. }
  225. .fab-wrap .fab {
  226. pointer-events: auto;
  227. }
  228. #openApp {
  229. touch-action: manipulation;
  230. }
  231. .fab {
  232. display: flex;
  233. align-items: center;
  234. justify-content: center;
  235. gap: 4px;
  236. width: 100%;
  237. max-width: 280px;
  238. margin: 0 auto;
  239. height: 48px;
  240. border: none;
  241. border-radius: 999px;
  242. background: linear-gradient(90deg, #ffb84c 0%, #ff6b3e 100%);
  243. color: #fff;
  244. font-size: 16px;
  245. font-weight: 600;
  246. box-shadow: 0 4px 16px rgba(255, 107, 62, 0.32);
  247. cursor: pointer;
  248. }
  249. .home-indicator {
  250. height: 5px;
  251. background: #000;
  252. border-radius: 3px;
  253. width: 134px;
  254. margin: 8px auto 4px;
  255. opacity: 0.2;
  256. }
  257. #openAppToast {
  258. display: none;
  259. position: fixed;
  260. left: 16px;
  261. right: 16px;
  262. bottom: calc(72px + var(--safe-bottom));
  263. z-index: 10001;
  264. padding: 10px 14px;
  265. font-size: 13px;
  266. line-height: 1.45;
  267. color: #fff;
  268. text-align: center;
  269. background: rgba(0, 0, 0, 0.78);
  270. border-radius: 8px;
  271. pointer-events: none;
  272. word-break: break-all;
  273. }
  274. </style>
  275. </head>
  276. <body>
  277. <main id="main">
  278. <div class="empty">对话内容加载中…</div>
  279. </main>
  280. <div id="openAppToast" role="status" aria-live="polite"></div>
  281. <div class="fab-wrap">
  282. <div class="fab-dock__slot">
  283. <!-- 与 secondShareGoods 相同顺序:openApp 在下,launch-btn 在上,避免挡住点击 -->
  284. <button type="button" class="fab" id="openApp" aria-label="和AI客服继续聊">
  285. <span class="fab__brand-clip" aria-hidden="true">
  286. <img class="fab__brand-img" src="images/uCharts.png" alt="和AI客服继续聊" decoding="async">
  287. </span>
  288. </button>
  289. <wx-open-launch-app id="launch-btn" appid="wxf5f1efe3a9f5012e" extinfo="">
  290. <script type="text/wxtag-template">
  291. <style>
  292. .wx-open-app-btn {
  293. display: flex;
  294. align-items: center;
  295. justify-content: center;
  296. width: 100%;
  297. height: 48px;
  298. margin: 0;
  299. padding: 0 10px;
  300. border: none;
  301. border-radius: 999px;
  302. background: linear-gradient(90deg, #ffb84c 0%, #ff6b3e 100%);
  303. box-shadow: 0 4px 16px rgba(255, 107, 62, 0.32);
  304. cursor: pointer;
  305. overflow: hidden;
  306. -webkit-tap-highlight-color: transparent;
  307. box-sizing: border-box;
  308. font-family: -apple-system, BlinkMacSystemFont, "PingFang SC", "Helvetica Neue", sans-serif;
  309. -webkit-font-smoothing: antialiased;
  310. }
  311. .wx-open-app-btn .fab__brand-clip {
  312. display: block;
  313. flex-shrink: 0;
  314. line-height: 0;
  315. }
  316. .wx-open-app-btn .fab__brand-img {
  317. display: block;
  318. height: 20px;
  319. width: auto;
  320. max-width: 90%;
  321. pointer-events: none;
  322. -webkit-user-drag: none;
  323. }
  324. </style>
  325. <button class="wx-open-app-btn" aria-label="和AI客服继续聊">
  326. <span class="fab__brand-clip" aria-hidden="true">
  327. <img class="fab__brand-img" src="https://prod.ailien.shop/h5/HBuilderProjects/images/uCharts.png" alt="和AI客服继续聊" decoding="async">
  328. </span>
  329. </button>
  330. </script>
  331. </wx-open-launch-app>
  332. </div>
  333. <div class="home-indicator" aria-hidden="true"></div>
  334. </div>
  335. <script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
  336. <script>
  337. (function () {
  338. "use strict";
  339. var API_BASE = "https://prod.ailien.shop/alienStore";
  340. var WECHAT_MP_APP_ID = "wx412792c77f47babd";
  341. var WECHAT_OPEN_APP_ID = "wxf5f1efe3a9f5012e";
  342. var WECHAT_GET_WX_CONFIG_PATH = "/wx/getWxConfig";
  343. var H5_PAGE_BASE_FALLBACK = "https://prod.ailien.shop/h5/HBuilderProjects/";
  344. var WX_GET_CONFIG_SIGN_URL = H5_PAGE_BASE_FALLBACK + "shareAiKfChat.html";
  345. var WECHAT_JS_SAFE_HOSTS = ["uat.ailien.shop", "prod.ailien.shop"];
  346. var APP_ANDROID_PACKAGE = "com.alien.Udianzaizhe";
  347. var APP_IOS_URL_SCHEME = "shopro://";
  348. var APP_UNI_AI_PATH = "pages/aiKfChat/index";
  349. var AI_KF_CS_CONVERSATION_API =
  350. "https://prod.ailien.shop/ai/life-manager/api/v1/udian-cs-conversation/history/conversation";
  351. var sharePayloadCache = null;
  352. var weChatJssdkConfigured = false;
  353. var wxConfigSignRetriedBaseUrl = false;
  354. var wxInitLastError = "";
  355. var wxJssdkInitPromise = null;
  356. function escHtml(s) {
  357. return String(s || "")
  358. .replace(/&/g, "&amp;")
  359. .replace(/</g, "&lt;")
  360. .replace(/>/g, "&gt;")
  361. .replace(/"/g, "&quot;");
  362. }
  363. var IMAGE_EXT = "(?:jpe?g|png|gif|webp|bmp|avif)";
  364. var IMAGE_URL_PATTERN =
  365. "https?:\\/\\/[^\\s))\\]]+\\." + IMAGE_EXT + "(?:\\?[^\\s))\\]]*)?";
  366. function isInsideImageUrlSyntax(full, offset) {
  367. if (offset >= 2 && full.slice(offset - 2, offset) === "](") return true;
  368. if (offset >= 1 && full[offset - 1] === "(") return true;
  369. if (offset >= 6 && full.slice(offset - 6, offset) === "{{IMG|") return true;
  370. return false;
  371. }
  372. /** AI 回复常见:店名(https://...jpg) — 转为可渲染的图片占位 */
  373. function embedInlineImageUrls(text) {
  374. if (text == null) return "";
  375. var t = String(text);
  376. t = t.replace(
  377. new RegExp("([^\\n((]+?)\\((" + IMAGE_URL_PATTERN + ")\\)", "gi"),
  378. function (_, label, url) {
  379. var name = String(label).trim();
  380. if (!name) return "\n\n{{IMG|" + url + "|}}\n\n";
  381. var alt = name.length > 24 ? "图片" : name.replace(/[\[\]]/g, "");
  382. return name + "\n\n{{IMG|" + url + "|" + alt + "}}\n\n";
  383. }
  384. );
  385. t = t.replace(
  386. new RegExp("\\((" + IMAGE_URL_PATTERN + ")\\)", "gi"),
  387. function (_, url) {
  388. return "\n\n{{IMG|" + url + "|}}\n\n";
  389. }
  390. );
  391. t = t.replace(new RegExp(IMAGE_URL_PATTERN, "gi"), function (url, offset, full) {
  392. if (isInsideImageUrlSyntax(full, offset)) return url;
  393. return "\n\n{{IMG|" + url + "|}}\n\n";
  394. });
  395. return t.replace(/\n{3,}/g, "\n\n");
  396. }
  397. function formatTextBlockHtml(text) {
  398. return escHtml(text).replace(/\n/g, "<br>");
  399. }
  400. function buildAiImageTag(url, alt) {
  401. var safeUrl = escHtml(url);
  402. var safeAlt = escHtml(alt || "图片");
  403. return (
  404. '<img class="ai-card__image" src="' +
  405. safeUrl +
  406. '" alt="' +
  407. safeAlt +
  408. '" loading="lazy" decoding="async" />'
  409. );
  410. }
  411. function renderAiContentHtml(text) {
  412. var t = embedInlineImageUrls(text);
  413. var html = "";
  414. var tokenRe = /\{\{IMG\|([^|]+)\|([^}]*)\}\}/g;
  415. var lastIndex = 0;
  416. var match;
  417. while ((match = tokenRe.exec(t)) !== null) {
  418. if (match.index > lastIndex) {
  419. html += formatTextBlockHtml(t.slice(lastIndex, match.index));
  420. }
  421. html += buildAiImageTag(match[1], match[2]);
  422. lastIndex = tokenRe.lastIndex;
  423. }
  424. if (lastIndex < t.length) {
  425. html += formatTextBlockHtml(t.slice(lastIndex));
  426. }
  427. return html;
  428. }
  429. function q(name) {
  430. try {
  431. var v = new URLSearchParams(location.search || "").get(name);
  432. return v == null ? "" : String(v);
  433. } catch (e) {
  434. return "";
  435. }
  436. }
  437. function getQueryParam(name) {
  438. var m = new RegExp("[?&]" + name + "=([^&]*)").exec(window.location.search);
  439. if (!m) return "";
  440. try {
  441. return decodeURIComponent(m[1].replace(/\+/g, " "));
  442. } catch (e) {
  443. return "";
  444. }
  445. }
  446. function parsePayload() {
  447. var raw = getQueryParam("payload");
  448. if (!raw) return null;
  449. try {
  450. return JSON.parse(raw);
  451. } catch (e) {
  452. return null;
  453. }
  454. }
  455. function getConversationQueryParams() {
  456. var sessionId = String(q("session_id") || q("sessionId") || "").trim();
  457. var userId = String(q("user_id") || q("userId") || "").trim();
  458. var clientType = String(q("client_type") || q("clientType") || "0").trim();
  459. if (!sessionId || !userId) return null;
  460. return { sessionId: sessionId, userId: userId, clientType: clientType };
  461. }
  462. function parseMessageIdsFromQuery() {
  463. var raw = String(q("message_ids") || q("messageIds") || "").trim();
  464. if (!raw) return null;
  465. return raw
  466. .split(",")
  467. .map(function (s) {
  468. return String(s || "").trim();
  469. })
  470. .filter(Boolean);
  471. }
  472. function normalizeHistoryRowImageUrls(item) {
  473. var raw = item.image_urls || item.imageUrls || item.images;
  474. if (Array.isArray(raw)) {
  475. return raw
  476. .map(function (u) {
  477. return String(u || "").trim();
  478. })
  479. .filter(Boolean);
  480. }
  481. if (typeof raw === "string" && raw.trim()) {
  482. return raw
  483. .split(",")
  484. .map(function (s) {
  485. return s.trim();
  486. })
  487. .filter(Boolean);
  488. }
  489. return [];
  490. }
  491. function filterConversationMessagesByIds(messages, idList) {
  492. if (!Array.isArray(idList) || !idList.length) return messages;
  493. var idSet = {};
  494. for (var i = 0; i < idList.length; i++) {
  495. idSet[String(idList[i])] = true;
  496. }
  497. return (Array.isArray(messages) ? messages : []).filter(function (msg) {
  498. if (!msg || msg.id == null || msg.id === "") return false;
  499. return !!idSet[String(msg.id)];
  500. });
  501. }
  502. function buildConversationApiUrl(sessionId, userId, clientType) {
  503. var params = new URLSearchParams();
  504. params.set("client_type", String(clientType != null && clientType !== "" ? clientType : "0"));
  505. params.set("session_id", sessionId);
  506. params.set("user_id", userId);
  507. return AI_KF_CS_CONVERSATION_API + "?" + params.toString();
  508. }
  509. function buildConversationRequestParams(sessionId, userId, clientType) {
  510. return {
  511. client_type: String(clientType != null && clientType !== "" ? clientType : "0"),
  512. session_id: sessionId,
  513. user_id: userId,
  514. };
  515. }
  516. function normalizeConversationRole(raw) {
  517. var role = String(raw || "").trim().toLowerCase();
  518. if (
  519. role === "user" ||
  520. role === "human" ||
  521. role === "customer" ||
  522. role === "question" ||
  523. role === "1" ||
  524. role === "我"
  525. ) {
  526. return "user";
  527. }
  528. if (
  529. role === "ai" ||
  530. role === "assistant" ||
  531. role === "bot" ||
  532. role === "ubao" ||
  533. role === "answer" ||
  534. role === "2" ||
  535. role === "system"
  536. ) {
  537. return "ai";
  538. }
  539. return "";
  540. }
  541. function normalizeConversationApiPayload(res) {
  542. if (!res || typeof res !== "object") return null;
  543. if (res.code != null) {
  544. var code = Number(res.code);
  545. if (code !== 200 && code !== 0 && res.success !== true) {
  546. throw new Error(res.msg || res.message || "对话接口返回 code " + code);
  547. }
  548. }
  549. var root = res.data != null && typeof res.data === "object" ? res.data : res;
  550. var rawList =
  551. (Array.isArray(root) && root) ||
  552. (Array.isArray(root.messages) && root.messages) ||
  553. (Array.isArray(root.messageList) && root.messageList) ||
  554. (Array.isArray(root.conversation) && root.conversation) ||
  555. (Array.isArray(root.conversations) && root.conversations) ||
  556. (Array.isArray(root.records) && root.records) ||
  557. (Array.isArray(root.list) && root.list) ||
  558. null;
  559. if (!rawList) return null;
  560. var messages = [];
  561. for (var i = 0; i < rawList.length; i++) {
  562. var item = rawList[i];
  563. if (!item || typeof item !== "object") continue;
  564. var msgId = item.id != null ? item.id : item.message_id;
  565. var role = normalizeConversationRole(
  566. item.role || item.sender || item.messageRole || item.type || item.messageType || item.senderType
  567. );
  568. var content = String(
  569. item.content != null
  570. ? item.content
  571. : item.message != null
  572. ? item.message
  573. : item.text != null
  574. ? item.text
  575. : ""
  576. ).trim();
  577. if (!role && item.question) {
  578. role = "user";
  579. content = String(item.question).trim();
  580. } else if (!role && item.answer) {
  581. role = "ai";
  582. content = String(item.answer).trim();
  583. } else if (!role && item.userMessage) {
  584. role = "user";
  585. content = String(item.userMessage).trim();
  586. } else if (!role && (item.aiMessage || item.assistantMessage)) {
  587. role = "ai";
  588. content = String(item.aiMessage || item.assistantMessage).trim();
  589. }
  590. var imageUrls = normalizeHistoryRowImageUrls(item);
  591. if (imageUrls.length) {
  592. messages.push({
  593. id: msgId,
  594. role: role || "user",
  595. isImage: true,
  596. imageUrl: imageUrls[0],
  597. content: content,
  598. });
  599. continue;
  600. }
  601. if (!content) continue;
  602. var imageUrl = item.imageUrl || item.image || item.imgUrl || item.url;
  603. if (imageUrl && /^(https?:)?\/\//i.test(String(imageUrl))) {
  604. messages.push({
  605. id: msgId,
  606. role: role || "user",
  607. isImage: true,
  608. imageUrl: String(imageUrl),
  609. });
  610. continue;
  611. }
  612. messages.push({
  613. id: msgId,
  614. role: role || (messages.length % 2 === 0 ? "user" : "ai"),
  615. content: content,
  616. });
  617. }
  618. if (!messages.length) return null;
  619. return {
  620. messages: messages,
  621. shareTime:
  622. root.shareTime ||
  623. root.createdAt ||
  624. root.createTime ||
  625. root.updateTime ||
  626. root.timestamp ||
  627. res.timestamp,
  628. firstQuestion: root.firstQuestion || root.title || root.topic || "",
  629. sessionId: root.sessionId || root.session_id || "",
  630. userId: root.userId || root.user_id || "",
  631. };
  632. }
  633. function fetchConversationHistory(sessionId, userId, clientType) {
  634. var requestUrl = buildConversationApiUrl(sessionId, userId, clientType);
  635. var requestParams = buildConversationRequestParams(sessionId, userId, clientType);
  636. console.log("[kf-conversation-api] GET", requestUrl);
  637. return fetch(requestUrl, {
  638. method: "GET",
  639. mode: "cors",
  640. credentials: "omit",
  641. headers: { Accept: "application/json" },
  642. })
  643. .then(function (r) {
  644. if (r.ok) {
  645. return r.json().then(function (json) {
  646. return { ok: true, json: json };
  647. });
  648. }
  649. return r
  650. .text()
  651. .catch(function () {
  652. return "";
  653. })
  654. .then(function (text) {
  655. var hint = "";
  656. try {
  657. var j = JSON.parse(text);
  658. hint = j.msg || j.message || "";
  659. } catch (eP) {
  660. if (text) hint = text.slice(0, 120);
  661. }
  662. throw new Error("对话接口 HTTP " + r.status + (hint ? ":" + hint : ""));
  663. });
  664. })
  665. .then(function (result) {
  666. var data = normalizeConversationApiPayload(result.json);
  667. if (!data) {
  668. throw new Error("对话接口返回数据为空或格式无法解析");
  669. }
  670. return data;
  671. });
  672. }
  673. function loadPageData() {
  674. var main = document.getElementById("main");
  675. var params = getConversationQueryParams();
  676. if (!params) {
  677. main.innerHTML = '<div class="empty">缺少 session_id 或 user_id 参数</div>';
  678. return;
  679. }
  680. var filterIds = parseMessageIdsFromQuery();
  681. main.innerHTML = '<div class="empty">对话内容加载中…</div>';
  682. fetchConversationHistory(params.sessionId, params.userId, params.clientType)
  683. .then(function (data) {
  684. if (filterIds && filterIds.length) {
  685. var filtered = filterConversationMessagesByIds(data.messages, filterIds);
  686. if (!filtered.length) {
  687. throw new Error("未找到所选对话内容");
  688. }
  689. data = Object.assign({}, data, { messages: filtered });
  690. }
  691. render(data);
  692. })
  693. .catch(function (e) {
  694. var tip = e && e.message ? e.message : "对话加载失败,请稍后重试";
  695. console.warn("[kf-conversation-api]", tip, e);
  696. main.innerHTML = '<div class="empty">' + escHtml(tip) + "</div>";
  697. refreshWxLaunchTagAttrs();
  698. });
  699. }
  700. function getFirstUserQuestion(messages) {
  701. var list = Array.isArray(messages) ? messages : [];
  702. for (var i = 0; i < list.length; i++) {
  703. var m = list[i];
  704. if (!m || m.role !== "user") continue;
  705. if (m.isImage) return "[图片]";
  706. var t = String(m.content || "").trim();
  707. if (t) return t;
  708. }
  709. return "";
  710. }
  711. function formatDiscussionTitle(question) {
  712. var qText = String(question || "").trim();
  713. if (!qText) return "与AI客服对话";
  714. if (qText.slice(-3) === "的讨论") return qText;
  715. return qText + "的讨论";
  716. }
  717. function normalizeShareTimestamp(ts) {
  718. if (ts == null || ts === "") return null;
  719. var n = Number(ts);
  720. if (!isFinite(n) || n <= 0) return null;
  721. if (n < 1e12) n = n * 1000;
  722. var d = new Date(n);
  723. if (isNaN(d.getTime()) || d.getFullYear() < 2020) return null;
  724. return n;
  725. }
  726. function resolveDisplayShareTime(data) {
  727. var fromUrl = q("shareTime") || q("share_time");
  728. var urlTs = normalizeShareTimestamp(fromUrl);
  729. if (urlTs != null) return urlTs;
  730. var dataTs = normalizeShareTimestamp(data && data.shareTime);
  731. if (dataTs != null) return dataTs;
  732. return Date.now();
  733. }
  734. function formatDate(ts) {
  735. var normalized = normalizeShareTimestamp(ts);
  736. var d = normalized != null ? new Date(normalized) : new Date();
  737. return d.getFullYear() + "年" + (d.getMonth() + 1) + "月" + d.getDate() + "日";
  738. }
  739. function renderMessages(messages) {
  740. var html = "";
  741. var list = Array.isArray(messages) ? messages : [];
  742. for (var i = 0; i < list.length; i++) {
  743. var msg = list[i];
  744. if (!msg) continue;
  745. if (msg.role === "user") {
  746. if (msg.isImage && msg.imageUrl) {
  747. html +=
  748. '<div class="row row--user"><div class="user-bubble"><img class="user-bubble__image" src="' +
  749. escHtml(msg.imageUrl) +
  750. '" alt="图片" loading="lazy" decoding="async" /></div></div>';
  751. var imageUserText = String(msg.content || "").trim();
  752. if (imageUserText) {
  753. html +=
  754. '<div class="row row--user"><div class="user-bubble">' +
  755. escHtml(imageUserText) +
  756. "</div></div>";
  757. }
  758. continue;
  759. }
  760. var userText = String(msg.content || "").trim();
  761. if (!userText) continue;
  762. html +=
  763. '<div class="row row--user"><div class="user-bubble">' +
  764. escHtml(userText) +
  765. "</div></div>";
  766. continue;
  767. }
  768. if (msg.role === "ai" || msg.role === "assistant") {
  769. var aiText = String(msg.content || "").trim();
  770. if (!aiText) continue;
  771. html +=
  772. '<div class="row row--ai"><div class="ai-card"><div class="ai-card__text">' +
  773. renderAiContentHtml(aiText) +
  774. "</div></div></div>";
  775. }
  776. }
  777. return html;
  778. }
  779. function applyWeixinShareMeta() {
  780. var siteName = "U店在哪";
  781. var iconUrl =
  782. "https://alien-volume.oss-cn-beijing.aliyuncs.com/icon/ubao.png";
  783. var setMeta = function (key, content) {
  784. var el =
  785. document.querySelector('meta[property="' + key + '"]') ||
  786. document.querySelector('meta[name="' + key + '"]');
  787. if (!el) {
  788. el = document.createElement("meta");
  789. if (key.indexOf("og:") === 0) {
  790. el.setAttribute("property", key);
  791. } else {
  792. el.setAttribute("name", key);
  793. }
  794. document.head.appendChild(el);
  795. }
  796. el.setAttribute("content", content);
  797. };
  798. setMeta("og:site_name", siteName);
  799. setMeta("application-name", siteName);
  800. setMeta("og:title", "和AI客服的对话");
  801. setMeta("og:description", "点击查看对话内容");
  802. var links = document.querySelectorAll('link[rel="icon"], link[rel="apple-touch-icon"]');
  803. for (var i = 0; i < links.length; i++) {
  804. links[i].setAttribute("href", iconUrl);
  805. }
  806. }
  807. function countDisplayableMessages(messages) {
  808. var list = Array.isArray(messages) ? messages : [];
  809. var count = 0;
  810. for (var i = 0; i < list.length; i++) {
  811. var msg = list[i];
  812. if (!msg) continue;
  813. if (msg.role === "user") {
  814. if (msg.isImage && msg.imageUrl) {
  815. count += 1;
  816. continue;
  817. }
  818. if (String(msg.content || "").trim()) count += 1;
  819. continue;
  820. }
  821. if (msg.role === "ai" || msg.role === "assistant") {
  822. if (String(msg.content || "").trim()) count += 1;
  823. }
  824. }
  825. return count;
  826. }
  827. function parseMessagesFromContent(text) {
  828. var raw = String(text || "").trim();
  829. if (!raw) return [];
  830. var list = [];
  831. var blocks = raw.split(/\n\n+/);
  832. for (var i = 0; i < blocks.length; i++) {
  833. var block = String(blocks[i] || "").trim();
  834. if (!block) continue;
  835. var userMatch = block.match(/^我[::]\s*([\s\S]*)$/);
  836. if (userMatch) {
  837. var userText = String(userMatch[1] || "").trim();
  838. if (userText) list.push({ role: "user", content: userText });
  839. continue;
  840. }
  841. var aiMatch = block.match(/^UBAO[::]\s*([\s\S]*)$/i);
  842. if (aiMatch) {
  843. var aiText = String(aiMatch[1] || "").trim();
  844. if (aiText) list.push({ role: "ai", content: aiText });
  845. }
  846. }
  847. if (list.length) return list;
  848. var current = null;
  849. var lines = raw.split(/\n/);
  850. for (var j = 0; j < lines.length; j++) {
  851. var line = String(lines[j] || "");
  852. var userLine = line.match(/^我[::]\s*(.*)$/);
  853. var aiLine = line.match(/^UBAO[::]\s*(.*)$/i);
  854. if (userLine) {
  855. if (current) list.push(current);
  856. current = { role: "user", content: String(userLine[1] || "").trim() };
  857. continue;
  858. }
  859. if (aiLine) {
  860. if (current) list.push(current);
  861. current = { role: "ai", content: String(aiLine[1] || "").trim() };
  862. continue;
  863. }
  864. if (current && line.trim()) {
  865. current.content = (current.content ? current.content + "\n" : "") + line.trim();
  866. }
  867. }
  868. if (current && String(current.content || "").trim()) list.push(current);
  869. return list;
  870. }
  871. function resolveShareMessagesForDisplay(data) {
  872. var fromArray = Array.isArray(data && data.messages) ? data.messages : [];
  873. var fromContent = parseMessagesFromContent((data && data.content) || "");
  874. var arrayCount = countDisplayableMessages(fromArray);
  875. var contentCount = countDisplayableMessages(fromContent);
  876. // 分享链接超长时 messages 会被截断,但 content 仍保留完整对话文本
  877. if (contentCount > arrayCount) return fromContent;
  878. if (arrayCount) return fromArray;
  879. return fromContent;
  880. }
  881. function render(data) {
  882. applyWeixinShareMeta();
  883. sharePayloadCache = data || null;
  884. var main = document.getElementById("main");
  885. if (!data) {
  886. main.innerHTML = '<div class="empty">对话内容不存在或链接已失效</div>';
  887. refreshWxLaunchTagAttrs();
  888. return;
  889. }
  890. var messages = resolveShareMessagesForDisplay(data);
  891. var firstQuestion =
  892. String(data.firstQuestion || "").trim() ||
  893. getFirstUserQuestion(messages) ||
  894. (function () {
  895. var text = String(data.content || "").trim();
  896. var m = text.match(/^我[::]([\s\S]+?)(?:\n\n|$)/);
  897. return m ? String(m[1] || "").trim() : "";
  898. })();
  899. var pageTitle = formatDiscussionTitle(firstQuestion);
  900. var dateText = formatDate(resolveDisplayShareTime(data));
  901. document.title = pageTitle;
  902. var bodyHtml =
  903. '<section class="hero">' +
  904. '<h1 class="hero__title">' +
  905. escHtml(pageTitle) +
  906. "</h1>" +
  907. '<p class="hero__meta">' +
  908. escHtml(dateText) +
  909. " · 内容由AI生成,不能完全保障真实</p>" +
  910. '<div class="hero__divider"></div>' +
  911. "</section>";
  912. var convHtml = renderMessages(messages);
  913. if (convHtml) {
  914. bodyHtml +=
  915. '<section class="conversation">' +
  916. convHtml +
  917. '</section><div class="scroll-spacer" aria-hidden="true"></div>';
  918. } else {
  919. bodyHtml += '<div class="empty">暂无对话内容</div>';
  920. }
  921. main.innerHTML = bodyHtml;
  922. refreshWxLaunchTagAttrs();
  923. }
  924. function buildAiConsultOpenParams() {
  925. var params = new URLSearchParams();
  926. params.set("fromShareAiKfChat", "1");
  927. return params;
  928. }
  929. function buildAppDeepLink() {
  930. var path = APP_UNI_AI_PATH;
  931. var qs = buildAiConsultOpenParams().toString();
  932. var root = APP_IOS_URL_SCHEME.replace(/\/$/, "");
  933. return root + "/" + path + (qs ? "?" + qs : "");
  934. }
  935. function buildWeChatLaunchExtinfo(useBarePathOnly) {
  936. var path = APP_UNI_AI_PATH.replace(/^\//, "");
  937. if (useBarePathOnly) return path;
  938. var qs = buildAiConsultOpenParams().toString();
  939. var uniPage = qs ? path + "?" + qs : path;
  940. if (uniPage.length <= 1024) return uniPage;
  941. return path + "?fromShareAiKfChat=1";
  942. }
  943. function isWeChatInAppBrowser() {
  944. return /MicroMessenger/i.test(navigator.userAgent || "");
  945. }
  946. function getWxShareEntryFrom() {
  947. var from = q("from");
  948. if (from) return String(from).trim().toLowerCase();
  949. try {
  950. var h = location.hash || "";
  951. var qi = h.indexOf("?");
  952. if (qi >= 0) {
  953. var hf = new URLSearchParams(h.slice(qi + 1)).get("from");
  954. if (hf) return String(hf).trim().toLowerCase();
  955. }
  956. } catch (eH) {}
  957. return "";
  958. }
  959. function logWxEntryDiagnostics() {
  960. if (!isWeChatInAppBrowser()) return;
  961. console.log("[wx-entry]", {
  962. entryFrom: getWxShareEntryFrom() || "(无)",
  963. wxJssdkReady: weChatJssdkConfigured,
  964. signUrl: getWxConfigSignUrl(),
  965. });
  966. }
  967. function isIOSWeChatBrowser() {
  968. var ua = navigator.userAgent || "";
  969. return /MicroMessenger/i.test(ua) && /iPhone|iPad|iPod/i.test(ua);
  970. }
  971. function isWxDebugOn() {
  972. return q("wxDebug") === "1";
  973. }
  974. function isWxForceDebug() {
  975. return q("wxForce") === "1";
  976. }
  977. function isWxConfigOnClickDebug() {
  978. return q("wxConfigOnClick") === "1";
  979. }
  980. function isWxPcAutoDebugHost() {
  981. var h = (location.hostname || "").toLowerCase();
  982. if (h === "localhost" || h === "127.0.0.1") return true;
  983. for (var i = 0; i < WECHAT_JS_SAFE_HOSTS.length; i++) {
  984. if (WECHAT_JS_SAFE_HOSTS[i] === h) return true;
  985. }
  986. return false;
  987. }
  988. function isWxPcBrowser() {
  989. return !isWeChatInAppBrowser();
  990. }
  991. function shouldInitWeChatJssdkOnLoad() {
  992. if (isWeChatInAppBrowser()) return true;
  993. return isWxForceDebug() || isWxPcAutoDebugHost();
  994. }
  995. function shouldFetchWxConfig(fromUserClick) {
  996. if (isWeChatInAppBrowser()) return true;
  997. if (fromUserClick) return true;
  998. return isWxForceDebug() || isWxPcAutoDebugHost();
  999. }
  1000. function getWxHtmlUrl() {
  1001. var forced = String(q("wxSignUrl") || "").trim();
  1002. if (forced) return forced.split("#")[0];
  1003. return String(location.href || "").split("#")[0];
  1004. }
  1005. function getWxSignPageUrlForApi() {
  1006. var htmlUrl = getWxHtmlUrl();
  1007. if (htmlUrl && /^https?:\/\//i.test(htmlUrl)) return htmlUrl;
  1008. return WX_GET_CONFIG_SIGN_URL;
  1009. }
  1010. function getWxHtmlUrlBase() {
  1011. var htmlUrl = getWxSignPageUrlForApi();
  1012. try {
  1013. var u = new URL(htmlUrl);
  1014. return u.origin + u.pathname;
  1015. } catch (eU) {
  1016. return WX_GET_CONFIG_SIGN_URL;
  1017. }
  1018. }
  1019. /** 与 secondShareGoods 一致:默认用当前页完整 URL 验签(须与微信地址栏一致,含 query) */
  1020. function getWxConfigSignUrl() {
  1021. if (String(q("wxSignBaseOnly") || "") === "1") return getWxHtmlUrlBase();
  1022. return getWxSignPageUrlForApi();
  1023. }
  1024. function getWxGetConfigApiUrl() {
  1025. return API_BASE.replace(/\/$/, "") + WECHAT_GET_WX_CONFIG_PATH;
  1026. }
  1027. function buildWxGetConfigRequestBody(htmlUrl) {
  1028. return {
  1029. url: String(htmlUrl || "").split("#")[0].trim(),
  1030. };
  1031. }
  1032. function resolveWxConfigAppIdFromSignData(d) {
  1033. if (!d || typeof d !== "object") return "";
  1034. var mp =
  1035. d.mpAppId ||
  1036. d.mpAppid ||
  1037. d.officialAppId ||
  1038. d.gzhAppId ||
  1039. d.serviceAppId;
  1040. if (mp != null && String(mp).trim() !== "") return String(mp).trim();
  1041. var fromQuery = String(q("wxMpAppId") || WECHAT_MP_APP_ID || "").trim();
  1042. if (fromQuery) return fromQuery;
  1043. var raw = d.appId || d.appid || d.wxAppId;
  1044. return raw != null && String(raw).trim() !== "" ? String(raw).trim() : "";
  1045. }
  1046. function normalizeWxJssdkSignPayload(res, signUrlUsed) {
  1047. if (!res || typeof res !== "object") return null;
  1048. var d = res.data != null && typeof res.data === "object" ? res.data : res;
  1049. if (!d || typeof d !== "object") return null;
  1050. var appId = resolveWxConfigAppIdFromSignData(d);
  1051. var timestamp = d.timestamp != null ? d.timestamp : d.timeStamp;
  1052. var nonceStr =
  1053. d.nonceStr != null && String(d.nonceStr) !== ""
  1054. ? d.nonceStr
  1055. : d.noncestr != null && String(d.noncestr) !== ""
  1056. ? d.noncestr
  1057. : d.nonce;
  1058. var signature = d.signature || d.sign;
  1059. if (!appId || timestamp == null || nonceStr == null || nonceStr === "" || !signature) {
  1060. return null;
  1061. }
  1062. return {
  1063. appId: String(appId),
  1064. timestamp: Number(timestamp),
  1065. nonceStr: String(nonceStr),
  1066. signature: String(signature),
  1067. signUrl: String(signUrlUsed || "")
  1068. .split("#")[0]
  1069. .trim(),
  1070. };
  1071. }
  1072. function getWxErrMsg(err) {
  1073. if (!err) return "";
  1074. if (err.errMsg) return String(err.errMsg);
  1075. if (typeof err === "string") return err;
  1076. try {
  1077. return JSON.stringify(err);
  1078. } catch (e) {
  1079. return String(err);
  1080. }
  1081. }
  1082. function formatWxConfigErrorTip(err, signPageUrl) {
  1083. var errMsg = getWxErrMsg(err);
  1084. var tip = "微信 JSSDK 配置失败";
  1085. if (/invalid signature/i.test(errMsg)) {
  1086. return (
  1087. tip +
  1088. ":签名无效。请核对:①后端用与前端相同的 url 签名;②url=" +
  1089. (signPageUrl || getWxHtmlUrl()) +
  1090. ";③nonceStr/timestamp 与接口返回一致;④appId=" +
  1091. WECHAT_MP_APP_ID
  1092. );
  1093. }
  1094. if (/require\s*subscribe/i.test(errMsg)) {
  1095. return tip + ":" + errMsg + "(服务号需用户已关注)";
  1096. }
  1097. return errMsg ? tip + ":" + errMsg : tip;
  1098. }
  1099. function setWxInitError(msg) {
  1100. wxInitLastError = String(msg || "").trim();
  1101. if (wxInitLastError) console.warn("[wx]", wxInitLastError);
  1102. }
  1103. function requestWeChatJssdkSignAndConfig(htmlUrlOptional) {
  1104. var htmlUrl = String(htmlUrlOptional != null ? htmlUrlOptional : getWxConfigSignUrl())
  1105. .split("#")[0]
  1106. .trim();
  1107. if (!htmlUrl || !/^https?:\/\//i.test(htmlUrl)) {
  1108. htmlUrl = WX_GET_CONFIG_SIGN_URL;
  1109. }
  1110. if (isWxDebugOn()) {
  1111. try {
  1112. window.alert("htmlUrl(签名用,应与地址栏一致):\n" + htmlUrl);
  1113. } catch (eDbg) {}
  1114. }
  1115. var requestUrl = getWxGetConfigApiUrl();
  1116. var requestBody = buildWxGetConfigRequestBody(htmlUrl);
  1117. console.log("[wx] htmlUrl=", htmlUrl);
  1118. console.log("[wx] POST getWxConfig →", requestUrl, requestBody);
  1119. return fetch(requestUrl, {
  1120. method: "POST",
  1121. mode: "cors",
  1122. credentials: "omit",
  1123. headers: {
  1124. Accept: "application/json",
  1125. "Content-Type": "application/json;charset=UTF-8",
  1126. },
  1127. body: JSON.stringify(requestBody),
  1128. })
  1129. .then(function (r) {
  1130. if (r.ok) return r.json();
  1131. return r
  1132. .text()
  1133. .catch(function () {
  1134. return "";
  1135. })
  1136. .then(function (text) {
  1137. var hint = "";
  1138. try {
  1139. var j = JSON.parse(text);
  1140. hint = j.msg || j.message || "";
  1141. } catch (eP) {
  1142. if (text) hint = text.slice(0, 120);
  1143. }
  1144. throw new Error("getWxConfig HTTP " + r.status + (hint ? ":" + hint : ""));
  1145. });
  1146. })
  1147. .then(function (res) {
  1148. if (res && res.code != null) {
  1149. var c = Number(res.code);
  1150. if (c !== 200 && c !== 0 && res.success !== true) {
  1151. throw new Error(res.msg || res.message || "getWxConfig code " + c);
  1152. }
  1153. }
  1154. var sign = normalizeWxJssdkSignPayload(res, htmlUrl);
  1155. if (!sign) {
  1156. console.warn("[wx] getWxConfig 响应字段不全", res, "htmlUrl=", htmlUrl);
  1157. throw new Error("getWxConfig 缺少 appId/timestamp/nonceStr/signature(见控制台)");
  1158. }
  1159. if (sign.appId !== WECHAT_MP_APP_ID) {
  1160. console.warn(
  1161. "[wx] 后端 appId=" + sign.appId + ",期望服务号 " + WECHAT_MP_APP_ID
  1162. );
  1163. }
  1164. if (typeof wx === "undefined") {
  1165. if (isWxPcBrowser()) {
  1166. console.log("[wx] PC getWxConfig 成功(无 jweixin)", sign);
  1167. return true;
  1168. }
  1169. setWxInitError("jweixin.js 未加载");
  1170. return false;
  1171. }
  1172. return applyWxConfigFromSign(sign, htmlUrl);
  1173. });
  1174. }
  1175. function applyWxConfigFromSign(sign, htmlUrl) {
  1176. var wxConfigParams = {
  1177. debug: isWxDebugOn(),
  1178. appId: String(sign.appId),
  1179. timestamp: sign.timestamp,
  1180. nonceStr: String(sign.nonceStr),
  1181. signature: String(sign.signature),
  1182. jsApiList: [],
  1183. openTagList: ["wx-open-launch-app"],
  1184. };
  1185. return new Promise(function (resolve) {
  1186. wx.config(wxConfigParams);
  1187. wx.ready(function () {
  1188. weChatJssdkConfigured = true;
  1189. document.body.classList.add("wx-jssdk-ready");
  1190. refreshWxLaunchTagAttrs();
  1191. console.log("[wx.config] ready, htmlUrl=", htmlUrl);
  1192. resolve(true);
  1193. });
  1194. wx.error(function (err) {
  1195. weChatJssdkConfigured = false;
  1196. document.body.classList.remove("wx-jssdk-ready");
  1197. wxJssdkInitPromise = null;
  1198. var errMsg = getWxErrMsg(err);
  1199. setWxInitError(formatWxConfigErrorTip(err, htmlUrl));
  1200. if (isWxDebugOn()) window.alert(wxInitLastError);
  1201. console.warn("[wx.config]", errMsg, "htmlUrl=", htmlUrl);
  1202. var baseUrl = getWxHtmlUrlBase();
  1203. var fullUrl = getWxSignPageUrlForApi();
  1204. if (
  1205. !/invalid signature/i.test(errMsg) ||
  1206. wxConfigSignRetriedBaseUrl ||
  1207. baseUrl === fullUrl ||
  1208. htmlUrl === baseUrl
  1209. ) {
  1210. resolve(false);
  1211. return;
  1212. }
  1213. wxConfigSignRetriedBaseUrl = true;
  1214. requestWeChatJssdkSignAndConfig(baseUrl).then(resolve);
  1215. });
  1216. });
  1217. }
  1218. function refreshWxLaunchTagAttrs(useBarePathOnly) {
  1219. var tag = document.getElementById("launch-btn");
  1220. if (!tag) return;
  1221. try {
  1222. tag.setAttribute("appid", WECHAT_OPEN_APP_ID);
  1223. tag.setAttribute("extinfo", buildWeChatLaunchExtinfo(!!useBarePathOnly));
  1224. console.log("[wx-open-launch-app] extinfo=", tag.getAttribute("extinfo"));
  1225. } catch (eA) {}
  1226. }
  1227. function bindWeChatLaunchTagEvents() {
  1228. var tag = document.getElementById("launch-btn");
  1229. if (!tag || tag._wxLaunchBound) return;
  1230. tag._wxLaunchBound = true;
  1231. refreshWxLaunchTagAttrs();
  1232. tag.addEventListener("launch", function () {
  1233. console.log("[wx-open-launch-app] launch ok");
  1234. });
  1235. tag.addEventListener("error", function (e) {
  1236. var detail = e && e.detail;
  1237. var errMsg =
  1238. detail && detail.errMsg
  1239. ? String(detail.errMsg)
  1240. : detail && detail.errmsg
  1241. ? String(detail.errmsg)
  1242. : "";
  1243. console.warn(
  1244. "[wx-open-launch-app]",
  1245. detail,
  1246. "extinfo=",
  1247. tag.getAttribute("extinfo")
  1248. );
  1249. if (/launch:fail_check/i.test(errMsg)) {
  1250. showAppOpenFailTip(
  1251. "请用微信分享卡片进入,或确认已安装最新版「U店在哪」"
  1252. );
  1253. return;
  1254. }
  1255. // if (
  1256. // /launch:fail/i.test(errMsg) &&
  1257. // !tag._wxLaunchBareRetried &&
  1258. // tag.getAttribute("extinfo") !== buildWeChatLaunchExtinfo(true)
  1259. // ) {
  1260. // tag._wxLaunchBareRetried = true;
  1261. // refreshWxLaunchTagAttrs(true);
  1262. // showFabToast("请再点一次「和U宝继续聊」");
  1263. // return;
  1264. // }
  1265. if (/launch:fail/i.test(errMsg) && !getWxShareEntryFrom()) {
  1266. showAppOpenFailTip("请前往应用商店下载U店在哪app");
  1267. return;
  1268. }
  1269. showAppOpenFailTip(
  1270. errMsg
  1271. ? "未能打开 App:" + errMsg
  1272. : "未能打开 App,请确认已安装最新版「U店在哪」"
  1273. );
  1274. });
  1275. }
  1276. function initWeChatOpenLaunchApp(fromUserClick) {
  1277. if (!shouldFetchWxConfig(!!fromUserClick)) {
  1278. return Promise.resolve(false);
  1279. }
  1280. if (wxJssdkInitPromise && !fromUserClick) return wxJssdkInitPromise;
  1281. wxConfigSignRetriedBaseUrl = false;
  1282. wxInitLastError = "";
  1283. var htmlUrl = getWxConfigSignUrl();
  1284. bindWeChatLaunchTagEvents();
  1285. wxJssdkInitPromise = requestWeChatJssdkSignAndConfig(htmlUrl)
  1286. .then(function (ok) {
  1287. if (ok === true) return true;
  1288. if (!wxInitLastError) {
  1289. setWxInitError("wx.config 失败,可加 ?wxDebug=1 查看 htmlUrl");
  1290. }
  1291. return false;
  1292. })
  1293. .catch(function (e) {
  1294. var msg = e && e.message ? e.message : "getWxConfig 请求失败";
  1295. setWxInitError(msg);
  1296. console.warn("[wx] requestWeChatJssdkSignAndConfig failed", msg, "htmlUrl=", htmlUrl);
  1297. if (isWeChatInAppBrowser() && isWxDebugOn()) window.alert(msg);
  1298. return false;
  1299. })
  1300. .finally(function () {
  1301. if (!weChatJssdkConfigured) wxJssdkInitPromise = null;
  1302. });
  1303. return wxJssdkInitPromise;
  1304. }
  1305. function scheduleWeChatJssdkBootstrap() {
  1306. if (!shouldInitWeChatJssdkOnLoad()) return;
  1307. var attempts = 0;
  1308. function tick() {
  1309. attempts += 1;
  1310. if (weChatJssdkConfigured) return;
  1311. initWeChatOpenLaunchApp();
  1312. if (!weChatJssdkConfigured && attempts < 8 && typeof wx === "undefined") {
  1313. setTimeout(tick, 400);
  1314. }
  1315. }
  1316. if (isIOSWeChatBrowser()) {
  1317. setTimeout(tick, 350);
  1318. } else {
  1319. tick();
  1320. }
  1321. }
  1322. function showFabToast(msg, ms) {
  1323. var tip = String(msg || "").trim();
  1324. if (!tip) return;
  1325. var el = document.getElementById("openAppToast");
  1326. if (el) {
  1327. el.textContent = tip;
  1328. el.style.display = "block";
  1329. if (showFabToast._t) clearTimeout(showFabToast._t);
  1330. showFabToast._t = setTimeout(function () {
  1331. el.style.display = "none";
  1332. }, ms || 2800);
  1333. }
  1334. console.log("[openApp]", tip);
  1335. }
  1336. function showDownloadTip() {
  1337. var msg = "请到应用商店下载「U店在哪」";
  1338. if (typeof uni !== "undefined" && typeof uni.showToast === "function") {
  1339. uni.showToast({ title: msg, icon: "none", duration: 2500 });
  1340. } else {
  1341. window.alert(msg);
  1342. }
  1343. }
  1344. function showAppOpenFailTip(msg) {
  1345. var tip = msg || "未能打开 App,请确认已安装最新版「U店在哪」。";
  1346. if (typeof uni !== "undefined" && typeof uni.showToast === "function") {
  1347. uni.showToast({ title: msg, icon: "none", duration: 2800 });
  1348. } else if (isWeChatInAppBrowser()) {
  1349. window.alert(tip);
  1350. } else {
  1351. showFabToast(tip);
  1352. }
  1353. }
  1354. function launchAppDeepLink(deepLink) {
  1355. try {
  1356. var a = document.createElement("a");
  1357. a.href = deepLink;
  1358. a.setAttribute("target", "_self");
  1359. document.body.appendChild(a);
  1360. a.click();
  1361. document.body.removeChild(a);
  1362. } catch (e1) {}
  1363. try {
  1364. window.location.href = deepLink;
  1365. } catch (e2) {}
  1366. }
  1367. function tryOpenHBuilderAppViaScheme() {
  1368. var deepLink = buildAppDeepLink();
  1369. if (typeof plus !== "undefined" && plus.runtime) {
  1370. var installed = null;
  1371. try {
  1372. if (typeof plus.runtime.isApplicationExist === "function") {
  1373. installed = plus.runtime.isApplicationExist({
  1374. pname: APP_ANDROID_PACKAGE,
  1375. action: APP_IOS_URL_SCHEME,
  1376. });
  1377. }
  1378. } catch (e) {
  1379. console.warn(e);
  1380. }
  1381. if (installed === false) {
  1382. showDownloadTip();
  1383. return;
  1384. }
  1385. try {
  1386. plus.runtime.openURL(deepLink);
  1387. } catch (e2) {
  1388. console.warn(e2);
  1389. showDownloadTip();
  1390. }
  1391. return;
  1392. }
  1393. var done = false;
  1394. function finish() {
  1395. if (done) return;
  1396. done = true;
  1397. document.removeEventListener("visibilitychange", onVis);
  1398. window.removeEventListener("pagehide", onHide);
  1399. }
  1400. function onVis() {
  1401. if (document.visibilityState === "hidden") finish();
  1402. }
  1403. function onHide() {
  1404. finish();
  1405. }
  1406. document.addEventListener("visibilitychange", onVis);
  1407. window.addEventListener("pagehide", onHide);
  1408. try {
  1409. launchAppDeepLink(deepLink);
  1410. } catch (e3) {
  1411. finish();
  1412. showDownloadTip();
  1413. return;
  1414. }
  1415. window.setTimeout(function () {
  1416. finish();
  1417. }, 3200);
  1418. }
  1419. function tryFetchWxConfigOnPcClick() {
  1420. if (!isWxPcBrowser()) return Promise.resolve(false);
  1421. showFabToast("正在请求 getWxConfig…");
  1422. wxJssdkInitPromise = null;
  1423. return initWeChatOpenLaunchApp(true).then(function (ok) {
  1424. if (ok) {
  1425. showFabToast(
  1426. weChatJssdkConfigured
  1427. ? "getWxConfig 成功,wx.config 已就绪"
  1428. : "getWxConfig 成功"
  1429. );
  1430. } else {
  1431. showFabToast(wxInitLastError || "getWxConfig 失败");
  1432. }
  1433. return ok;
  1434. });
  1435. }
  1436. function tryOpenHBuilderApp() {
  1437. if (isWeChatInAppBrowser()) return;
  1438. if (!isWxPcBrowser()) {
  1439. tryOpenHBuilderAppViaScheme();
  1440. return;
  1441. }
  1442. tryFetchWxConfigOnPcClick().then(function () {
  1443. if (isWxConfigOnClickDebug() && !isWxForceDebug() && !isWxPcAutoDebugHost()) {
  1444. return;
  1445. }
  1446. tryOpenHBuilderAppViaScheme();
  1447. });
  1448. }
  1449. function boot() {
  1450. var launchTag = document.getElementById("launch-btn");
  1451. if (launchTag) launchTag.setAttribute("appid", WECHAT_OPEN_APP_ID);
  1452. bindWeChatLaunchTagEvents();
  1453. if (isWeChatInAppBrowser()) {
  1454. document.body.classList.add("is-wechat");
  1455. logWxEntryDiagnostics();
  1456. }
  1457. if (shouldInitWeChatJssdkOnLoad()) {
  1458. if (isWxPcBrowser() && (isWxForceDebug() || isWxPcAutoDebugHost())) {
  1459. document.body.classList.add("wx-pc-debug");
  1460. }
  1461. scheduleWeChatJssdkBootstrap();
  1462. }
  1463. document.addEventListener("WeixinOpenTagsError", function (e) {
  1464. console.warn("[WeixinOpenTagsError]", e && e.detail);
  1465. });
  1466. if (isWeChatInAppBrowser()) {
  1467. var openBtnWx = document.getElementById("openApp");
  1468. if (openBtnWx) {
  1469. openBtnWx.addEventListener("click", function () {
  1470. if (!weChatJssdkConfigured) {
  1471. showFabToast(
  1472. wxInitLastError || "微信 SDK 初始化中,请稍候再点底部按钮"
  1473. );
  1474. }
  1475. });
  1476. }
  1477. } else {
  1478. var openAppBtn = document.getElementById("openApp");
  1479. if (openAppBtn) {
  1480. openAppBtn.addEventListener("click", tryOpenHBuilderApp);
  1481. }
  1482. }
  1483. loadPageData();
  1484. }
  1485. if (document.readyState === "complete") {
  1486. boot();
  1487. } else {
  1488. window.addEventListener("load", boot);
  1489. }
  1490. })();
  1491. </script>
  1492. </body>
  1493. </html>