shareAiConsult.html 54 KB

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