shareAiConsult.html 58 KB

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