shareAiConsult.html 49 KB

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