shareAiConsult.html 48 KB

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