shareAiConsult.html 52 KB

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