shareAiConsult.html 31 KB

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