shareAiConsult.html 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558
  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 normalizeShareTimestamp(ts) {
  640. if (ts == null || ts === "") return null;
  641. var n = Number(ts);
  642. if (!isFinite(n) || n <= 0) return null;
  643. if (n < 1e12) n = n * 1000;
  644. var d = new Date(n);
  645. if (isNaN(d.getTime()) || d.getFullYear() < 2020) return null;
  646. return n;
  647. }
  648. function resolveDisplayShareTime(data) {
  649. var fromUrl = q("shareTime") || q("share_time");
  650. var urlTs = normalizeShareTimestamp(fromUrl);
  651. if (urlTs != null) return urlTs;
  652. var dataTs = normalizeShareTimestamp(data && data.shareTime);
  653. if (dataTs != null) return dataTs;
  654. return Date.now();
  655. }
  656. function formatDate(ts) {
  657. var normalized = normalizeShareTimestamp(ts);
  658. var d = normalized != null ? new Date(normalized) : new Date();
  659. return d.getFullYear() + "年" + (d.getMonth() + 1) + "月" + d.getDate() + "日";
  660. }
  661. function renderMessages(messages) {
  662. var html = "";
  663. var list = Array.isArray(messages) ? messages : [];
  664. for (var i = 0; i < list.length; i++) {
  665. var msg = list[i];
  666. if (!msg) continue;
  667. if (msg.role === "user") {
  668. if (msg.isImage && msg.imageUrl) {
  669. html +=
  670. '<div class="row row--user"><div class="user-bubble"><img class="user-bubble__image" src="' +
  671. escHtml(msg.imageUrl) +
  672. '" alt="图片" loading="lazy" decoding="async" /></div></div>';
  673. continue;
  674. }
  675. var userText = String(msg.content || "").trim();
  676. if (!userText) continue;
  677. html +=
  678. '<div class="row row--user"><div class="user-bubble">' +
  679. escHtml(userText) +
  680. "</div></div>";
  681. continue;
  682. }
  683. if (msg.role === "ai" || msg.role === "assistant") {
  684. var aiText = String(msg.content || "").trim();
  685. if (!aiText) continue;
  686. html +=
  687. '<div class="row row--ai"><div class="ai-card"><div class="ai-card__text">' +
  688. renderAiContentHtml(aiText) +
  689. "</div></div></div>";
  690. }
  691. }
  692. return html;
  693. }
  694. function applyWeixinShareMeta() {
  695. var siteName = "U店在哪";
  696. var iconUrl =
  697. "https://alien-volume.oss-cn-beijing.aliyuncs.com/icon/ubao.png";
  698. var setMeta = function (key, content) {
  699. var el =
  700. document.querySelector('meta[property="' + key + '"]') ||
  701. document.querySelector('meta[name="' + key + '"]');
  702. if (!el) {
  703. el = document.createElement("meta");
  704. if (key.indexOf("og:") === 0) {
  705. el.setAttribute("property", key);
  706. } else {
  707. el.setAttribute("name", key);
  708. }
  709. document.head.appendChild(el);
  710. }
  711. el.setAttribute("content", content);
  712. };
  713. setMeta("og:site_name", siteName);
  714. setMeta("application-name", siteName);
  715. setMeta("og:title", "和U宝的对话");
  716. setMeta("og:description", "点击查看对话内容");
  717. var links = document.querySelectorAll('link[rel="icon"], link[rel="apple-touch-icon"]');
  718. for (var i = 0; i < links.length; i++) {
  719. links[i].setAttribute("href", iconUrl);
  720. }
  721. }
  722. function countDisplayableMessages(messages) {
  723. var list = Array.isArray(messages) ? messages : [];
  724. var count = 0;
  725. for (var i = 0; i < list.length; i++) {
  726. var msg = list[i];
  727. if (!msg) continue;
  728. if (msg.role === "user") {
  729. if (msg.isImage && msg.imageUrl) {
  730. count += 1;
  731. continue;
  732. }
  733. if (String(msg.content || "").trim()) count += 1;
  734. continue;
  735. }
  736. if (msg.role === "ai" || msg.role === "assistant") {
  737. if (String(msg.content || "").trim()) count += 1;
  738. }
  739. }
  740. return count;
  741. }
  742. function parseMessagesFromContent(text) {
  743. var raw = String(text || "").trim();
  744. if (!raw) return [];
  745. var list = [];
  746. var blocks = raw.split(/\n\n+/);
  747. for (var i = 0; i < blocks.length; i++) {
  748. var block = String(blocks[i] || "").trim();
  749. if (!block) continue;
  750. var userMatch = block.match(/^我[::]\s*([\s\S]*)$/);
  751. if (userMatch) {
  752. var userText = String(userMatch[1] || "").trim();
  753. if (userText) list.push({ role: "user", content: userText });
  754. continue;
  755. }
  756. var aiMatch = block.match(/^UBAO[::]\s*([\s\S]*)$/i);
  757. if (aiMatch) {
  758. var aiText = String(aiMatch[1] || "").trim();
  759. if (aiText) list.push({ role: "ai", content: aiText });
  760. }
  761. }
  762. if (list.length) return list;
  763. var current = null;
  764. var lines = raw.split(/\n/);
  765. for (var j = 0; j < lines.length; j++) {
  766. var line = String(lines[j] || "");
  767. var userLine = line.match(/^我[::]\s*(.*)$/);
  768. var aiLine = line.match(/^UBAO[::]\s*(.*)$/i);
  769. if (userLine) {
  770. if (current) list.push(current);
  771. current = { role: "user", content: String(userLine[1] || "").trim() };
  772. continue;
  773. }
  774. if (aiLine) {
  775. if (current) list.push(current);
  776. current = { role: "ai", content: String(aiLine[1] || "").trim() };
  777. continue;
  778. }
  779. if (current && line.trim()) {
  780. current.content = (current.content ? current.content + "\n" : "") + line.trim();
  781. }
  782. }
  783. if (current && String(current.content || "").trim()) list.push(current);
  784. return list;
  785. }
  786. function resolveShareMessagesForDisplay(data) {
  787. var fromArray = Array.isArray(data && data.messages) ? data.messages : [];
  788. var fromContent = parseMessagesFromContent((data && data.content) || "");
  789. var arrayCount = countDisplayableMessages(fromArray);
  790. var contentCount = countDisplayableMessages(fromContent);
  791. // 分享链接超长时 messages 会被截断,但 content 仍保留完整对话文本
  792. if (contentCount > arrayCount) return fromContent;
  793. if (arrayCount) return fromArray;
  794. return fromContent;
  795. }
  796. function render(data) {
  797. applyWeixinShareMeta();
  798. sharePayloadCache = data || null;
  799. var main = document.getElementById("main");
  800. if (!data) {
  801. main.innerHTML = '<div class="empty">对话内容不存在或链接已失效</div>';
  802. refreshWxLaunchTagAttrs();
  803. return;
  804. }
  805. var messages = resolveShareMessagesForDisplay(data);
  806. var firstQuestion =
  807. String(data.firstQuestion || "").trim() ||
  808. getFirstUserQuestion(messages) ||
  809. (function () {
  810. var text = String(data.content || "").trim();
  811. var m = text.match(/^我[::]([\s\S]+?)(?:\n\n|$)/);
  812. return m ? String(m[1] || "").trim() : "";
  813. })();
  814. var pageTitle = formatDiscussionTitle(firstQuestion);
  815. var dateText = formatDate(resolveDisplayShareTime(data));
  816. document.title = pageTitle;
  817. var bodyHtml =
  818. '<section class="hero">' +
  819. '<h1 class="hero__title">' +
  820. escHtml(pageTitle) +
  821. "</h1>" +
  822. '<p class="hero__meta">' +
  823. escHtml(dateText) +
  824. " · 内容由AI生成,不能完全保障真实</p>" +
  825. '<div class="hero__divider"></div>' +
  826. "</section>";
  827. var convHtml = renderMessages(messages);
  828. if (convHtml) {
  829. bodyHtml +=
  830. '<section class="conversation">' +
  831. convHtml +
  832. '</section><div class="scroll-spacer" aria-hidden="true"></div>';
  833. } else {
  834. bodyHtml += '<div class="empty">暂无对话内容</div>';
  835. }
  836. main.innerHTML = bodyHtml;
  837. refreshWxLaunchTagAttrs();
  838. }
  839. function buildAiConsultOpenParams() {
  840. var params = new URLSearchParams();
  841. params.set("pageType", "home");
  842. params.set("fromShareAiConsult", "1");
  843. return params;
  844. }
  845. function buildAppDeepLink() {
  846. var path = APP_UNI_AI_PATH;
  847. var qs = buildAiConsultOpenParams().toString();
  848. var root = APP_IOS_URL_SCHEME.replace(/\/$/, "");
  849. return root + "/" + path + (qs ? "?" + qs : "");
  850. }
  851. function buildWeChatLaunchExtinfo(useBarePathOnly) {
  852. var path = APP_UNI_AI_PATH.replace(/^\//, "");
  853. if (useBarePathOnly) return path;
  854. var qs = buildAiConsultOpenParams().toString();
  855. var uniPage = qs ? path + "?" + qs : path;
  856. if (uniPage.length <= 1024) return uniPage;
  857. return path + "?pageType=home&fromShareAiConsult=1";
  858. }
  859. function isWeChatInAppBrowser() {
  860. return /MicroMessenger/i.test(navigator.userAgent || "");
  861. }
  862. function getWxShareEntryFrom() {
  863. var from = q("from");
  864. if (from) return String(from).trim().toLowerCase();
  865. try {
  866. var h = location.hash || "";
  867. var qi = h.indexOf("?");
  868. if (qi >= 0) {
  869. var hf = new URLSearchParams(h.slice(qi + 1)).get("from");
  870. if (hf) return String(hf).trim().toLowerCase();
  871. }
  872. } catch (eH) {}
  873. return "";
  874. }
  875. function logWxEntryDiagnostics() {
  876. if (!isWeChatInAppBrowser()) return;
  877. console.log("[wx-entry]", {
  878. entryFrom: getWxShareEntryFrom() || "(无)",
  879. wxJssdkReady: weChatJssdkConfigured,
  880. signUrl: getWxConfigSignUrl(),
  881. });
  882. }
  883. function isIOSWeChatBrowser() {
  884. var ua = navigator.userAgent || "";
  885. return /MicroMessenger/i.test(ua) && /iPhone|iPad|iPod/i.test(ua);
  886. }
  887. function isWxDebugOn() {
  888. return q("wxDebug") === "1";
  889. }
  890. function isWxForceDebug() {
  891. return q("wxForce") === "1";
  892. }
  893. function isWxConfigOnClickDebug() {
  894. return q("wxConfigOnClick") === "1";
  895. }
  896. function isWxPcAutoDebugHost() {
  897. var h = (location.hostname || "").toLowerCase();
  898. if (h === "localhost" || h === "127.0.0.1") return true;
  899. for (var i = 0; i < WECHAT_JS_SAFE_HOSTS.length; i++) {
  900. if (WECHAT_JS_SAFE_HOSTS[i] === h) return true;
  901. }
  902. return false;
  903. }
  904. function isWxPcBrowser() {
  905. return !isWeChatInAppBrowser();
  906. }
  907. function shouldInitWeChatJssdkOnLoad() {
  908. if (isWeChatInAppBrowser()) return true;
  909. return isWxForceDebug() || isWxPcAutoDebugHost();
  910. }
  911. function shouldFetchWxConfig(fromUserClick) {
  912. if (isWeChatInAppBrowser()) return true;
  913. if (fromUserClick) return true;
  914. return isWxForceDebug() || isWxPcAutoDebugHost();
  915. }
  916. function getWxHtmlUrl() {
  917. var forced = String(q("wxSignUrl") || "").trim();
  918. if (forced) return forced.split("#")[0];
  919. return String(location.href || "").split("#")[0];
  920. }
  921. function getWxSignPageUrlForApi() {
  922. var htmlUrl = getWxHtmlUrl();
  923. if (htmlUrl && /^https?:\/\//i.test(htmlUrl)) return htmlUrl;
  924. return WX_GET_CONFIG_SIGN_URL;
  925. }
  926. function getWxHtmlUrlBase() {
  927. var htmlUrl = getWxSignPageUrlForApi();
  928. try {
  929. var u = new URL(htmlUrl);
  930. return u.origin + u.pathname;
  931. } catch (eU) {
  932. return WX_GET_CONFIG_SIGN_URL;
  933. }
  934. }
  935. /** 与 secondShareGoods 一致:默认用当前页完整 URL 验签(须与微信地址栏一致,含 query) */
  936. function getWxConfigSignUrl() {
  937. if (String(q("wxSignBaseOnly") || "") === "1") return getWxHtmlUrlBase();
  938. return getWxSignPageUrlForApi();
  939. }
  940. function getWxGetConfigApiUrl() {
  941. return API_BASE.replace(/\/$/, "") + WECHAT_GET_WX_CONFIG_PATH;
  942. }
  943. function buildWxGetConfigRequestBody(htmlUrl) {
  944. return {
  945. url: String(htmlUrl || "").split("#")[0].trim(),
  946. };
  947. }
  948. function resolveWxConfigAppIdFromSignData(d) {
  949. if (!d || typeof d !== "object") return "";
  950. var mp =
  951. d.mpAppId ||
  952. d.mpAppid ||
  953. d.officialAppId ||
  954. d.gzhAppId ||
  955. d.serviceAppId;
  956. if (mp != null && String(mp).trim() !== "") return String(mp).trim();
  957. var fromQuery = String(q("wxMpAppId") || WECHAT_MP_APP_ID || "").trim();
  958. if (fromQuery) return fromQuery;
  959. var raw = d.appId || d.appid || d.wxAppId;
  960. return raw != null && String(raw).trim() !== "" ? String(raw).trim() : "";
  961. }
  962. function normalizeWxJssdkSignPayload(res, signUrlUsed) {
  963. if (!res || typeof res !== "object") return null;
  964. var d = res.data != null && typeof res.data === "object" ? res.data : res;
  965. if (!d || typeof d !== "object") return null;
  966. var appId = resolveWxConfigAppIdFromSignData(d);
  967. var timestamp = d.timestamp != null ? d.timestamp : d.timeStamp;
  968. var nonceStr =
  969. d.nonceStr != null && String(d.nonceStr) !== ""
  970. ? d.nonceStr
  971. : d.noncestr != null && String(d.noncestr) !== ""
  972. ? d.noncestr
  973. : d.nonce;
  974. var signature = d.signature || d.sign;
  975. if (!appId || timestamp == null || nonceStr == null || nonceStr === "" || !signature) {
  976. return null;
  977. }
  978. return {
  979. appId: String(appId),
  980. timestamp: Number(timestamp),
  981. nonceStr: String(nonceStr),
  982. signature: String(signature),
  983. signUrl: String(signUrlUsed || "")
  984. .split("#")[0]
  985. .trim(),
  986. };
  987. }
  988. function getWxErrMsg(err) {
  989. if (!err) return "";
  990. if (err.errMsg) return String(err.errMsg);
  991. if (typeof err === "string") return err;
  992. try {
  993. return JSON.stringify(err);
  994. } catch (e) {
  995. return String(err);
  996. }
  997. }
  998. function formatWxConfigErrorTip(err, signPageUrl) {
  999. var errMsg = getWxErrMsg(err);
  1000. var tip = "微信 JSSDK 配置失败";
  1001. if (/invalid signature/i.test(errMsg)) {
  1002. return (
  1003. tip +
  1004. ":签名无效。请核对:①后端用与前端相同的 url 签名;②url=" +
  1005. (signPageUrl || getWxHtmlUrl()) +
  1006. ";③nonceStr/timestamp 与接口返回一致;④appId=" +
  1007. WECHAT_MP_APP_ID
  1008. );
  1009. }
  1010. if (/require\s*subscribe/i.test(errMsg)) {
  1011. return tip + ":" + errMsg + "(服务号需用户已关注)";
  1012. }
  1013. return errMsg ? tip + ":" + errMsg : tip;
  1014. }
  1015. function setWxInitError(msg) {
  1016. wxInitLastError = String(msg || "").trim();
  1017. if (wxInitLastError) console.warn("[wx]", wxInitLastError);
  1018. }
  1019. function requestWeChatJssdkSignAndConfig(htmlUrlOptional) {
  1020. var htmlUrl = String(htmlUrlOptional != null ? htmlUrlOptional : getWxConfigSignUrl())
  1021. .split("#")[0]
  1022. .trim();
  1023. if (!htmlUrl || !/^https?:\/\//i.test(htmlUrl)) {
  1024. htmlUrl = WX_GET_CONFIG_SIGN_URL;
  1025. }
  1026. if (isWxDebugOn()) {
  1027. try {
  1028. window.alert("htmlUrl(签名用,应与地址栏一致):\n" + htmlUrl);
  1029. } catch (eDbg) {}
  1030. }
  1031. var requestUrl = getWxGetConfigApiUrl();
  1032. var requestBody = buildWxGetConfigRequestBody(htmlUrl);
  1033. console.log("[wx] htmlUrl=", htmlUrl);
  1034. console.log("[wx] POST getWxConfig →", requestUrl, requestBody);
  1035. return fetch(requestUrl, {
  1036. method: "POST",
  1037. mode: "cors",
  1038. credentials: "omit",
  1039. headers: {
  1040. Accept: "application/json",
  1041. "Content-Type": "application/json;charset=UTF-8",
  1042. },
  1043. body: JSON.stringify(requestBody),
  1044. })
  1045. .then(function (r) {
  1046. if (r.ok) return r.json();
  1047. return r
  1048. .text()
  1049. .catch(function () {
  1050. return "";
  1051. })
  1052. .then(function (text) {
  1053. var hint = "";
  1054. try {
  1055. var j = JSON.parse(text);
  1056. hint = j.msg || j.message || "";
  1057. } catch (eP) {
  1058. if (text) hint = text.slice(0, 120);
  1059. }
  1060. throw new Error("getWxConfig HTTP " + r.status + (hint ? ":" + hint : ""));
  1061. });
  1062. })
  1063. .then(function (res) {
  1064. if (res && res.code != null) {
  1065. var c = Number(res.code);
  1066. if (c !== 200 && c !== 0 && res.success !== true) {
  1067. throw new Error(res.msg || res.message || "getWxConfig code " + c);
  1068. }
  1069. }
  1070. var sign = normalizeWxJssdkSignPayload(res, htmlUrl);
  1071. if (!sign) {
  1072. console.warn("[wx] getWxConfig 响应字段不全", res, "htmlUrl=", htmlUrl);
  1073. throw new Error("getWxConfig 缺少 appId/timestamp/nonceStr/signature(见控制台)");
  1074. }
  1075. if (sign.appId !== WECHAT_MP_APP_ID) {
  1076. console.warn(
  1077. "[wx] 后端 appId=" + sign.appId + ",期望服务号 " + WECHAT_MP_APP_ID
  1078. );
  1079. }
  1080. if (typeof wx === "undefined") {
  1081. if (isWxPcBrowser()) {
  1082. console.log("[wx] PC getWxConfig 成功(无 jweixin)", sign);
  1083. return true;
  1084. }
  1085. setWxInitError("jweixin.js 未加载");
  1086. return false;
  1087. }
  1088. return applyWxConfigFromSign(sign, htmlUrl);
  1089. });
  1090. }
  1091. function applyWxConfigFromSign(sign, htmlUrl) {
  1092. var wxConfigParams = {
  1093. debug: isWxDebugOn(),
  1094. appId: String(sign.appId),
  1095. timestamp: sign.timestamp,
  1096. nonceStr: String(sign.nonceStr),
  1097. signature: String(sign.signature),
  1098. jsApiList: [],
  1099. openTagList: ["wx-open-launch-app"],
  1100. };
  1101. return new Promise(function (resolve) {
  1102. wx.config(wxConfigParams);
  1103. wx.ready(function () {
  1104. weChatJssdkConfigured = true;
  1105. document.body.classList.add("wx-jssdk-ready");
  1106. refreshWxLaunchTagAttrs();
  1107. console.log("[wx.config] ready, htmlUrl=", htmlUrl);
  1108. resolve(true);
  1109. });
  1110. wx.error(function (err) {
  1111. weChatJssdkConfigured = false;
  1112. document.body.classList.remove("wx-jssdk-ready");
  1113. wxJssdkInitPromise = null;
  1114. var errMsg = getWxErrMsg(err);
  1115. setWxInitError(formatWxConfigErrorTip(err, htmlUrl));
  1116. if (isWxDebugOn()) window.alert(wxInitLastError);
  1117. console.warn("[wx.config]", errMsg, "htmlUrl=", htmlUrl);
  1118. var baseUrl = getWxHtmlUrlBase();
  1119. var fullUrl = getWxSignPageUrlForApi();
  1120. if (
  1121. !/invalid signature/i.test(errMsg) ||
  1122. wxConfigSignRetriedBaseUrl ||
  1123. baseUrl === fullUrl ||
  1124. htmlUrl === baseUrl
  1125. ) {
  1126. resolve(false);
  1127. return;
  1128. }
  1129. wxConfigSignRetriedBaseUrl = true;
  1130. requestWeChatJssdkSignAndConfig(baseUrl).then(resolve);
  1131. });
  1132. });
  1133. }
  1134. function refreshWxLaunchTagAttrs(useBarePathOnly) {
  1135. var tag = document.getElementById("launch-btn");
  1136. if (!tag) return;
  1137. try {
  1138. tag.setAttribute("appid", WECHAT_OPEN_APP_ID);
  1139. tag.setAttribute("extinfo", buildWeChatLaunchExtinfo(!!useBarePathOnly));
  1140. console.log("[wx-open-launch-app] extinfo=", tag.getAttribute("extinfo"));
  1141. } catch (eA) {}
  1142. }
  1143. function bindWeChatLaunchTagEvents() {
  1144. var tag = document.getElementById("launch-btn");
  1145. if (!tag || tag._wxLaunchBound) return;
  1146. tag._wxLaunchBound = true;
  1147. refreshWxLaunchTagAttrs();
  1148. tag.addEventListener("launch", function () {
  1149. console.log("[wx-open-launch-app] launch ok");
  1150. });
  1151. tag.addEventListener("error", function (e) {
  1152. var detail = e && e.detail;
  1153. var errMsg =
  1154. detail && detail.errMsg
  1155. ? String(detail.errMsg)
  1156. : detail && detail.errmsg
  1157. ? String(detail.errmsg)
  1158. : "";
  1159. console.warn(
  1160. "[wx-open-launch-app]",
  1161. detail,
  1162. "extinfo=",
  1163. tag.getAttribute("extinfo")
  1164. );
  1165. if (/launch:fail_check/i.test(errMsg)) {
  1166. showAppOpenFailTip(
  1167. "请用微信分享卡片进入,或确认已安装最新版「U店在哪」"
  1168. );
  1169. return;
  1170. }
  1171. // if (
  1172. // /launch:fail/i.test(errMsg) &&
  1173. // !tag._wxLaunchBareRetried &&
  1174. // tag.getAttribute("extinfo") !== buildWeChatLaunchExtinfo(true)
  1175. // ) {
  1176. // tag._wxLaunchBareRetried = true;
  1177. // refreshWxLaunchTagAttrs(true);
  1178. // showFabToast("请再点一次「和U宝继续聊」");
  1179. // return;
  1180. // }
  1181. if (/launch:fail/i.test(errMsg) && !getWxShareEntryFrom()) {
  1182. showAppOpenFailTip("请前往应用商店下载U店在哪app");
  1183. return;
  1184. }
  1185. showAppOpenFailTip(
  1186. errMsg
  1187. ? "未能打开 App:" + errMsg
  1188. : "未能打开 App,请确认已安装最新版「U店在哪」"
  1189. );
  1190. });
  1191. }
  1192. function initWeChatOpenLaunchApp(fromUserClick) {
  1193. if (!shouldFetchWxConfig(!!fromUserClick)) {
  1194. return Promise.resolve(false);
  1195. }
  1196. if (wxJssdkInitPromise && !fromUserClick) return wxJssdkInitPromise;
  1197. wxConfigSignRetriedBaseUrl = false;
  1198. wxInitLastError = "";
  1199. var htmlUrl = getWxConfigSignUrl();
  1200. bindWeChatLaunchTagEvents();
  1201. wxJssdkInitPromise = requestWeChatJssdkSignAndConfig(htmlUrl)
  1202. .then(function (ok) {
  1203. if (ok === true) return true;
  1204. if (!wxInitLastError) {
  1205. setWxInitError("wx.config 失败,可加 ?wxDebug=1 查看 htmlUrl");
  1206. }
  1207. return false;
  1208. })
  1209. .catch(function (e) {
  1210. var msg = e && e.message ? e.message : "getWxConfig 请求失败";
  1211. setWxInitError(msg);
  1212. console.warn("[wx] requestWeChatJssdkSignAndConfig failed", msg, "htmlUrl=", htmlUrl);
  1213. if (isWeChatInAppBrowser() && isWxDebugOn()) window.alert(msg);
  1214. return false;
  1215. })
  1216. .finally(function () {
  1217. if (!weChatJssdkConfigured) wxJssdkInitPromise = null;
  1218. });
  1219. return wxJssdkInitPromise;
  1220. }
  1221. function scheduleWeChatJssdkBootstrap() {
  1222. if (!shouldInitWeChatJssdkOnLoad()) return;
  1223. var attempts = 0;
  1224. function tick() {
  1225. attempts += 1;
  1226. if (weChatJssdkConfigured) return;
  1227. initWeChatOpenLaunchApp();
  1228. if (!weChatJssdkConfigured && attempts < 8 && typeof wx === "undefined") {
  1229. setTimeout(tick, 400);
  1230. }
  1231. }
  1232. if (isIOSWeChatBrowser()) {
  1233. setTimeout(tick, 350);
  1234. } else {
  1235. tick();
  1236. }
  1237. }
  1238. function showFabToast(msg, ms) {
  1239. var tip = String(msg || "").trim();
  1240. if (!tip) return;
  1241. var el = document.getElementById("openAppToast");
  1242. if (el) {
  1243. el.textContent = tip;
  1244. el.style.display = "block";
  1245. if (showFabToast._t) clearTimeout(showFabToast._t);
  1246. showFabToast._t = setTimeout(function () {
  1247. el.style.display = "none";
  1248. }, ms || 2800);
  1249. }
  1250. console.log("[openApp]", tip);
  1251. }
  1252. function showDownloadTip() {
  1253. var msg = "请到应用商店下载「U店在哪」";
  1254. if (typeof uni !== "undefined" && typeof uni.showToast === "function") {
  1255. uni.showToast({ title: msg, icon: "none", duration: 2500 });
  1256. } else {
  1257. window.alert(msg);
  1258. }
  1259. }
  1260. function showAppOpenFailTip(msg) {
  1261. var tip = msg || "未能打开 App,请确认已安装最新版「U店在哪」。";
  1262. if (typeof uni !== "undefined" && typeof uni.showToast === "function") {
  1263. uni.showToast({ title: msg, icon: "none", duration: 2800 });
  1264. } else if (isWeChatInAppBrowser()) {
  1265. window.alert(tip);
  1266. } else {
  1267. showFabToast(tip);
  1268. }
  1269. }
  1270. function launchAppDeepLink(deepLink) {
  1271. try {
  1272. var a = document.createElement("a");
  1273. a.href = deepLink;
  1274. a.setAttribute("target", "_self");
  1275. document.body.appendChild(a);
  1276. a.click();
  1277. document.body.removeChild(a);
  1278. } catch (e1) {}
  1279. try {
  1280. window.location.href = deepLink;
  1281. } catch (e2) {}
  1282. }
  1283. function tryOpenHBuilderAppViaScheme() {
  1284. var deepLink = buildAppDeepLink();
  1285. if (typeof plus !== "undefined" && plus.runtime) {
  1286. var installed = null;
  1287. try {
  1288. if (typeof plus.runtime.isApplicationExist === "function") {
  1289. installed = plus.runtime.isApplicationExist({
  1290. pname: APP_ANDROID_PACKAGE,
  1291. action: APP_IOS_URL_SCHEME,
  1292. });
  1293. }
  1294. } catch (e) {
  1295. console.warn(e);
  1296. }
  1297. if (installed === false) {
  1298. showDownloadTip();
  1299. return;
  1300. }
  1301. try {
  1302. plus.runtime.openURL(deepLink);
  1303. } catch (e2) {
  1304. console.warn(e2);
  1305. showDownloadTip();
  1306. }
  1307. return;
  1308. }
  1309. var done = false;
  1310. function finish() {
  1311. if (done) return;
  1312. done = true;
  1313. document.removeEventListener("visibilitychange", onVis);
  1314. window.removeEventListener("pagehide", onHide);
  1315. }
  1316. function onVis() {
  1317. if (document.visibilityState === "hidden") finish();
  1318. }
  1319. function onHide() {
  1320. finish();
  1321. }
  1322. document.addEventListener("visibilitychange", onVis);
  1323. window.addEventListener("pagehide", onHide);
  1324. try {
  1325. launchAppDeepLink(deepLink);
  1326. } catch (e3) {
  1327. finish();
  1328. showDownloadTip();
  1329. return;
  1330. }
  1331. window.setTimeout(function () {
  1332. finish();
  1333. }, 3200);
  1334. }
  1335. function tryFetchWxConfigOnPcClick() {
  1336. if (!isWxPcBrowser()) return Promise.resolve(false);
  1337. showFabToast("正在请求 getWxConfig…");
  1338. wxJssdkInitPromise = null;
  1339. return initWeChatOpenLaunchApp(true).then(function (ok) {
  1340. if (ok) {
  1341. showFabToast(
  1342. weChatJssdkConfigured
  1343. ? "getWxConfig 成功,wx.config 已就绪"
  1344. : "getWxConfig 成功"
  1345. );
  1346. } else {
  1347. showFabToast(wxInitLastError || "getWxConfig 失败");
  1348. }
  1349. return ok;
  1350. });
  1351. }
  1352. function tryOpenHBuilderApp() {
  1353. if (isWeChatInAppBrowser()) return;
  1354. if (!isWxPcBrowser()) {
  1355. tryOpenHBuilderAppViaScheme();
  1356. return;
  1357. }
  1358. tryFetchWxConfigOnPcClick().then(function () {
  1359. if (isWxConfigOnClickDebug() && !isWxForceDebug() && !isWxPcAutoDebugHost()) {
  1360. return;
  1361. }
  1362. tryOpenHBuilderAppViaScheme();
  1363. });
  1364. }
  1365. function boot() {
  1366. var launchTag = document.getElementById("launch-btn");
  1367. if (launchTag) launchTag.setAttribute("appid", WECHAT_OPEN_APP_ID);
  1368. bindWeChatLaunchTagEvents();
  1369. if (isWeChatInAppBrowser()) {
  1370. document.body.classList.add("is-wechat");
  1371. logWxEntryDiagnostics();
  1372. }
  1373. if (shouldInitWeChatJssdkOnLoad()) {
  1374. if (isWxPcBrowser() && (isWxForceDebug() || isWxPcAutoDebugHost())) {
  1375. document.body.classList.add("wx-pc-debug");
  1376. }
  1377. scheduleWeChatJssdkBootstrap();
  1378. }
  1379. document.addEventListener("WeixinOpenTagsError", function (e) {
  1380. console.warn("[WeixinOpenTagsError]", e && e.detail);
  1381. });
  1382. if (isWeChatInAppBrowser()) {
  1383. var openBtnWx = document.getElementById("openApp");
  1384. if (openBtnWx) {
  1385. openBtnWx.addEventListener("click", function () {
  1386. if (!weChatJssdkConfigured) {
  1387. showFabToast(
  1388. wxInitLastError || "微信 SDK 初始化中,请稍候再点底部按钮"
  1389. );
  1390. }
  1391. });
  1392. }
  1393. } else {
  1394. var openAppBtn = document.getElementById("openApp");
  1395. if (openAppBtn) {
  1396. openAppBtn.addEventListener("click", tryOpenHBuilderApp);
  1397. }
  1398. }
  1399. loadPageData();
  1400. }
  1401. if (document.readyState === "complete") {
  1402. boot();
  1403. } else {
  1404. window.addEventListener("load", boot);
  1405. }
  1406. })();
  1407. </script>
  1408. </body>
  1409. </html>