shareAiConsult.html 33 KB

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