shareAiKfChat.html 54 KB

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