shareAiConsult.html 33 KB

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