shareAiConsult.html 59 KB

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