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