shareAiConsult.html 48 KB

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