shareAiConsult.html 31 KB

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