shareAiConsult.html 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031
  1. <!DOCTYPE html>
  2. <html lang="zh-CN">
  3. <head>
  4. <meta charset="utf-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover">
  6. <meta name="format-detection" content="telephone=no">
  7. <title>与U宝对话</title>
  8. <meta property="og:title" content="和U宝的对话">
  9. <meta property="og:description" content="点击查看对话内容">
  10. <meta property="og:site_name" content="U宝AI智能助手">
  11. <meta name="application-name" content="U宝AI智能助手">
  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. -webkit-tap-highlight-color: transparent;
  29. }
  30. body {
  31. font-family: -apple-system, BlinkMacSystemFont, "PingFang SC", "Microsoft YaHei", sans-serif;
  32. background: var(--bg);
  33. color: var(--text);
  34. min-height: 100vh;
  35. padding-bottom: calc(92px + var(--safe-bottom));
  36. }
  37. .hero {
  38. padding: 16px 15px 0;
  39. }
  40. .hero__title {
  41. font-size: 20px;
  42. font-weight: 700;
  43. line-height: 1.4;
  44. word-break: break-word;
  45. }
  46. .hero__meta {
  47. margin-top: 8px;
  48. font-size: 12px;
  49. color: var(--muted);
  50. line-height: 1.4;
  51. }
  52. .hero__divider {
  53. margin-top: 14px;
  54. height: 1px;
  55. background: rgba(170, 170, 170, 0.25);
  56. }
  57. .conversation {
  58. padding: 14px 15px 0;
  59. box-sizing: border-box;
  60. }
  61. .row {
  62. display: flex;
  63. width: 100%;
  64. margin-bottom: 12px;
  65. }
  66. .row--user {
  67. justify-content: flex-end;
  68. }
  69. .row--ai {
  70. justify-content: flex-start;
  71. }
  72. .user-bubble {
  73. position: relative;
  74. max-width: 78%;
  75. padding: 10px 12px;
  76. background: #f47d1f;
  77. border-radius: 6px;
  78. box-sizing: border-box;
  79. }
  80. .user-bubble::after {
  81. content: "";
  82. position: absolute;
  83. right: -5px;
  84. bottom: 10px;
  85. width: 0;
  86. height: 0;
  87. border-style: solid;
  88. border-width: 5px 0 5px 6px;
  89. border-color: transparent transparent transparent #f47d1f;
  90. }
  91. .user-bubble__text {
  92. font-size: 15px;
  93. font-weight: 500;
  94. color: #ffffff;
  95. line-height: 22px;
  96. word-break: break-word;
  97. white-space: pre-wrap;
  98. }
  99. .ai-card {
  100. width: 100%;
  101. padding: 14px 13px;
  102. background: #ffffff;
  103. border-radius: 8px;
  104. box-sizing: border-box;
  105. box-shadow: 0 1px 6px rgba(0, 0, 0, 0.04);
  106. }
  107. .ai-card__text {
  108. font-size: 14px;
  109. color: #151515;
  110. line-height: 23px;
  111. word-break: break-word;
  112. white-space: pre-wrap;
  113. text-align: left;
  114. }
  115. .fallback-card {
  116. margin: 14px 15px 0;
  117. padding: 14px 13px;
  118. background: #ffffff;
  119. border-radius: 8px;
  120. box-sizing: border-box;
  121. }
  122. .fallback-card__text {
  123. font-size: 14px;
  124. color: #151515;
  125. line-height: 23px;
  126. white-space: pre-wrap;
  127. word-break: break-word;
  128. }
  129. .empty {
  130. padding: 48px 20px;
  131. text-align: center;
  132. color: var(--muted);
  133. font-size: 14px;
  134. }
  135. .footer {
  136. position: fixed;
  137. left: 0;
  138. right: 0;
  139. bottom: 0;
  140. z-index: 200;
  141. padding: 10px 15px calc(10px + var(--safe-bottom));
  142. background: linear-gradient(180deg, rgba(244, 246, 251, 0) 0%, #f4f6fb 36%);
  143. pointer-events: none;
  144. }
  145. .footer__dock {
  146. display: flex;
  147. justify-content: center;
  148. width: 100%;
  149. pointer-events: auto;
  150. }
  151. .footer__btn-slot {
  152. width: 50%;
  153. height: 48px;
  154. margin: 0 auto;
  155. }
  156. .continue-btn {
  157. display: flex;
  158. align-items: center;
  159. justify-content: center;
  160. width: 100%;
  161. height: 48px;
  162. margin: 0;
  163. padding: 0;
  164. border: none;
  165. border-radius: 999px;
  166. background: linear-gradient(90deg, #ffb84c 0%, #ff6b3e 100%);
  167. box-shadow: 0 4px 16px rgba(255, 107, 62, 0.32);
  168. touch-action: manipulation;
  169. -webkit-tap-highlight-color: transparent;
  170. }
  171. .continue-btn__label {
  172. display: block;
  173. height: 20px;
  174. width: auto;
  175. max-width: 90%;
  176. pointer-events: none;
  177. -webkit-user-drag: none;
  178. }
  179. #launch-btn {
  180. display: none;
  181. width: 100%;
  182. height: 48px;
  183. min-height: 48px;
  184. border-radius: 999px;
  185. overflow: hidden;
  186. }
  187. body.is-wechat.wx-jssdk-ready #launch-btn {
  188. display: block;
  189. pointer-events: auto;
  190. }
  191. body.is-wechat.wx-jssdk-ready #btnContinue {
  192. display: none !important;
  193. }
  194. #openAppToast {
  195. display: none;
  196. position: fixed;
  197. left: 16px;
  198. right: 16px;
  199. bottom: calc(72px + var(--safe-bottom));
  200. z-index: 10001;
  201. padding: 10px 14px;
  202. font-size: 13px;
  203. line-height: 1.45;
  204. color: #fff;
  205. text-align: center;
  206. background: rgba(0, 0, 0, 0.78);
  207. border-radius: 8px;
  208. pointer-events: none;
  209. word-break: break-all;
  210. }
  211. </style>
  212. </head>
  213. <body>
  214. <main id="main">
  215. <div class="empty">对话内容加载中…</div>
  216. </main>
  217. <div id="openAppToast" role="status" aria-live="polite"></div>
  218. <footer class="footer">
  219. <div class="footer__dock">
  220. <div class="footer__btn-slot">
  221. <button type="button" class="continue-btn" id="btnContinue" aria-label="和U宝继续聊">
  222. <img class="continue-btn__label" src="images/uCharts.png" alt="和U宝继续聊" decoding="async">
  223. </button>
  224. <wx-open-launch-app id="launch-btn" appid="wxf5f1efe3a9f5012e" extinfo="">
  225. <script type="text/wxtag-template">
  226. <style>
  227. .wx-open-app-btn {
  228. display: flex;
  229. align-items: center;
  230. justify-content: center;
  231. width: 100%;
  232. height: 48px;
  233. margin: 0;
  234. padding: 0;
  235. border: none;
  236. border-radius: 999px;
  237. background: linear-gradient(90deg, #ffb84c 0%, #ff6b3e 100%);
  238. box-shadow: 0 4px 16px rgba(255, 107, 62, 0.32);
  239. cursor: pointer;
  240. -webkit-tap-highlight-color: transparent;
  241. }
  242. .continue-btn__label {
  243. display: block;
  244. height: 20px;
  245. width: auto;
  246. max-width: 90%;
  247. pointer-events: none;
  248. }
  249. </style>
  250. <button class="wx-open-app-btn" aria-label="和U宝继续聊">
  251. <img class="continue-btn__label" src="https://test.ailien.shop/h5/HBuilderProjects/images/uCharts.png" alt="和U宝继续聊" decoding="async">
  252. </button>
  253. </script>
  254. </wx-open-launch-app>
  255. </div>
  256. </div>
  257. </footer>
  258. <script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
  259. <script>
  260. (function () {
  261. "use strict";
  262. var API_BASE = "https://test.ailien.shop/alienStore";
  263. var WECHAT_MP_APP_ID = "wx412792c77f47babd";
  264. var WECHAT_OPEN_APP_ID = "wxf5f1efe3a9f5012e";
  265. var WECHAT_GET_WX_CONFIG_PATH = "/wx/getWxConfig";
  266. var H5_PAGE_BASE_FALLBACK = "https://test.ailien.shop/h5/HBuilderProjects/";
  267. var WX_GET_CONFIG_SIGN_URL = H5_PAGE_BASE_FALLBACK + "shareAiConsult.html";
  268. var WECHAT_JS_SAFE_HOSTS = ["uat.ailien.shop", "test.ailien.shop"];
  269. var APP_ANDROID_PACKAGE = "com.alien.Udianzaizhe";
  270. var APP_IOS_URL_SCHEME = "shopro://";
  271. var APP_UNI_AI_PATH = "pages/aiSearchResult/index";
  272. var sharePayloadCache = null;
  273. var weChatJssdkConfigured = false;
  274. var wxConfigSignRetriedBaseUrl = false;
  275. var wxInitLastError = "";
  276. var wxJssdkInitPromise = null;
  277. function escHtml(s) {
  278. return String(s || "")
  279. .replace(/&/g, "&amp;")
  280. .replace(/</g, "&lt;")
  281. .replace(/>/g, "&gt;")
  282. .replace(/"/g, "&quot;");
  283. }
  284. function q(name) {
  285. try {
  286. var v = new URLSearchParams(location.search || "").get(name);
  287. return v == null ? "" : String(v);
  288. } catch (e) {
  289. return "";
  290. }
  291. }
  292. function getQueryParam(name) {
  293. var m = new RegExp("[?&]" + name + "=([^&]*)").exec(window.location.search);
  294. if (!m) return "";
  295. try {
  296. return decodeURIComponent(m[1].replace(/\+/g, " "));
  297. } catch (e) {
  298. return "";
  299. }
  300. }
  301. function parsePayload() {
  302. var raw = getQueryParam("payload");
  303. if (!raw) return null;
  304. try {
  305. return JSON.parse(raw);
  306. } catch (e) {
  307. return null;
  308. }
  309. }
  310. /** 对话 payload 在 query 中会导致 URL 过长,微信 JSSDK / 开放标签易 launch:fail;读完后清掉 query */
  311. function stripPayloadQueryFromUrl() {
  312. try {
  313. if (!location.search || location.search.indexOf("payload=") < 0) return;
  314. var u = new URL(location.href);
  315. u.searchParams.delete("payload");
  316. var next = u.pathname + (u.search || "") + (u.hash || "");
  317. history.replaceState(null, document.title, next);
  318. } catch (eStrip) {}
  319. }
  320. function getFirstUserQuestion(messages) {
  321. var list = Array.isArray(messages) ? messages : [];
  322. for (var i = 0; i < list.length; i++) {
  323. var m = list[i];
  324. if (!m || m.role !== "user") continue;
  325. if (m.isImage) return "[图片]";
  326. var t = String(m.content || "").trim();
  327. if (t) return t;
  328. }
  329. return "";
  330. }
  331. function formatDiscussionTitle(question) {
  332. var qText = String(question || "").trim();
  333. if (!qText) return "与AI助手对话";
  334. if (qText.slice(-3) === "的讨论") return qText;
  335. return qText + "的讨论";
  336. }
  337. function formatNavTitle(question) {
  338. var titled = formatDiscussionTitle(question);
  339. var maxLen = 14;
  340. var short = titled.length > maxLen ? titled.slice(0, maxLen) + "..." : titled;
  341. return short + "-U宝";
  342. }
  343. function extractFirstQuestionFromContent(content) {
  344. var text = String(content || "").trim();
  345. if (!text) return "";
  346. var match = text.match(/^我[::]([\s\S]+?)(?:\n\n|$)/);
  347. if (match) return String(match[1] || "").trim();
  348. return "";
  349. }
  350. function parseContentToMessages(content) {
  351. var text = String(content || "").trim();
  352. if (!text) return [];
  353. var messages = [];
  354. var blocks = text.split(/\n\n+/);
  355. for (var i = 0; i < blocks.length; i++) {
  356. var block = String(blocks[i] || "").trim();
  357. if (!block) continue;
  358. var userMatch = block.match(/^我[::]\s*([\s\S]*)$/);
  359. if (userMatch) {
  360. var userText = String(userMatch[1] || "").trim();
  361. if (userText) messages.push({ role: "user", content: userText });
  362. continue;
  363. }
  364. var aiMatch = block.match(/^UBAO[::]\s*([\s\S]*)$/i);
  365. if (aiMatch) {
  366. var aiText = String(aiMatch[1] || "").trim();
  367. if (aiText) messages.push({ role: "ai", content: aiText });
  368. }
  369. }
  370. return messages;
  371. }
  372. function resolveShareMessages(data) {
  373. var messages = Array.isArray(data && data.messages) ? data.messages : [];
  374. if (messages.length) return messages;
  375. return parseContentToMessages(data && data.content);
  376. }
  377. function formatDate(ts) {
  378. var d = ts ? new Date(Number(ts)) : new Date();
  379. if (isNaN(d.getTime())) d = new Date();
  380. return d.getFullYear() + "年" + (d.getMonth() + 1) + "月" + d.getDate() + "日";
  381. }
  382. function renderMessages(messages) {
  383. var html = "";
  384. var list = Array.isArray(messages) ? messages : [];
  385. for (var i = 0; i < list.length; i++) {
  386. var msg = list[i];
  387. if (!msg) continue;
  388. if (msg.role === "user") {
  389. var userText = msg.isImage ? "[图片]" : String(msg.content || "").trim();
  390. if (!userText) continue;
  391. html +=
  392. '<div class="row row--user"><div class="user-bubble"><div class="user-bubble__text">' +
  393. escHtml(userText) +
  394. "</div></div></div>";
  395. continue;
  396. }
  397. if (msg.role === "ai") {
  398. var aiText = String(msg.content || "").trim();
  399. if (!aiText) continue;
  400. html +=
  401. '<div class="row row--ai"><div class="ai-card"><div class="ai-card__text">' +
  402. escHtml(aiText) +
  403. "</div></div></div>";
  404. }
  405. }
  406. return html;
  407. }
  408. function applyWeixinShareMeta() {
  409. var siteName = "U宝AI智能助手";
  410. var iconUrl =
  411. "https://alien-volume.oss-cn-beijing.aliyuncs.com/icon/ubao.png";
  412. var setMeta = function (key, content) {
  413. var el =
  414. document.querySelector('meta[property="' + key + '"]') ||
  415. document.querySelector('meta[name="' + key + '"]');
  416. if (!el) {
  417. el = document.createElement("meta");
  418. if (key.indexOf("og:") === 0) {
  419. el.setAttribute("property", key);
  420. } else {
  421. el.setAttribute("name", key);
  422. }
  423. document.head.appendChild(el);
  424. }
  425. el.setAttribute("content", content);
  426. };
  427. setMeta("og:site_name", siteName);
  428. setMeta("application-name", siteName);
  429. setMeta("og:title", "和U宝的对话");
  430. setMeta("og:description", "点击查看对话内容");
  431. var links = document.querySelectorAll('link[rel="icon"], link[rel="apple-touch-icon"]');
  432. for (var i = 0; i < links.length; i++) {
  433. links[i].setAttribute("href", iconUrl);
  434. }
  435. }
  436. function render(data) {
  437. applyWeixinShareMeta();
  438. sharePayloadCache = data || null;
  439. var main = document.getElementById("main");
  440. if (!data) {
  441. document.title = "与AI助手-U宝";
  442. main.innerHTML = '<div class="empty">对话内容不存在或链接已失效</div>';
  443. refreshWxLaunchTagAttrs();
  444. return;
  445. }
  446. var messages = resolveShareMessages(data);
  447. var firstQuestion =
  448. String(data.firstQuestion || "").trim() ||
  449. getFirstUserQuestion(messages) ||
  450. extractFirstQuestionFromContent(data.content);
  451. var pageTitle = formatDiscussionTitle(firstQuestion);
  452. var navTitleText = formatNavTitle(firstQuestion);
  453. var dateText = formatDate(data.shareTime);
  454. document.title = navTitleText;
  455. var bodyHtml =
  456. '<section class="hero">' +
  457. '<h1 class="hero__title">' +
  458. escHtml(pageTitle) +
  459. "</h1>" +
  460. '<p class="hero__meta">' +
  461. escHtml(dateText) +
  462. " · 内容由AI生成,不能完全保障真实</p>" +
  463. '<div class="hero__divider"></div>' +
  464. "</section>";
  465. var convHtml = renderMessages(messages);
  466. if (convHtml) {
  467. bodyHtml += '<section class="conversation">' + convHtml + "</section>";
  468. } else {
  469. bodyHtml += '<div class="empty">暂无对话内容</div>';
  470. }
  471. main.innerHTML = bodyHtml;
  472. refreshWxLaunchTagAttrs();
  473. }
  474. function buildAppDeepLink() {
  475. var path = String(APP_UNI_AI_PATH || "pages/aiSearchResult/index").replace(/^\//, "");
  476. var root = APP_IOS_URL_SCHEME.replace(/\/$/, "");
  477. return root + "/" + path;
  478. }
  479. function buildWeChatLaunchExtinfo() {
  480. return String(APP_UNI_AI_PATH || "pages/aiSearchResult/index").replace(/^\//, "");
  481. }
  482. function isWeChatInAppBrowser() {
  483. return /MicroMessenger/i.test(navigator.userAgent || "");
  484. }
  485. function isIOSWeChatBrowser() {
  486. var ua = navigator.userAgent || "";
  487. return /MicroMessenger/i.test(ua) && /iPhone|iPad|iPod/i.test(ua);
  488. }
  489. function isWxDebugOn() {
  490. return q("wxDebug") === "1";
  491. }
  492. function isWxForceDebug() {
  493. return q("wxForce") === "1";
  494. }
  495. function isWxPcAutoDebugHost() {
  496. var h = (location.hostname || "").toLowerCase();
  497. if (h === "localhost" || h === "127.0.0.1") return true;
  498. for (var i = 0; i < WECHAT_JS_SAFE_HOSTS.length; i++) {
  499. if (WECHAT_JS_SAFE_HOSTS[i] === h) return true;
  500. }
  501. return false;
  502. }
  503. function isWxPcBrowser() {
  504. return !isWeChatInAppBrowser();
  505. }
  506. function shouldInitWeChatJssdkOnLoad() {
  507. if (isWeChatInAppBrowser()) return true;
  508. return isWxForceDebug() || isWxPcAutoDebugHost();
  509. }
  510. function shouldFetchWxConfig(fromUserClick) {
  511. if (isWeChatInAppBrowser()) return true;
  512. if (fromUserClick) return true;
  513. return isWxForceDebug() || isWxPcAutoDebugHost();
  514. }
  515. function getWxHtmlUrl() {
  516. var forced = String(q("wxSignUrl") || "").trim();
  517. if (forced) return forced.split("#")[0];
  518. return String(location.href || "").split("#")[0];
  519. }
  520. function getWxSignPageUrlForApi() {
  521. var htmlUrl = getWxHtmlUrl();
  522. if (htmlUrl && /^https?:\/\//i.test(htmlUrl)) return htmlUrl;
  523. return WX_GET_CONFIG_SIGN_URL;
  524. }
  525. function getWxHtmlUrlBase() {
  526. var htmlUrl = getWxSignPageUrlForApi();
  527. try {
  528. var u = new URL(htmlUrl);
  529. return u.origin + u.pathname;
  530. } catch (eU) {
  531. return WX_GET_CONFIG_SIGN_URL;
  532. }
  533. }
  534. function getWxConfigSignUrl() {
  535. return getWxHtmlUrlBase();
  536. }
  537. function getWxGetConfigApiUrl() {
  538. return API_BASE.replace(/\/$/, "") + WECHAT_GET_WX_CONFIG_PATH;
  539. }
  540. function buildWxGetConfigRequestBody(htmlUrl) {
  541. return {
  542. url: String(htmlUrl || "").split("#")[0].trim(),
  543. };
  544. }
  545. function resolveWxConfigAppIdFromSignData(d) {
  546. if (!d || typeof d !== "object") return "";
  547. var mp =
  548. d.mpAppId ||
  549. d.mpAppid ||
  550. d.officialAppId ||
  551. d.gzhAppId ||
  552. d.serviceAppId;
  553. if (mp != null && String(mp).trim() !== "") return String(mp).trim();
  554. var fromQuery = String(q("wxMpAppId") || WECHAT_MP_APP_ID || "").trim();
  555. if (fromQuery) return fromQuery;
  556. var raw = d.appId || d.appid || d.wxAppId;
  557. return raw != null && String(raw).trim() !== "" ? String(raw).trim() : "";
  558. }
  559. function normalizeWxJssdkSignPayload(res, signUrlUsed) {
  560. if (!res || typeof res !== "object") return null;
  561. var d = res.data != null && typeof res.data === "object" ? res.data : res;
  562. if (!d || typeof d !== "object") return null;
  563. var appId = resolveWxConfigAppIdFromSignData(d);
  564. var timestamp = d.timestamp != null ? d.timestamp : d.timeStamp;
  565. var nonceStr =
  566. d.nonceStr != null && String(d.nonceStr) !== ""
  567. ? d.nonceStr
  568. : d.noncestr != null && String(d.noncestr) !== ""
  569. ? d.noncestr
  570. : d.nonce;
  571. var signature = d.signature || d.sign;
  572. if (!appId || timestamp == null || nonceStr == null || nonceStr === "" || !signature) {
  573. return null;
  574. }
  575. return {
  576. appId: String(appId),
  577. timestamp: Number(timestamp),
  578. nonceStr: String(nonceStr),
  579. signature: String(signature),
  580. signUrl: String(signUrlUsed || "")
  581. .split("#")[0]
  582. .trim(),
  583. };
  584. }
  585. function getWxErrMsg(err) {
  586. if (!err) return "";
  587. if (err.errMsg) return String(err.errMsg);
  588. if (typeof err === "string") return err;
  589. try {
  590. return JSON.stringify(err);
  591. } catch (e) {
  592. return String(err);
  593. }
  594. }
  595. function formatWxConfigErrorTip(err, signPageUrl) {
  596. var errMsg = getWxErrMsg(err);
  597. var tip = "微信 JSSDK 配置失败";
  598. if (/invalid signature/i.test(errMsg)) {
  599. return (
  600. tip +
  601. ":签名无效。请核对:①后端用与前端相同的 url 签名;②url=" +
  602. (signPageUrl || getWxHtmlUrl()) +
  603. ";③nonceStr/timestamp 与接口返回一致;④appId=" +
  604. WECHAT_MP_APP_ID
  605. );
  606. }
  607. if (/require\s*subscribe/i.test(errMsg)) {
  608. return tip + ":" + errMsg + "(服务号需用户已关注)";
  609. }
  610. return errMsg ? tip + ":" + errMsg : tip;
  611. }
  612. function setWxInitError(msg) {
  613. wxInitLastError = String(msg || "").trim();
  614. if (wxInitLastError) console.warn("[wx]", wxInitLastError);
  615. }
  616. function requestWeChatJssdkSignAndConfig(htmlUrlOptional) {
  617. var htmlUrl = String(htmlUrlOptional != null ? htmlUrlOptional : getWxConfigSignUrl())
  618. .split("#")[0]
  619. .trim();
  620. if (!htmlUrl || !/^https?:\/\//i.test(htmlUrl)) {
  621. htmlUrl = WX_GET_CONFIG_SIGN_URL;
  622. }
  623. if (isWxDebugOn()) {
  624. try {
  625. window.alert("htmlUrl(签名用,应与地址栏一致):\n" + htmlUrl);
  626. } catch (eDbg) {}
  627. }
  628. var requestUrl = getWxGetConfigApiUrl();
  629. var requestBody = buildWxGetConfigRequestBody(htmlUrl);
  630. return fetch(requestUrl, {
  631. method: "POST",
  632. mode: "cors",
  633. credentials: "omit",
  634. headers: {
  635. Accept: "application/json",
  636. "Content-Type": "application/json;charset=UTF-8",
  637. },
  638. body: JSON.stringify(requestBody),
  639. })
  640. .then(function (r) {
  641. if (r.ok) return r.json();
  642. return r
  643. .text()
  644. .catch(function () {
  645. return "";
  646. })
  647. .then(function (text) {
  648. var hint = "";
  649. try {
  650. var j = JSON.parse(text);
  651. hint = j.msg || j.message || "";
  652. } catch (eP) {
  653. if (text) hint = text.slice(0, 120);
  654. }
  655. throw new Error("getWxConfig HTTP " + r.status + (hint ? ":" + hint : ""));
  656. });
  657. })
  658. .then(function (res) {
  659. if (res && res.code != null) {
  660. var c = Number(res.code);
  661. if (c !== 200 && c !== 0 && res.success !== true) {
  662. throw new Error(res.msg || res.message || "getWxConfig code " + c);
  663. }
  664. }
  665. var sign = normalizeWxJssdkSignPayload(res, htmlUrl);
  666. if (!sign) {
  667. throw new Error("getWxConfig 缺少 appId/timestamp/nonceStr/signature(见控制台)");
  668. }
  669. if (typeof wx === "undefined") {
  670. if (isWxPcBrowser()) {
  671. console.log("[wx] PC getWxConfig 成功(无 jweixin)", sign);
  672. return true;
  673. }
  674. setWxInitError("jweixin.js 未加载");
  675. return false;
  676. }
  677. return applyWxConfigFromSign(sign, htmlUrl);
  678. });
  679. }
  680. function applyWxConfigFromSign(sign, htmlUrl) {
  681. var wxConfigParams = {
  682. debug: isWxDebugOn(),
  683. appId: String(sign.appId),
  684. timestamp: sign.timestamp,
  685. nonceStr: String(sign.nonceStr),
  686. signature: String(sign.signature),
  687. jsApiList: [],
  688. openTagList: ["wx-open-launch-app"],
  689. };
  690. return new Promise(function (resolve) {
  691. wx.config(wxConfigParams);
  692. wx.ready(function () {
  693. weChatJssdkConfigured = true;
  694. document.body.classList.add("wx-jssdk-ready");
  695. refreshWxLaunchTagAttrs();
  696. console.log("[wx.config] ready, htmlUrl=", htmlUrl);
  697. resolve(true);
  698. });
  699. wx.error(function (err) {
  700. weChatJssdkConfigured = false;
  701. document.body.classList.remove("wx-jssdk-ready");
  702. wxJssdkInitPromise = null;
  703. var errMsg = getWxErrMsg(err);
  704. setWxInitError(formatWxConfigErrorTip(err, htmlUrl));
  705. if (isWxDebugOn()) window.alert(wxInitLastError);
  706. console.warn("[wx.config]", errMsg, "htmlUrl=", htmlUrl);
  707. var baseUrl = getWxHtmlUrlBase();
  708. var fullUrl = getWxSignPageUrlForApi();
  709. if (
  710. !/invalid signature/i.test(errMsg) ||
  711. wxConfigSignRetriedBaseUrl ||
  712. baseUrl === fullUrl ||
  713. htmlUrl === baseUrl
  714. ) {
  715. resolve(false);
  716. return;
  717. }
  718. wxConfigSignRetriedBaseUrl = true;
  719. requestWeChatJssdkSignAndConfig(baseUrl).then(resolve);
  720. });
  721. });
  722. }
  723. function refreshWxLaunchTagAttrs() {
  724. var tag = document.getElementById("launch-btn");
  725. if (!tag) return;
  726. try {
  727. tag.setAttribute("appid", WECHAT_OPEN_APP_ID);
  728. tag.setAttribute("extinfo", buildWeChatLaunchExtinfo());
  729. } catch (eA) {}
  730. }
  731. function bindWeChatLaunchTagEvents() {
  732. var tag = document.getElementById("launch-btn");
  733. if (!tag || tag._wxLaunchBound) return;
  734. tag._wxLaunchBound = true;
  735. refreshWxLaunchTagAttrs();
  736. tag.addEventListener("launch", function () {
  737. console.log("[wx-open-launch-app] launch ok");
  738. });
  739. tag.addEventListener("error", function (e) {
  740. var detail = e && e.detail;
  741. var errMsg =
  742. detail && detail.errMsg
  743. ? String(detail.errMsg)
  744. : detail && detail.errmsg
  745. ? String(detail.errmsg)
  746. : "";
  747. console.warn("[wx-open-launch-app]", detail, "extinfo=", tag.getAttribute("extinfo"));
  748. if (/launch:fail_check/i.test(errMsg)) {
  749. showAppOpenFailTip(
  750. "微信唤起 App 校验失败,请确认开放标签域名与 App 关联配置正确"
  751. );
  752. return;
  753. }
  754. if (/launch:fail/i.test(errMsg)) {
  755. showAppOpenFailTip(
  756. "未能打开 App,请确认已安装最新版「U店在哪」,或从 App 内分享到微信后再打开"
  757. );
  758. return;
  759. }
  760. showAppOpenFailTip(
  761. errMsg
  762. ? "未能打开 App:" + errMsg
  763. : "未能打开 App,请确认已安装最新版「U店在哪」"
  764. );
  765. });
  766. }
  767. function initWeChatOpenLaunchApp(fromUserClick) {
  768. if (!shouldFetchWxConfig(!!fromUserClick)) {
  769. return Promise.resolve(false);
  770. }
  771. if (wxJssdkInitPromise && !fromUserClick) return wxJssdkInitPromise;
  772. wxConfigSignRetriedBaseUrl = false;
  773. wxInitLastError = "";
  774. var htmlUrl = getWxConfigSignUrl();
  775. bindWeChatLaunchTagEvents();
  776. wxJssdkInitPromise = requestWeChatJssdkSignAndConfig(htmlUrl)
  777. .then(function (ok) {
  778. if (ok === true) return true;
  779. if (!wxInitLastError) {
  780. setWxInitError("wx.config 失败,可加 ?wxDebug=1 查看 htmlUrl");
  781. }
  782. return false;
  783. })
  784. .catch(function (e) {
  785. var msg = e && e.message ? e.message : "getWxConfig 请求失败";
  786. setWxInitError(msg);
  787. console.warn("[wx] requestWeChatJssdkSignAndConfig failed", msg, "htmlUrl=", htmlUrl);
  788. if (isWeChatInAppBrowser() && isWxDebugOn()) window.alert(msg);
  789. return false;
  790. })
  791. .finally(function () {
  792. if (!weChatJssdkConfigured) wxJssdkInitPromise = null;
  793. });
  794. return wxJssdkInitPromise;
  795. }
  796. function scheduleWeChatJssdkBootstrap() {
  797. if (!shouldInitWeChatJssdkOnLoad()) return;
  798. var attempts = 0;
  799. function tick() {
  800. attempts += 1;
  801. if (weChatJssdkConfigured) return;
  802. initWeChatOpenLaunchApp();
  803. if (!weChatJssdkConfigured && attempts < 8 && typeof wx === "undefined") {
  804. setTimeout(tick, 400);
  805. }
  806. }
  807. if (isIOSWeChatBrowser()) {
  808. setTimeout(tick, 350);
  809. } else {
  810. tick();
  811. }
  812. }
  813. function showFabToast(msg, ms) {
  814. var tip = String(msg || "").trim();
  815. if (!tip) return;
  816. var el = document.getElementById("openAppToast");
  817. if (el) {
  818. el.textContent = tip;
  819. el.style.display = "block";
  820. if (showFabToast._t) clearTimeout(showFabToast._t);
  821. showFabToast._t = setTimeout(function () {
  822. el.style.display = "none";
  823. }, ms || 2800);
  824. }
  825. console.log("[openApp]", tip);
  826. }
  827. function showDownloadTip() {
  828. var msg = "请到应用商店下载「U店在哪」";
  829. if (typeof uni !== "undefined" && typeof uni.showToast === "function") {
  830. uni.showToast({ title: msg, icon: "none", duration: 2500 });
  831. } else {
  832. window.alert(msg);
  833. }
  834. }
  835. function showAppOpenFailTip(msg) {
  836. var tip = msg || "未能打开 App,请确认已安装最新版「U店在哪」。";
  837. if (typeof uni !== "undefined" && typeof uni.showToast === "function") {
  838. uni.showToast({ title: tip, icon: "none", duration: 2800 });
  839. } else {
  840. showFabToast(tip, 3200);
  841. }
  842. }
  843. function launchAppDeepLink(deepLink) {
  844. try {
  845. var a = document.createElement("a");
  846. a.href = deepLink;
  847. a.setAttribute("target", "_self");
  848. document.body.appendChild(a);
  849. a.click();
  850. document.body.removeChild(a);
  851. } catch (e1) {}
  852. try {
  853. window.location.href = deepLink;
  854. } catch (e2) {}
  855. }
  856. function tryOpenHBuilderAppViaScheme() {
  857. var deepLink = buildAppDeepLink();
  858. if (typeof plus !== "undefined" && plus.runtime) {
  859. var installed = null;
  860. try {
  861. if (typeof plus.runtime.isApplicationExist === "function") {
  862. installed = plus.runtime.isApplicationExist({
  863. pname: APP_ANDROID_PACKAGE,
  864. action: APP_IOS_URL_SCHEME,
  865. });
  866. }
  867. } catch (e) {
  868. console.warn(e);
  869. }
  870. try {
  871. plus.runtime.openURL(deepLink);
  872. } catch (e2) {
  873. console.warn(e2);
  874. if (installed === false) {
  875. showDownloadTip();
  876. }
  877. }
  878. return;
  879. }
  880. var done = false;
  881. function finish() {
  882. if (done) return;
  883. done = true;
  884. document.removeEventListener("visibilitychange", onVis);
  885. window.removeEventListener("pagehide", onHide);
  886. }
  887. function onVis() {
  888. if (document.visibilityState === "hidden") finish();
  889. }
  890. function onHide() {
  891. finish();
  892. }
  893. document.addEventListener("visibilitychange", onVis);
  894. window.addEventListener("pagehide", onHide);
  895. try {
  896. launchAppDeepLink(deepLink);
  897. } catch (e3) {
  898. finish();
  899. showDownloadTip();
  900. return;
  901. }
  902. window.setTimeout(function () {
  903. finish();
  904. }, 3200);
  905. }
  906. function tryOpenApp() {
  907. if (isWeChatInAppBrowser()) {
  908. if (!weChatJssdkConfigured) {
  909. showFabToast(wxInitLastError || "微信 SDK 初始化中,请稍候再点底部按钮");
  910. initWeChatOpenLaunchApp(true);
  911. }
  912. return;
  913. }
  914. tryOpenHBuilderAppViaScheme();
  915. }
  916. if (isWeChatInAppBrowser()) {
  917. document.body.classList.add("is-wechat");
  918. }
  919. document.addEventListener("WeixinOpenTagsError", function (e) {
  920. console.warn("[WeixinOpenTagsError]", e && e.detail);
  921. });
  922. var sharePayload = parsePayload();
  923. stripPayloadQueryFromUrl();
  924. bindWeChatLaunchTagEvents();
  925. document.getElementById("btnContinue").addEventListener("click", tryOpenApp);
  926. render(sharePayload);
  927. scheduleWeChatJssdkBootstrap();
  928. })();
  929. </script>
  930. </body>
  931. </html>