shareAiConsult.html 32 KB

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