shareAiConsult.html 31 KB

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