shareAiKfChat.html 57 KB

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