shareAiKfChat.html 53 KB

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