shareAiConsult.html 53 KB

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