shareAiConsult.html 59 KB

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