shareAiKfChat.html 57 KB

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