shareAiConsult.html 33 KB

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