shareAiConsult.html 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702
  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>与U宝对话</title>
  8. <meta property="og:title" content="和U宝的对话">
  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="和U宝继续聊">
  285. <span class="fab__brand-clip" aria-hidden="true">
  286. <img class="fab__brand-img" src="images/uCharts.png" alt="和U宝继续聊" 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="和U宝继续聊">
  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="和U宝继续聊" 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 + "shareAiConsult.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/aiSearchResult/index";
  349. var AI_LEGAL_CONVERSATION_API =
  350. "https://prod.ailien.shop/ai/life-manager/api/v1/legal-consultation/history/conversation";
  351. var AI_UBAO_CONVERSATION_API =
  352. "https://prod.ailien.shop/ai/life-manager/api/v1/ubao-conversation/history/conversation";
  353. var AI_CS_CONVERSATION_API =
  354. "https://prod.ailien.shop/ai/life-manager/api/v1/udian-cs-conversation/history/conversation";
  355. var sharePayloadCache = null;
  356. var weChatJssdkConfigured = false;
  357. var wxConfigSignRetriedBaseUrl = false;
  358. var wxInitLastError = "";
  359. var wxJssdkInitPromise = null;
  360. function escHtml(s) {
  361. return String(s || "")
  362. .replace(/&/g, "&amp;")
  363. .replace(/</g, "&lt;")
  364. .replace(/>/g, "&gt;")
  365. .replace(/"/g, "&quot;");
  366. }
  367. var IMAGE_EXT = "(?:jpe?g|png|gif|webp|bmp|avif)";
  368. var IMAGE_URL_PATTERN =
  369. "https?:\\/\\/[^\\s))\\]]+\\." + IMAGE_EXT + "(?:\\?[^\\s))\\]]*)?";
  370. function isInsideImageUrlSyntax(full, offset) {
  371. if (offset >= 2 && full.slice(offset - 2, offset) === "](") return true;
  372. if (offset >= 1 && full[offset - 1] === "(") return true;
  373. if (offset >= 6 && full.slice(offset - 6, offset) === "{{IMG|") return true;
  374. return false;
  375. }
  376. /** AI 回复常见:店名(https://...jpg) — 转为可渲染的图片占位 */
  377. function embedInlineImageUrls(text) {
  378. if (text == null) return "";
  379. var t = String(text);
  380. t = t.replace(
  381. new RegExp("([^\\n((]+?)\\((" + IMAGE_URL_PATTERN + ")\\)", "gi"),
  382. function (_, label, url) {
  383. var name = String(label).trim();
  384. if (!name) return "\n\n{{IMG|" + url + "|}}\n\n";
  385. var alt = name.length > 24 ? "图片" : name.replace(/[\[\]]/g, "");
  386. return name + "\n\n{{IMG|" + url + "|" + alt + "}}\n\n";
  387. }
  388. );
  389. t = t.replace(
  390. new RegExp("\\((" + IMAGE_URL_PATTERN + ")\\)", "gi"),
  391. function (_, url) {
  392. return "\n\n{{IMG|" + url + "|}}\n\n";
  393. }
  394. );
  395. t = t.replace(new RegExp(IMAGE_URL_PATTERN, "gi"), function (url, offset, full) {
  396. if (isInsideImageUrlSyntax(full, offset)) return url;
  397. return "\n\n{{IMG|" + url + "|}}\n\n";
  398. });
  399. return t.replace(/\n{3,}/g, "\n\n");
  400. }
  401. function formatTextBlockHtml(text) {
  402. return escHtml(text).replace(/\n/g, "<br>");
  403. }
  404. function buildAiImageTag(url, alt) {
  405. var safeUrl = escHtml(url);
  406. var safeAlt = escHtml(alt || "图片");
  407. return (
  408. '<img class="ai-card__image" src="' +
  409. safeUrl +
  410. '" alt="' +
  411. safeAlt +
  412. '" loading="lazy" decoding="async" />'
  413. );
  414. }
  415. function renderAiContentHtml(text) {
  416. var t = embedInlineImageUrls(text);
  417. var html = "";
  418. var tokenRe = /\{\{IMG\|([^|]+)\|([^}]*)\}\}/g;
  419. var lastIndex = 0;
  420. var match;
  421. while ((match = tokenRe.exec(t)) !== null) {
  422. if (match.index > lastIndex) {
  423. html += formatTextBlockHtml(t.slice(lastIndex, match.index));
  424. }
  425. html += buildAiImageTag(match[1], match[2]);
  426. lastIndex = tokenRe.lastIndex;
  427. }
  428. if (lastIndex < t.length) {
  429. html += formatTextBlockHtml(t.slice(lastIndex));
  430. }
  431. return html;
  432. }
  433. function q(name) {
  434. try {
  435. var v = new URLSearchParams(location.search || "").get(name);
  436. return v == null ? "" : String(v);
  437. } catch (e) {
  438. return "";
  439. }
  440. }
  441. function getQueryParam(name) {
  442. var m = new RegExp("[?&]" + name + "=([^&]*)").exec(window.location.search);
  443. if (!m) return "";
  444. try {
  445. return decodeURIComponent(m[1].replace(/\+/g, " "));
  446. } catch (e) {
  447. return "";
  448. }
  449. }
  450. function parsePayload() {
  451. var raw = getQueryParam("payload");
  452. if (!raw) return null;
  453. try {
  454. return JSON.parse(raw);
  455. } catch (e) {
  456. return null;
  457. }
  458. }
  459. function getConversationQueryParams() {
  460. var sessionId = String(q("session_id") || q("sessionId") || "").trim();
  461. var userId = String(q("user_id") || q("userId") || "").trim();
  462. var type = String(q("type") || "").trim();
  463. if (!sessionId || !userId) return null;
  464. return { sessionId: sessionId, userId: userId, type: type };
  465. }
  466. function parseMessageIdsFromQuery() {
  467. var raw = String(q("message_ids") || q("messageIds") || "").trim();
  468. if (!raw) return null;
  469. return raw
  470. .split(",")
  471. .map(function (s) {
  472. return String(s || "").trim();
  473. })
  474. .filter(Boolean);
  475. }
  476. function normalizeHistoryRowImageUrls(item) {
  477. var raw = item.image_urls || item.imageUrls || item.images;
  478. if (Array.isArray(raw)) {
  479. return raw
  480. .map(function (u) {
  481. return String(u || "").trim();
  482. })
  483. .filter(Boolean);
  484. }
  485. if (typeof raw === "string" && raw.trim()) {
  486. return raw
  487. .split(",")
  488. .map(function (s) {
  489. return s.trim();
  490. })
  491. .filter(Boolean);
  492. }
  493. return [];
  494. }
  495. function filterConversationMessagesByIds(messages, idList) {
  496. if (!Array.isArray(idList) || !idList.length) return messages;
  497. var idSet = {};
  498. for (var i = 0; i < idList.length; i++) {
  499. idSet[String(idList[i])] = true;
  500. }
  501. return (Array.isArray(messages) ? messages : []).filter(function (msg) {
  502. if (!msg || msg.id == null || msg.id === "") return false;
  503. return !!idSet[String(msg.id)];
  504. });
  505. }
  506. function getSharePageType() {
  507. return String(q("type") || "").trim();
  508. }
  509. /** type=1 U宝;type=0 AI客服;其它(如 2)法律U宝 */
  510. function getShareBrandByType(type) {
  511. var t = String(type || "").trim();
  512. if (t === "0") {
  513. return {
  514. ogTitle: "和AI客服的对话",
  515. ogDescription: "点击查看对话内容",
  516. appPath: "pages/aiKfChat/index",
  517. pageType: "",
  518. fabLabel: "和AI客服继续聊",
  519. };
  520. }
  521. if (t === "2") {
  522. return {
  523. ogTitle: "和法律U宝的对话",
  524. ogDescription: "点击查看对话内容",
  525. appPath: "pages/lawyer/index",
  526. pageType: "",
  527. fabLabel: "和法律U宝继续聊",
  528. };
  529. }
  530. return {
  531. ogTitle: "和U宝的对话",
  532. ogDescription: "点击查看对话内容",
  533. appPath: "pages/aiSearchResult/index",
  534. pageType: "home",
  535. fabLabel: "和U宝继续聊",
  536. };
  537. }
  538. function getConversationApiBase(type) {
  539. var t = String(type || "").trim();
  540. if (t === "1") return AI_UBAO_CONVERSATION_API;
  541. if (t === "0") return AI_CS_CONVERSATION_API;
  542. return AI_LEGAL_CONVERSATION_API;
  543. }
  544. function buildConversationApiUrl(sessionId, userId, type) {
  545. var params = new URLSearchParams();
  546. params.set("session_id", sessionId);
  547. params.set("user_id", userId);
  548. if (String(type || "").trim() === "0") {
  549. params.set("client_type", "0");
  550. }
  551. return getConversationApiBase(type) + "?" + params.toString();
  552. }
  553. function normalizeConversationRole(raw) {
  554. var role = String(raw || "").trim().toLowerCase();
  555. if (
  556. role === "user" ||
  557. role === "human" ||
  558. role === "customer" ||
  559. role === "question" ||
  560. role === "1" ||
  561. role === "我"
  562. ) {
  563. return "user";
  564. }
  565. if (
  566. role === "ai" ||
  567. role === "assistant" ||
  568. role === "bot" ||
  569. role === "ubao" ||
  570. role === "answer" ||
  571. role === "2" ||
  572. role === "system"
  573. ) {
  574. return "ai";
  575. }
  576. return "";
  577. }
  578. function normalizeConversationApiPayload(res) {
  579. if (!res || typeof res !== "object") return null;
  580. if (res.code != null) {
  581. var code = Number(res.code);
  582. if (code !== 200 && code !== 0 && res.success !== true) {
  583. throw new Error(res.msg || res.message || "对话接口返回 code " + code);
  584. }
  585. }
  586. var root = res.data != null && typeof res.data === "object" ? res.data : res;
  587. var rawList =
  588. (Array.isArray(root) && root) ||
  589. (Array.isArray(root.messages) && root.messages) ||
  590. (Array.isArray(root.messageList) && root.messageList) ||
  591. (Array.isArray(root.conversation) && root.conversation) ||
  592. (Array.isArray(root.conversations) && root.conversations) ||
  593. (Array.isArray(root.records) && root.records) ||
  594. (Array.isArray(root.list) && root.list) ||
  595. null;
  596. if (!rawList) return null;
  597. var messages = [];
  598. for (var i = 0; i < rawList.length; i++) {
  599. var item = rawList[i];
  600. if (!item || typeof item !== "object") continue;
  601. var msgId = item.id != null ? item.id : item.message_id;
  602. var role = normalizeConversationRole(
  603. item.role || item.sender || item.messageRole || item.type || item.messageType || item.senderType
  604. );
  605. var content = String(
  606. item.content != null
  607. ? item.content
  608. : item.message != null
  609. ? item.message
  610. : item.text != null
  611. ? item.text
  612. : ""
  613. ).trim();
  614. if (!role && item.question) {
  615. role = "user";
  616. content = String(item.question).trim();
  617. } else if (!role && item.answer) {
  618. role = "ai";
  619. content = String(item.answer).trim();
  620. } else if (!role && item.userMessage) {
  621. role = "user";
  622. content = String(item.userMessage).trim();
  623. } else if (!role && (item.aiMessage || item.assistantMessage)) {
  624. role = "ai";
  625. content = String(item.aiMessage || item.assistantMessage).trim();
  626. }
  627. var imageUrls = normalizeHistoryRowImageUrls(item);
  628. if (imageUrls.length) {
  629. messages.push({
  630. id: msgId,
  631. role: role || "user",
  632. isImage: true,
  633. imageUrl: imageUrls[0],
  634. content: content,
  635. });
  636. continue;
  637. }
  638. if (!content) continue;
  639. var imageUrl = item.imageUrl || item.image || item.imgUrl || item.url;
  640. if (imageUrl && /^(https?:)?\/\//i.test(String(imageUrl))) {
  641. messages.push({
  642. id: msgId,
  643. role: role || "user",
  644. isImage: true,
  645. imageUrl: String(imageUrl),
  646. });
  647. continue;
  648. }
  649. messages.push({
  650. id: msgId,
  651. role: role || (messages.length % 2 === 0 ? "user" : "ai"),
  652. content: content,
  653. });
  654. }
  655. if (!messages.length) return null;
  656. return {
  657. messages: messages,
  658. shareTime:
  659. root.shareTime ||
  660. root.createdAt ||
  661. root.createTime ||
  662. root.updateTime ||
  663. root.timestamp ||
  664. res.timestamp,
  665. firstQuestion: root.firstQuestion || root.title || root.topic || "",
  666. sessionId: root.sessionId || root.session_id || "",
  667. userId: root.userId || root.user_id || "",
  668. };
  669. }
  670. function fetchConversationHistory(sessionId, userId, type) {
  671. var requestUrl = buildConversationApiUrl(sessionId, userId, type);
  672. console.log("[conversation-api] GET", requestUrl);
  673. return fetch(requestUrl, {
  674. method: "GET",
  675. mode: "cors",
  676. credentials: "omit",
  677. headers: { Accept: "application/json" },
  678. })
  679. .then(function (r) {
  680. if (r.ok) return r.json();
  681. return r
  682. .text()
  683. .catch(function () {
  684. return "";
  685. })
  686. .then(function (text) {
  687. var hint = "";
  688. try {
  689. var j = JSON.parse(text);
  690. hint = j.msg || j.message || "";
  691. } catch (eP) {
  692. if (text) hint = text.slice(0, 120);
  693. }
  694. throw new Error("对话接口 HTTP " + r.status + (hint ? ":" + hint : ""));
  695. });
  696. })
  697. .then(function (res) {
  698. var data = normalizeConversationApiPayload(res);
  699. if (!data) {
  700. throw new Error("对话接口返回数据为空或格式无法解析");
  701. }
  702. return data;
  703. });
  704. }
  705. function loadPageData() {
  706. var main = document.getElementById("main");
  707. var params = getConversationQueryParams();
  708. if (!params) {
  709. render(parsePayload());
  710. return;
  711. }
  712. var filterIds = parseMessageIdsFromQuery();
  713. updateFabLabels(getShareBrandByType(params.type).fabLabel);
  714. main.innerHTML = '<div class="empty">对话内容加载中…</div>';
  715. fetchConversationHistory(params.sessionId, params.userId, params.type)
  716. .then(function (data) {
  717. if (filterIds && filterIds.length) {
  718. var filtered = filterConversationMessagesByIds(data.messages, filterIds);
  719. if (!filtered.length) {
  720. throw new Error("未找到所选对话内容");
  721. }
  722. data = Object.assign({}, data, { messages: filtered });
  723. }
  724. render(data);
  725. })
  726. .catch(function (e) {
  727. var tip = e && e.message ? e.message : "对话加载失败,请稍后重试";
  728. console.warn("[conversation-api]", tip, e);
  729. main.innerHTML = '<div class="empty">' + escHtml(tip) + "</div>";
  730. refreshWxLaunchTagAttrs();
  731. });
  732. }
  733. function getFirstUserQuestion(messages) {
  734. var list = Array.isArray(messages) ? messages : [];
  735. for (var i = 0; i < list.length; i++) {
  736. var m = list[i];
  737. if (!m || m.role !== "user") continue;
  738. if (m.isImage) return "[图片]";
  739. var t = String(m.content || "").trim();
  740. if (t) return t;
  741. }
  742. return "";
  743. }
  744. function formatDiscussionTitle(question) {
  745. var qText = String(question || "").trim();
  746. if (!qText) return "与AI助手对话";
  747. if (qText.slice(-3) === "的讨论") return qText;
  748. return qText + "的讨论";
  749. }
  750. function normalizeShareTimestamp(ts) {
  751. if (ts == null || ts === "") return null;
  752. var n = Number(ts);
  753. if (!isFinite(n) || n <= 0) return null;
  754. if (n < 1e12) n = n * 1000;
  755. var d = new Date(n);
  756. if (isNaN(d.getTime()) || d.getFullYear() < 2020) return null;
  757. return n;
  758. }
  759. function resolveDisplayShareTime(data) {
  760. var fromUrl = q("shareTime") || q("share_time");
  761. var urlTs = normalizeShareTimestamp(fromUrl);
  762. if (urlTs != null) return urlTs;
  763. var dataTs = normalizeShareTimestamp(data && data.shareTime);
  764. if (dataTs != null) return dataTs;
  765. return Date.now();
  766. }
  767. function formatDate(ts) {
  768. var normalized = normalizeShareTimestamp(ts);
  769. var d = normalized != null ? new Date(normalized) : new Date();
  770. return d.getFullYear() + "年" + (d.getMonth() + 1) + "月" + d.getDate() + "日";
  771. }
  772. function renderMessages(messages) {
  773. var html = "";
  774. var list = Array.isArray(messages) ? messages : [];
  775. for (var i = 0; i < list.length; i++) {
  776. var msg = list[i];
  777. if (!msg) continue;
  778. if (msg.role === "user") {
  779. if (msg.isImage && msg.imageUrl) {
  780. html +=
  781. '<div class="row row--user"><div class="user-bubble"><img class="user-bubble__image" src="' +
  782. escHtml(msg.imageUrl) +
  783. '" alt="图片" loading="lazy" decoding="async" /></div></div>';
  784. var imageUserText = String(msg.content || "").trim();
  785. if (imageUserText) {
  786. html +=
  787. '<div class="row row--user"><div class="user-bubble">' +
  788. escHtml(imageUserText) +
  789. "</div></div>";
  790. }
  791. continue;
  792. }
  793. var userText = String(msg.content || "").trim();
  794. if (!userText) continue;
  795. html +=
  796. '<div class="row row--user"><div class="user-bubble">' +
  797. escHtml(userText) +
  798. "</div></div>";
  799. continue;
  800. }
  801. if (msg.role === "ai" || msg.role === "assistant") {
  802. var aiText = String(msg.content || "").trim();
  803. if (!aiText) continue;
  804. html +=
  805. '<div class="row row--ai"><div class="ai-card"><div class="ai-card__text">' +
  806. renderAiContentHtml(aiText) +
  807. "</div></div></div>";
  808. }
  809. }
  810. return html;
  811. }
  812. function applyWeixinShareMeta() {
  813. var brand = getShareBrandByType(getSharePageType());
  814. var siteName = "U店在哪";
  815. var iconUrl =
  816. "https://alien-volume.oss-cn-beijing.aliyuncs.com/icon/ubao.png";
  817. var setMeta = function (key, content) {
  818. var el =
  819. document.querySelector('meta[property="' + key + '"]') ||
  820. document.querySelector('meta[name="' + key + '"]');
  821. if (!el) {
  822. el = document.createElement("meta");
  823. if (key.indexOf("og:") === 0) {
  824. el.setAttribute("property", key);
  825. } else {
  826. el.setAttribute("name", key);
  827. }
  828. document.head.appendChild(el);
  829. }
  830. el.setAttribute("content", content);
  831. };
  832. setMeta("og:site_name", siteName);
  833. setMeta("application-name", siteName);
  834. setMeta("og:title", brand.ogTitle);
  835. setMeta("og:description", brand.ogDescription);
  836. var links = document.querySelectorAll('link[rel="icon"], link[rel="apple-touch-icon"]');
  837. for (var i = 0; i < links.length; i++) {
  838. links[i].setAttribute("href", iconUrl);
  839. }
  840. }
  841. function updateFabLabels(label) {
  842. var text = String(label || "和U宝继续聊").trim() || "和U宝继续聊";
  843. var openApp = document.getElementById("openApp");
  844. if (openApp) {
  845. openApp.setAttribute("aria-label", text);
  846. var img = openApp.querySelector(".fab__brand-img");
  847. if (img) img.setAttribute("alt", text);
  848. }
  849. }
  850. function countDisplayableMessages(messages) {
  851. var list = Array.isArray(messages) ? messages : [];
  852. var count = 0;
  853. for (var i = 0; i < list.length; i++) {
  854. var msg = list[i];
  855. if (!msg) continue;
  856. if (msg.role === "user") {
  857. if (msg.isImage && msg.imageUrl) {
  858. count += 1;
  859. continue;
  860. }
  861. if (String(msg.content || "").trim()) count += 1;
  862. continue;
  863. }
  864. if (msg.role === "ai" || msg.role === "assistant") {
  865. if (String(msg.content || "").trim()) count += 1;
  866. }
  867. }
  868. return count;
  869. }
  870. function parseMessagesFromContent(text) {
  871. var raw = String(text || "").trim();
  872. if (!raw) return [];
  873. var list = [];
  874. var blocks = raw.split(/\n\n+/);
  875. for (var i = 0; i < blocks.length; i++) {
  876. var block = String(blocks[i] || "").trim();
  877. if (!block) continue;
  878. var userMatch = block.match(/^我[::]\s*([\s\S]*)$/);
  879. if (userMatch) {
  880. var userText = String(userMatch[1] || "").trim();
  881. if (userText) list.push({ role: "user", content: userText });
  882. continue;
  883. }
  884. var aiMatch = block.match(/^UBAO[::]\s*([\s\S]*)$/i);
  885. if (aiMatch) {
  886. var aiText = String(aiMatch[1] || "").trim();
  887. if (aiText) list.push({ role: "ai", content: aiText });
  888. }
  889. }
  890. if (list.length) return list;
  891. var current = null;
  892. var lines = raw.split(/\n/);
  893. for (var j = 0; j < lines.length; j++) {
  894. var line = String(lines[j] || "");
  895. var userLine = line.match(/^我[::]\s*(.*)$/);
  896. var aiLine = line.match(/^UBAO[::]\s*(.*)$/i);
  897. if (userLine) {
  898. if (current) list.push(current);
  899. current = { role: "user", content: String(userLine[1] || "").trim() };
  900. continue;
  901. }
  902. if (aiLine) {
  903. if (current) list.push(current);
  904. current = { role: "ai", content: String(aiLine[1] || "").trim() };
  905. continue;
  906. }
  907. if (current && line.trim()) {
  908. current.content = (current.content ? current.content + "\n" : "") + line.trim();
  909. }
  910. }
  911. if (current && String(current.content || "").trim()) list.push(current);
  912. return list;
  913. }
  914. function resolveShareMessagesForDisplay(data) {
  915. var fromArray = Array.isArray(data && data.messages) ? data.messages : [];
  916. var fromContent = parseMessagesFromContent((data && data.content) || "");
  917. var arrayCount = countDisplayableMessages(fromArray);
  918. var contentCount = countDisplayableMessages(fromContent);
  919. // 分享链接超长时 messages 会被截断,但 content 仍保留完整对话文本
  920. if (contentCount > arrayCount) return fromContent;
  921. if (arrayCount) return fromArray;
  922. return fromContent;
  923. }
  924. function render(data) {
  925. var brand = getShareBrandByType(getSharePageType());
  926. applyWeixinShareMeta();
  927. updateFabLabels(brand.fabLabel);
  928. sharePayloadCache = data || null;
  929. var main = document.getElementById("main");
  930. if (!data) {
  931. main.innerHTML = '<div class="empty">对话内容不存在或链接已失效</div>';
  932. refreshWxLaunchTagAttrs();
  933. return;
  934. }
  935. var messages = resolveShareMessagesForDisplay(data);
  936. var firstQuestion =
  937. String(data.firstQuestion || "").trim() ||
  938. getFirstUserQuestion(messages) ||
  939. (function () {
  940. var text = String(data.content || "").trim();
  941. var m = text.match(/^我[::]([\s\S]+?)(?:\n\n|$)/);
  942. return m ? String(m[1] || "").trim() : "";
  943. })();
  944. var pageTitle = formatDiscussionTitle(firstQuestion);
  945. var dateText = formatDate(resolveDisplayShareTime(data));
  946. document.title = pageTitle;
  947. var bodyHtml =
  948. '<section class="hero">' +
  949. '<h1 class="hero__title">' +
  950. escHtml(pageTitle) +
  951. "</h1>" +
  952. '<p class="hero__meta">' +
  953. escHtml(dateText) +
  954. " · 内容由AI生成,不能完全保障真实</p>" +
  955. '<div class="hero__divider"></div>' +
  956. "</section>";
  957. var convHtml = renderMessages(messages);
  958. if (convHtml) {
  959. bodyHtml +=
  960. '<section class="conversation">' +
  961. convHtml +
  962. '</section><div class="scroll-spacer" aria-hidden="true"></div>';
  963. } else {
  964. bodyHtml += '<div class="empty">暂无对话内容</div>';
  965. }
  966. main.innerHTML = bodyHtml;
  967. refreshWxLaunchTagAttrs();
  968. }
  969. function buildAiConsultOpenParams() {
  970. var brand = getShareBrandByType(getSharePageType());
  971. var params = new URLSearchParams();
  972. if (brand.pageType) params.set("pageType", brand.pageType);
  973. params.set("fromShareAiConsult", "1");
  974. return params;
  975. }
  976. function buildAppDeepLink() {
  977. var brand = getShareBrandByType(getSharePageType());
  978. var path = brand.appPath || APP_UNI_AI_PATH;
  979. var qs = buildAiConsultOpenParams().toString();
  980. var root = APP_IOS_URL_SCHEME.replace(/\/$/, "");
  981. return root + "/" + path + (qs ? "?" + qs : "");
  982. }
  983. function buildWeChatLaunchExtinfo(useBarePathOnly) {
  984. var brand = getShareBrandByType(getSharePageType());
  985. var path = (brand.appPath || APP_UNI_AI_PATH).replace(/^\//, "");
  986. if (useBarePathOnly) return path;
  987. var qs = buildAiConsultOpenParams().toString();
  988. var uniPage = qs ? path + "?" + qs : path;
  989. if (uniPage.length <= 1024) return uniPage;
  990. if (brand.pageType) {
  991. return path + "?pageType=" + encodeURIComponent(brand.pageType) + "&fromShareAiConsult=1";
  992. }
  993. return path + "?fromShareAiConsult=1";
  994. }
  995. function isWeChatInAppBrowser() {
  996. return /MicroMessenger/i.test(navigator.userAgent || "");
  997. }
  998. function getWxShareEntryFrom() {
  999. var from = q("from");
  1000. if (from) return String(from).trim().toLowerCase();
  1001. try {
  1002. var h = location.hash || "";
  1003. var qi = h.indexOf("?");
  1004. if (qi >= 0) {
  1005. var hf = new URLSearchParams(h.slice(qi + 1)).get("from");
  1006. if (hf) return String(hf).trim().toLowerCase();
  1007. }
  1008. } catch (eH) {}
  1009. return "";
  1010. }
  1011. function logWxEntryDiagnostics() {
  1012. if (!isWeChatInAppBrowser()) return;
  1013. console.log("[wx-entry]", {
  1014. entryFrom: getWxShareEntryFrom() || "(无)",
  1015. wxJssdkReady: weChatJssdkConfigured,
  1016. signUrl: getWxConfigSignUrl(),
  1017. });
  1018. }
  1019. function isIOSWeChatBrowser() {
  1020. var ua = navigator.userAgent || "";
  1021. return /MicroMessenger/i.test(ua) && /iPhone|iPad|iPod/i.test(ua);
  1022. }
  1023. function isWxDebugOn() {
  1024. return q("wxDebug") === "1";
  1025. }
  1026. function isWxForceDebug() {
  1027. return q("wxForce") === "1";
  1028. }
  1029. function isWxConfigOnClickDebug() {
  1030. return q("wxConfigOnClick") === "1";
  1031. }
  1032. function isWxPcAutoDebugHost() {
  1033. var h = (location.hostname || "").toLowerCase();
  1034. if (h === "localhost" || h === "127.0.0.1") return true;
  1035. for (var i = 0; i < WECHAT_JS_SAFE_HOSTS.length; i++) {
  1036. if (WECHAT_JS_SAFE_HOSTS[i] === h) return true;
  1037. }
  1038. return false;
  1039. }
  1040. function isWxPcBrowser() {
  1041. return !isWeChatInAppBrowser();
  1042. }
  1043. function shouldInitWeChatJssdkOnLoad() {
  1044. if (isWeChatInAppBrowser()) return true;
  1045. return isWxForceDebug() || isWxPcAutoDebugHost();
  1046. }
  1047. function shouldFetchWxConfig(fromUserClick) {
  1048. if (isWeChatInAppBrowser()) return true;
  1049. if (fromUserClick) return true;
  1050. return isWxForceDebug() || isWxPcAutoDebugHost();
  1051. }
  1052. function getWxHtmlUrl() {
  1053. var forced = String(q("wxSignUrl") || "").trim();
  1054. if (forced) return forced.split("#")[0];
  1055. return String(location.href || "").split("#")[0];
  1056. }
  1057. function getWxSignPageUrlForApi() {
  1058. var htmlUrl = getWxHtmlUrl();
  1059. if (htmlUrl && /^https?:\/\//i.test(htmlUrl)) return htmlUrl;
  1060. return WX_GET_CONFIG_SIGN_URL;
  1061. }
  1062. function getWxHtmlUrlBase() {
  1063. var htmlUrl = getWxSignPageUrlForApi();
  1064. try {
  1065. var u = new URL(htmlUrl);
  1066. return u.origin + u.pathname;
  1067. } catch (eU) {
  1068. return WX_GET_CONFIG_SIGN_URL;
  1069. }
  1070. }
  1071. /** 与 secondShareGoods 一致:默认用当前页完整 URL 验签(须与微信地址栏一致,含 query) */
  1072. function getWxConfigSignUrl() {
  1073. if (String(q("wxSignBaseOnly") || "") === "1") return getWxHtmlUrlBase();
  1074. return getWxSignPageUrlForApi();
  1075. }
  1076. function getWxGetConfigApiUrl() {
  1077. return API_BASE.replace(/\/$/, "") + WECHAT_GET_WX_CONFIG_PATH;
  1078. }
  1079. function buildWxGetConfigRequestBody(htmlUrl) {
  1080. return {
  1081. url: String(htmlUrl || "").split("#")[0].trim(),
  1082. };
  1083. }
  1084. function resolveWxConfigAppIdFromSignData(d) {
  1085. if (!d || typeof d !== "object") return "";
  1086. var mp =
  1087. d.mpAppId ||
  1088. d.mpAppid ||
  1089. d.officialAppId ||
  1090. d.gzhAppId ||
  1091. d.serviceAppId;
  1092. if (mp != null && String(mp).trim() !== "") return String(mp).trim();
  1093. var fromQuery = String(q("wxMpAppId") || WECHAT_MP_APP_ID || "").trim();
  1094. if (fromQuery) return fromQuery;
  1095. var raw = d.appId || d.appid || d.wxAppId;
  1096. return raw != null && String(raw).trim() !== "" ? String(raw).trim() : "";
  1097. }
  1098. function normalizeWxJssdkSignPayload(res, signUrlUsed) {
  1099. if (!res || typeof res !== "object") return null;
  1100. var d = res.data != null && typeof res.data === "object" ? res.data : res;
  1101. if (!d || typeof d !== "object") return null;
  1102. var appId = resolveWxConfigAppIdFromSignData(d);
  1103. var timestamp = d.timestamp != null ? d.timestamp : d.timeStamp;
  1104. var nonceStr =
  1105. d.nonceStr != null && String(d.nonceStr) !== ""
  1106. ? d.nonceStr
  1107. : d.noncestr != null && String(d.noncestr) !== ""
  1108. ? d.noncestr
  1109. : d.nonce;
  1110. var signature = d.signature || d.sign;
  1111. if (!appId || timestamp == null || nonceStr == null || nonceStr === "" || !signature) {
  1112. return null;
  1113. }
  1114. return {
  1115. appId: String(appId),
  1116. timestamp: Number(timestamp),
  1117. nonceStr: String(nonceStr),
  1118. signature: String(signature),
  1119. signUrl: String(signUrlUsed || "")
  1120. .split("#")[0]
  1121. .trim(),
  1122. };
  1123. }
  1124. function getWxErrMsg(err) {
  1125. if (!err) return "";
  1126. if (err.errMsg) return String(err.errMsg);
  1127. if (typeof err === "string") return err;
  1128. try {
  1129. return JSON.stringify(err);
  1130. } catch (e) {
  1131. return String(err);
  1132. }
  1133. }
  1134. function formatWxConfigErrorTip(err, signPageUrl) {
  1135. var errMsg = getWxErrMsg(err);
  1136. var tip = "微信 JSSDK 配置失败";
  1137. if (/invalid signature/i.test(errMsg)) {
  1138. return (
  1139. tip +
  1140. ":签名无效。请核对:①后端用与前端相同的 url 签名;②url=" +
  1141. (signPageUrl || getWxHtmlUrl()) +
  1142. ";③nonceStr/timestamp 与接口返回一致;④appId=" +
  1143. WECHAT_MP_APP_ID
  1144. );
  1145. }
  1146. if (/require\s*subscribe/i.test(errMsg)) {
  1147. return tip + ":" + errMsg + "(服务号需用户已关注)";
  1148. }
  1149. return errMsg ? tip + ":" + errMsg : tip;
  1150. }
  1151. function setWxInitError(msg) {
  1152. wxInitLastError = String(msg || "").trim();
  1153. if (wxInitLastError) console.warn("[wx]", wxInitLastError);
  1154. }
  1155. function requestWeChatJssdkSignAndConfig(htmlUrlOptional) {
  1156. var htmlUrl = String(htmlUrlOptional != null ? htmlUrlOptional : getWxConfigSignUrl())
  1157. .split("#")[0]
  1158. .trim();
  1159. if (!htmlUrl || !/^https?:\/\//i.test(htmlUrl)) {
  1160. htmlUrl = WX_GET_CONFIG_SIGN_URL;
  1161. }
  1162. if (isWxDebugOn()) {
  1163. try {
  1164. window.alert("htmlUrl(签名用,应与地址栏一致):\n" + htmlUrl);
  1165. } catch (eDbg) {}
  1166. }
  1167. var requestUrl = getWxGetConfigApiUrl();
  1168. var requestBody = buildWxGetConfigRequestBody(htmlUrl);
  1169. console.log("[wx] htmlUrl=", htmlUrl);
  1170. console.log("[wx] POST getWxConfig →", requestUrl, requestBody);
  1171. return fetch(requestUrl, {
  1172. method: "POST",
  1173. mode: "cors",
  1174. credentials: "omit",
  1175. headers: {
  1176. Accept: "application/json",
  1177. "Content-Type": "application/json;charset=UTF-8",
  1178. },
  1179. body: JSON.stringify(requestBody),
  1180. })
  1181. .then(function (r) {
  1182. if (r.ok) return r.json();
  1183. return r
  1184. .text()
  1185. .catch(function () {
  1186. return "";
  1187. })
  1188. .then(function (text) {
  1189. var hint = "";
  1190. try {
  1191. var j = JSON.parse(text);
  1192. hint = j.msg || j.message || "";
  1193. } catch (eP) {
  1194. if (text) hint = text.slice(0, 120);
  1195. }
  1196. throw new Error("getWxConfig HTTP " + r.status + (hint ? ":" + hint : ""));
  1197. });
  1198. })
  1199. .then(function (res) {
  1200. if (res && res.code != null) {
  1201. var c = Number(res.code);
  1202. if (c !== 200 && c !== 0 && res.success !== true) {
  1203. throw new Error(res.msg || res.message || "getWxConfig code " + c);
  1204. }
  1205. }
  1206. var sign = normalizeWxJssdkSignPayload(res, htmlUrl);
  1207. if (!sign) {
  1208. console.warn("[wx] getWxConfig 响应字段不全", res, "htmlUrl=", htmlUrl);
  1209. throw new Error("getWxConfig 缺少 appId/timestamp/nonceStr/signature(见控制台)");
  1210. }
  1211. if (sign.appId !== WECHAT_MP_APP_ID) {
  1212. console.warn(
  1213. "[wx] 后端 appId=" + sign.appId + ",期望服务号 " + WECHAT_MP_APP_ID
  1214. );
  1215. }
  1216. if (typeof wx === "undefined") {
  1217. if (isWxPcBrowser()) {
  1218. console.log("[wx] PC getWxConfig 成功(无 jweixin)", sign);
  1219. return true;
  1220. }
  1221. setWxInitError("jweixin.js 未加载");
  1222. return false;
  1223. }
  1224. return applyWxConfigFromSign(sign, htmlUrl);
  1225. });
  1226. }
  1227. function applyWxConfigFromSign(sign, htmlUrl) {
  1228. var wxConfigParams = {
  1229. debug: isWxDebugOn(),
  1230. appId: String(sign.appId),
  1231. timestamp: sign.timestamp,
  1232. nonceStr: String(sign.nonceStr),
  1233. signature: String(sign.signature),
  1234. jsApiList: [],
  1235. openTagList: ["wx-open-launch-app"],
  1236. };
  1237. return new Promise(function (resolve) {
  1238. wx.config(wxConfigParams);
  1239. wx.ready(function () {
  1240. weChatJssdkConfigured = true;
  1241. document.body.classList.add("wx-jssdk-ready");
  1242. refreshWxLaunchTagAttrs();
  1243. console.log("[wx.config] ready, htmlUrl=", htmlUrl);
  1244. resolve(true);
  1245. });
  1246. wx.error(function (err) {
  1247. weChatJssdkConfigured = false;
  1248. document.body.classList.remove("wx-jssdk-ready");
  1249. wxJssdkInitPromise = null;
  1250. var errMsg = getWxErrMsg(err);
  1251. setWxInitError(formatWxConfigErrorTip(err, htmlUrl));
  1252. if (isWxDebugOn()) window.alert(wxInitLastError);
  1253. console.warn("[wx.config]", errMsg, "htmlUrl=", htmlUrl);
  1254. var baseUrl = getWxHtmlUrlBase();
  1255. var fullUrl = getWxSignPageUrlForApi();
  1256. if (
  1257. !/invalid signature/i.test(errMsg) ||
  1258. wxConfigSignRetriedBaseUrl ||
  1259. baseUrl === fullUrl ||
  1260. htmlUrl === baseUrl
  1261. ) {
  1262. resolve(false);
  1263. return;
  1264. }
  1265. wxConfigSignRetriedBaseUrl = true;
  1266. requestWeChatJssdkSignAndConfig(baseUrl).then(resolve);
  1267. });
  1268. });
  1269. }
  1270. function refreshWxLaunchTagAttrs(useBarePathOnly) {
  1271. var tag = document.getElementById("launch-btn");
  1272. if (!tag) return;
  1273. try {
  1274. tag.setAttribute("appid", WECHAT_OPEN_APP_ID);
  1275. tag.setAttribute("extinfo", buildWeChatLaunchExtinfo(!!useBarePathOnly));
  1276. console.log("[wx-open-launch-app] extinfo=", tag.getAttribute("extinfo"));
  1277. } catch (eA) {}
  1278. }
  1279. function bindWeChatLaunchTagEvents() {
  1280. var tag = document.getElementById("launch-btn");
  1281. if (!tag || tag._wxLaunchBound) return;
  1282. tag._wxLaunchBound = true;
  1283. refreshWxLaunchTagAttrs();
  1284. tag.addEventListener("launch", function () {
  1285. console.log("[wx-open-launch-app] launch ok");
  1286. });
  1287. tag.addEventListener("error", function (e) {
  1288. var detail = e && e.detail;
  1289. var errMsg =
  1290. detail && detail.errMsg
  1291. ? String(detail.errMsg)
  1292. : detail && detail.errmsg
  1293. ? String(detail.errmsg)
  1294. : "";
  1295. console.warn(
  1296. "[wx-open-launch-app]",
  1297. detail,
  1298. "extinfo=",
  1299. tag.getAttribute("extinfo")
  1300. );
  1301. if (/launch:fail_check/i.test(errMsg)) {
  1302. showAppOpenFailTip(
  1303. "请用微信分享卡片进入,或确认已安装最新版「U店在哪」"
  1304. );
  1305. return;
  1306. }
  1307. // if (
  1308. // /launch:fail/i.test(errMsg) &&
  1309. // !tag._wxLaunchBareRetried &&
  1310. // tag.getAttribute("extinfo") !== buildWeChatLaunchExtinfo(true)
  1311. // ) {
  1312. // tag._wxLaunchBareRetried = true;
  1313. // refreshWxLaunchTagAttrs(true);
  1314. // showFabToast("请再点一次「和U宝继续聊」");
  1315. // return;
  1316. // }
  1317. if (/launch:fail/i.test(errMsg) && !getWxShareEntryFrom()) {
  1318. showAppOpenFailTip("请前往应用商店下载U店在哪app");
  1319. return;
  1320. }
  1321. showAppOpenFailTip(
  1322. errMsg
  1323. ? "未能打开 App:" + errMsg
  1324. : "未能打开 App,请确认已安装最新版「U店在哪」"
  1325. );
  1326. });
  1327. }
  1328. function initWeChatOpenLaunchApp(fromUserClick) {
  1329. if (!shouldFetchWxConfig(!!fromUserClick)) {
  1330. return Promise.resolve(false);
  1331. }
  1332. if (wxJssdkInitPromise && !fromUserClick) return wxJssdkInitPromise;
  1333. wxConfigSignRetriedBaseUrl = false;
  1334. wxInitLastError = "";
  1335. var htmlUrl = getWxConfigSignUrl();
  1336. bindWeChatLaunchTagEvents();
  1337. wxJssdkInitPromise = requestWeChatJssdkSignAndConfig(htmlUrl)
  1338. .then(function (ok) {
  1339. if (ok === true) return true;
  1340. if (!wxInitLastError) {
  1341. setWxInitError("wx.config 失败,可加 ?wxDebug=1 查看 htmlUrl");
  1342. }
  1343. return false;
  1344. })
  1345. .catch(function (e) {
  1346. var msg = e && e.message ? e.message : "getWxConfig 请求失败";
  1347. setWxInitError(msg);
  1348. console.warn("[wx] requestWeChatJssdkSignAndConfig failed", msg, "htmlUrl=", htmlUrl);
  1349. if (isWeChatInAppBrowser() && isWxDebugOn()) window.alert(msg);
  1350. return false;
  1351. })
  1352. .finally(function () {
  1353. if (!weChatJssdkConfigured) wxJssdkInitPromise = null;
  1354. });
  1355. return wxJssdkInitPromise;
  1356. }
  1357. function scheduleWeChatJssdkBootstrap() {
  1358. if (!shouldInitWeChatJssdkOnLoad()) return;
  1359. var attempts = 0;
  1360. function tick() {
  1361. attempts += 1;
  1362. if (weChatJssdkConfigured) return;
  1363. initWeChatOpenLaunchApp();
  1364. if (!weChatJssdkConfigured && attempts < 8 && typeof wx === "undefined") {
  1365. setTimeout(tick, 400);
  1366. }
  1367. }
  1368. if (isIOSWeChatBrowser()) {
  1369. setTimeout(tick, 350);
  1370. } else {
  1371. tick();
  1372. }
  1373. }
  1374. function showFabToast(msg, ms) {
  1375. var tip = String(msg || "").trim();
  1376. if (!tip) return;
  1377. var el = document.getElementById("openAppToast");
  1378. if (el) {
  1379. el.textContent = tip;
  1380. el.style.display = "block";
  1381. if (showFabToast._t) clearTimeout(showFabToast._t);
  1382. showFabToast._t = setTimeout(function () {
  1383. el.style.display = "none";
  1384. }, ms || 2800);
  1385. }
  1386. console.log("[openApp]", tip);
  1387. }
  1388. function showDownloadTip() {
  1389. var msg = "请到应用商店下载「U店在哪」";
  1390. if (typeof uni !== "undefined" && typeof uni.showToast === "function") {
  1391. uni.showToast({ title: msg, icon: "none", duration: 2500 });
  1392. } else {
  1393. window.alert(msg);
  1394. }
  1395. }
  1396. function showAppOpenFailTip(msg) {
  1397. var tip = msg || "未能打开 App,请确认已安装最新版「U店在哪」。";
  1398. if (typeof uni !== "undefined" && typeof uni.showToast === "function") {
  1399. uni.showToast({ title: msg, icon: "none", duration: 2800 });
  1400. } else if (isWeChatInAppBrowser()) {
  1401. window.alert(tip);
  1402. } else {
  1403. showFabToast(tip);
  1404. }
  1405. }
  1406. function launchAppDeepLink(deepLink) {
  1407. try {
  1408. var a = document.createElement("a");
  1409. a.href = deepLink;
  1410. a.setAttribute("target", "_self");
  1411. document.body.appendChild(a);
  1412. a.click();
  1413. document.body.removeChild(a);
  1414. } catch (e1) {}
  1415. try {
  1416. window.location.href = deepLink;
  1417. } catch (e2) {}
  1418. }
  1419. function tryOpenHBuilderAppViaScheme() {
  1420. var deepLink = buildAppDeepLink();
  1421. if (typeof plus !== "undefined" && plus.runtime) {
  1422. var installed = null;
  1423. try {
  1424. if (typeof plus.runtime.isApplicationExist === "function") {
  1425. installed = plus.runtime.isApplicationExist({
  1426. pname: APP_ANDROID_PACKAGE,
  1427. action: APP_IOS_URL_SCHEME,
  1428. });
  1429. }
  1430. } catch (e) {
  1431. console.warn(e);
  1432. }
  1433. if (installed === false) {
  1434. showDownloadTip();
  1435. return;
  1436. }
  1437. try {
  1438. plus.runtime.openURL(deepLink);
  1439. } catch (e2) {
  1440. console.warn(e2);
  1441. showDownloadTip();
  1442. }
  1443. return;
  1444. }
  1445. var done = false;
  1446. function finish() {
  1447. if (done) return;
  1448. done = true;
  1449. document.removeEventListener("visibilitychange", onVis);
  1450. window.removeEventListener("pagehide", onHide);
  1451. }
  1452. function onVis() {
  1453. if (document.visibilityState === "hidden") finish();
  1454. }
  1455. function onHide() {
  1456. finish();
  1457. }
  1458. document.addEventListener("visibilitychange", onVis);
  1459. window.addEventListener("pagehide", onHide);
  1460. try {
  1461. launchAppDeepLink(deepLink);
  1462. } catch (e3) {
  1463. finish();
  1464. showDownloadTip();
  1465. return;
  1466. }
  1467. window.setTimeout(function () {
  1468. finish();
  1469. }, 3200);
  1470. }
  1471. function tryFetchWxConfigOnPcClick() {
  1472. if (!isWxPcBrowser()) return Promise.resolve(false);
  1473. showFabToast("正在请求 getWxConfig…");
  1474. wxJssdkInitPromise = null;
  1475. return initWeChatOpenLaunchApp(true).then(function (ok) {
  1476. if (ok) {
  1477. showFabToast(
  1478. weChatJssdkConfigured
  1479. ? "getWxConfig 成功,wx.config 已就绪"
  1480. : "getWxConfig 成功"
  1481. );
  1482. } else {
  1483. showFabToast(wxInitLastError || "getWxConfig 失败");
  1484. }
  1485. return ok;
  1486. });
  1487. }
  1488. function tryOpenHBuilderApp() {
  1489. if (isWeChatInAppBrowser()) return;
  1490. if (!isWxPcBrowser()) {
  1491. tryOpenHBuilderAppViaScheme();
  1492. return;
  1493. }
  1494. tryFetchWxConfigOnPcClick().then(function () {
  1495. if (isWxConfigOnClickDebug() && !isWxForceDebug() && !isWxPcAutoDebugHost()) {
  1496. return;
  1497. }
  1498. tryOpenHBuilderAppViaScheme();
  1499. });
  1500. }
  1501. function boot() {
  1502. var launchTag = document.getElementById("launch-btn");
  1503. if (launchTag) launchTag.setAttribute("appid", WECHAT_OPEN_APP_ID);
  1504. bindWeChatLaunchTagEvents();
  1505. if (isWeChatInAppBrowser()) {
  1506. document.body.classList.add("is-wechat");
  1507. logWxEntryDiagnostics();
  1508. }
  1509. if (shouldInitWeChatJssdkOnLoad()) {
  1510. if (isWxPcBrowser() && (isWxForceDebug() || isWxPcAutoDebugHost())) {
  1511. document.body.classList.add("wx-pc-debug");
  1512. }
  1513. scheduleWeChatJssdkBootstrap();
  1514. }
  1515. document.addEventListener("WeixinOpenTagsError", function (e) {
  1516. console.warn("[WeixinOpenTagsError]", e && e.detail);
  1517. });
  1518. if (isWeChatInAppBrowser()) {
  1519. var openBtnWx = document.getElementById("openApp");
  1520. if (openBtnWx) {
  1521. openBtnWx.addEventListener("click", function () {
  1522. if (!weChatJssdkConfigured) {
  1523. showFabToast(
  1524. wxInitLastError || "微信 SDK 初始化中,请稍候再点底部按钮"
  1525. );
  1526. }
  1527. });
  1528. }
  1529. } else {
  1530. var openAppBtn = document.getElementById("openApp");
  1531. if (openAppBtn) {
  1532. openAppBtn.addEventListener("click", tryOpenHBuilderApp);
  1533. }
  1534. }
  1535. loadPageData();
  1536. }
  1537. if (document.readyState === "complete") {
  1538. boot();
  1539. } else {
  1540. window.addEventListener("load", boot);
  1541. }
  1542. })();
  1543. </script>
  1544. </body>
  1545. </html>