shareCheckInUndefined.html 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044
  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>打卡分享</title>
  8. <style>
  9. :root {
  10. --orange: #F58220;
  11. --text: #333333;
  12. --text-secondary: #999999;
  13. --border: #EEEEEE;
  14. --bg: #FFFFFF;
  15. --safe-bottom: env(safe-area-inset-bottom, 0px);
  16. }
  17. * {
  18. margin: 0;
  19. padding: 0;
  20. box-sizing: border-box;
  21. }
  22. html {
  23. font-size: 16px;
  24. -webkit-tap-highlight-color: transparent;
  25. overflow-x: hidden;
  26. }
  27. body {
  28. font-family: -apple-system, BlinkMacSystemFont, "PingFang SC", "Microsoft YaHei", "Helvetica Neue", sans-serif;
  29. background: var(--bg);
  30. color: var(--text);
  31. padding-bottom: calc(88px + var(--safe-bottom));
  32. min-height: 100vh;
  33. overflow-x: hidden;
  34. }
  35. .hero.hero--empty {
  36. display: flex;
  37. flex-direction: column;
  38. align-items: center;
  39. justify-content: center;
  40. padding: 48px 24px 56px;
  41. min-height: min(52vh, 440px);
  42. background: var(--bg);
  43. }
  44. .hero--empty__illustration {
  45. display: block;
  46. width: 100%;
  47. max-width: 280px;
  48. height: auto;
  49. object-fit: contain;
  50. }
  51. .hero--empty__tip {
  52. padding: 0 16px;
  53. margin-top: 12px;
  54. font-size: 15px;
  55. line-height: 1.5;
  56. color: var(--text-secondary);
  57. text-align: center;
  58. font-weight: 400;
  59. }
  60. .fab-wrap {
  61. position: fixed;
  62. left: 0;
  63. right: 0;
  64. bottom: 0;
  65. z-index: 200;
  66. padding: 12px 24px calc(12px + var(--safe-bottom));
  67. background: linear-gradient(to top, rgba(255, 255, 255, 0.98) 70%, transparent);
  68. pointer-events: none;
  69. }
  70. .fab-dock__slot {
  71. width: 100%;
  72. max-width: 198px;
  73. height: 48px;
  74. margin: 0 auto;
  75. pointer-events: auto;
  76. }
  77. #openApp.fab {
  78. padding: 0 10px;
  79. -webkit-font-smoothing: antialiased;
  80. text-rendering: optimizeLegibility;
  81. }
  82. .fab__brand-clip {
  83. display: block;
  84. flex-shrink: 0;
  85. line-height: 0;
  86. }
  87. .fab__brand-img {
  88. display: block;
  89. height: 26px;
  90. width: auto;
  91. max-width: none;
  92. pointer-events: none;
  93. -webkit-user-drag: none;
  94. }
  95. .fab__label {
  96. font-size: 15px;
  97. line-height: 1;
  98. letter-spacing: 0.04em;
  99. white-space: nowrap;
  100. }
  101. #launch-btn {
  102. display: none;
  103. width: 100%;
  104. height: 48px;
  105. min-height: 48px;
  106. border-radius: 24px;
  107. overflow: hidden;
  108. opacity: 1;
  109. }
  110. body.is-wechat.wx-jssdk-ready #launch-btn {
  111. display: block;
  112. }
  113. body.is-wechat.wx-jssdk-ready #openApp {
  114. display: none !important;
  115. }
  116. #openAppToast {
  117. display: none;
  118. position: fixed;
  119. left: 16px;
  120. right: 16px;
  121. bottom: calc(72px + var(--safe-bottom));
  122. z-index: 10001;
  123. padding: 10px 14px;
  124. font-size: 13px;
  125. line-height: 1.45;
  126. color: #fff;
  127. text-align: center;
  128. background: rgba(0, 0, 0, 0.78);
  129. border-radius: 8px;
  130. pointer-events: none;
  131. word-break: break-all;
  132. }
  133. #openApp {
  134. touch-action: manipulation;
  135. }
  136. .fab-wrap .fab {
  137. pointer-events: auto;
  138. }
  139. .fab {
  140. display: flex;
  141. align-items: center;
  142. justify-content: center;
  143. gap: 4px;
  144. width: 100%;
  145. max-width: 198px;
  146. margin: 0 auto;
  147. height: 48px;
  148. border: none;
  149. border-radius: 24px;
  150. background: var(--orange);
  151. color: #fff;
  152. font-size: 16px;
  153. font-weight: 600;
  154. box-shadow: 0 4px 16px rgba(245, 130, 32, 0.45);
  155. cursor: pointer;
  156. }
  157. .home-indicator {
  158. height: 5px;
  159. background: #000;
  160. border-radius: 3px;
  161. width: 134px;
  162. margin: 8px auto 4px;
  163. opacity: 0.2;
  164. }
  165. </style>
  166. </head>
  167. <body>
  168. <div class="hero hero--empty" role="status" aria-live="polite">
  169. <img class="hero--empty__illustration" id="heroEmptyIllustration" src="images/empty.png" alt="" decoding="async">
  170. <p class="hero--empty__tip" id="heroEmptyTip">内容已删除</p>
  171. </div>
  172. <div id="openAppToast" role="status" aria-live="polite"></div>
  173. <div class="fab-wrap">
  174. <div class="fab-dock__slot">
  175. <!-- 非微信 / 微信 JSSDK 未就绪:scheme 唤起 -->
  176. <button type="button" class="fab" id="openApp" aria-label="APP内打开">
  177. <span class="fab__brand-clip" aria-hidden="true">
  178. <img class="fab__brand-img" src="images/uBtn.svg" alt="" decoding="async">
  179. </span>
  180. <span class="fab__label">APP内打开</span>
  181. </button>
  182. <!-- 微信内 wx.config 成功后:仅此按钮可唤起 App(须用户直接点击) -->
  183. <wx-open-launch-app id="launch-btn" appid="wxf5f1efe3a9f5012e" extinfo="">
  184. <script type="text/wxtag-template">
  185. <style>
  186. .wx-open-app-btn {
  187. display: flex;
  188. align-items: center;
  189. justify-content: center;
  190. gap: 4px;
  191. width: 100%;
  192. height: 48px;
  193. margin: 0;
  194. padding: 0 10px;
  195. border: none;
  196. border-radius: 24px;
  197. background: #F47D1F;
  198. box-shadow: 0 4px 16px rgba(245, 130, 32, 0.45);
  199. color: #fff;
  200. font-family: -apple-system, BlinkMacSystemFont, "PingFang SC", "Helvetica Neue", sans-serif;
  201. -webkit-font-smoothing: antialiased;
  202. cursor: pointer;
  203. overflow: hidden;
  204. -webkit-tap-highlight-color: transparent;
  205. box-sizing: border-box;
  206. }
  207. .wx-open-app-btn .fab__brand-clip {
  208. display: block;
  209. flex-shrink: 0;
  210. line-height: 0;
  211. }
  212. .wx-open-app-btn .fab__brand-img {
  213. display: block;
  214. height: 26px;
  215. width: auto;
  216. max-width: none;
  217. pointer-events: none;
  218. -webkit-user-drag: none;
  219. }
  220. .wx-open-app-btn .fab__label {
  221. font-size: 15px;
  222. line-height: 1;
  223. letter-spacing: 0.04em;
  224. white-space: nowrap;
  225. }
  226. </style>
  227. <button class="wx-open-app-btn" aria-label="APP内打开">
  228. <span class="fab__brand-clip" aria-hidden="true">
  229. <img class="fab__brand-img" src="https://prod.ailien.shop/h5/HBuilderProjects/images/uBtn.svg" alt="" decoding="async">
  230. </span>
  231. <span class="fab__label">APP内打开</span>
  232. </button>
  233. </script>
  234. </wx-open-launch-app>
  235. </div>
  236. <div class="home-indicator" aria-hidden="true"></div>
  237. </div>
  238. <script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
  239. <script>
  240. (function () {
  241. 'use strict';
  242. /**
  243. * businessStatus=99(关店,与 shareIndex.html 一致):点「APP内打开」深链为 shopro://pages/index/login?…,不再进打卡页。
  244. */
  245. var API_BASE = 'https://prod.ailien.shop/alienStore';
  246. /**
  247. * 微信 JSSDK — 与 shareIndex.html 一致
  248. * POST {API_BASE}/wx/getWxConfig,body 传 url(当前页完整地址,不含 #)
  249. */
  250. var WECHAT_MP_APP_ID = 'wx412792c77f47babd';
  251. var WECHAT_OPEN_APP_ID = 'wxf5f1efe3a9f5012e';
  252. var WECHAT_GET_WX_CONFIG_PATH = '/wx/getWxConfig';
  253. var H5_PAGE_BASE_FALLBACK = 'https://prod.ailien.shop/h5/HBuilderProjects/';
  254. var WX_GET_CONFIG_SIGN_URL = H5_PAGE_BASE_FALLBACK + 'shareCheckInUndefined.html';
  255. var WECHAT_JS_SAFE_HOSTS = ['uat.ailien.shop', 'prod.ailien.shop'];
  256. var weChatJssdkConfigured = false;
  257. var wxConfigSignRetriedBaseUrl = false;
  258. var wxInitLastError = '';
  259. var wxJssdkInitPromise = null;
  260. var APP_ANDROID_PACKAGE = 'com.alien.Udianzaizhe';
  261. var APP_IOS_URL_SCHEME = 'shopro://';
  262. var APP_UNI_STORE_PATH = 'pages/checkIn/index';
  263. function q(name) {
  264. var v = mergeSearchAndHashParams().get(name);
  265. return v == null ? '' : String(v);
  266. }
  267. function showDownloadTip() {
  268. var msg = '请到应用商店下载';
  269. if (typeof uni !== 'undefined' && typeof uni.showToast === 'function') {
  270. uni.showToast({ title: msg, icon: 'none', duration: 2500 });
  271. } else {
  272. window.alert(msg);
  273. }
  274. }
  275. function mergeSearchAndHashParams() {
  276. var params = new URLSearchParams();
  277. function ingestAppend(querySlice) {
  278. if (!querySlice) return;
  279. var p = new URLSearchParams(querySlice);
  280. p.forEach(function (val, key) {
  281. params.append(key, val);
  282. });
  283. }
  284. function ingestSet(querySlice) {
  285. if (!querySlice) return;
  286. var p = new URLSearchParams(querySlice);
  287. p.forEach(function (val, key) {
  288. params.set(key, val);
  289. });
  290. }
  291. if (location.search && location.search.length > 1) {
  292. ingestAppend(location.search.slice(1));
  293. }
  294. var hash = location.hash || '';
  295. var qi = hash.indexOf('?');
  296. if (qi >= 0) {
  297. ingestSet(hash.slice(qi + 1));
  298. }
  299. return params;
  300. }
  301. function getRawMergedQueryForAppOpen() {
  302. var rawSearch =
  303. location.search && location.search.length > 1 ? location.search.slice(1) : '';
  304. var hash0 = location.hash || '';
  305. var hqi0 = hash0.indexOf('?');
  306. var rawHashQ = hqi0 >= 0 ? hash0.slice(hqi0 + 1) : '';
  307. if (!rawSearch && !rawHashQ) return '';
  308. if (rawHashQ && rawSearch) {
  309. return rawHashQ;
  310. }
  311. return rawHashQ || rawSearch;
  312. }
  313. /**
  314. * 关店 businessStatus=99:URL(含 hash)带 businessStatus=99 时,唤起 App 进 pages/index/login(与 shareIndex.html isClosedMerchantForAppOpen)。
  315. */
  316. function isClosedMerchantForAppOpen() {
  317. try {
  318. var bs = String(mergeSearchAndHashParams().get('businessStatus') || '').trim();
  319. if (bs === '99' || Number(bs) === 99) return true;
  320. } catch (e0) {}
  321. return false;
  322. }
  323. function getAppUniPathForCheckInShare() {
  324. if (isClosedMerchantForAppOpen()) {
  325. return 'pages/index/login';
  326. }
  327. var p = mergeSearchAndHashParams();
  328. if (!p.has('isShareCheckInSquare')) {
  329. return String(APP_UNI_STORE_PATH || 'pages/checkIn/index').replace(/^\//, '');
  330. }
  331. var v = String(p.get('isShareCheckInSquare') || '').trim().toLowerCase();
  332. if (v === '' || v === '0' || v === 'false' || v === 'no') {
  333. return String(APP_UNI_STORE_PATH || 'pages/checkIn/index').replace(/^\//, '');
  334. }
  335. return 'pages/checkIn/details';
  336. }
  337. /** businessStatus=99(商户关闭):插图与文案;否则为「内容已删除」 */
  338. function applyEmptyHeroState() {
  339. var merged = mergeSearchAndHashParams();
  340. var bsRaw = merged.get('businessStatus');
  341. var bs = bsRaw == null ? '' : String(bsRaw).trim();
  342. var isClosed = Number(bs) === 99 || bs === '99';
  343. var img = document.getElementById('heroEmptyIllustration');
  344. var tip = document.getElementById('heroEmptyTip');
  345. if (!img || !tip) return;
  346. if (isClosed) {
  347. img.src = 'images/storeNone.png';
  348. img.alt = '';
  349. tip.textContent = '抱歉商户已关闭,看看别的吧';
  350. } else {
  351. img.src = 'images/empty.png';
  352. img.alt = '';
  353. tip.textContent = '内容已删除';
  354. }
  355. img.onerror = function () {
  356. this.onerror = null;
  357. this.src = 'images/empty.png';
  358. };
  359. if (weChatJssdkConfigured) {
  360. refreshWxLaunchTagAttrs();
  361. }
  362. }
  363. function buildAppOpenQueryStringMerged() {
  364. var rawQs = getRawMergedQueryForAppOpen();
  365. if (rawQs) {
  366. return '?' + rawQs;
  367. }
  368. var params = mergeSearchAndHashParams();
  369. var sid = params.get('storeId') || params.get('id') || '';
  370. if (sid && !params.has('storeId')) {
  371. params.set('storeId', sid);
  372. }
  373. var qsOut = params.toString();
  374. return qsOut ? ('?' + qsOut) : '';
  375. }
  376. function buildAppUniPageLaunchUrl() {
  377. var path = getAppUniPathForCheckInShare().replace(/^\//, '');
  378. var qs = buildAppOpenQueryStringMerged().replace(/^\?/, '');
  379. return qs ? path + '?' + qs : path;
  380. }
  381. /**
  382. * wx-open-launch-app extinfo:pages/checkIn/index、pages/checkIn/details 或关店 pages/index/login
  383. */
  384. function buildWeChatLaunchExtinfo() {
  385. var uniPage = buildAppUniPageLaunchUrl();
  386. if (uniPage.length <= 1024) return uniPage;
  387. var path = getAppUniPathForCheckInShare().replace(/^\//, '');
  388. var rawQs = getRawMergedQueryForAppOpen();
  389. if (rawQs) {
  390. var packedRaw = path + '?' + rawQs;
  391. if (packedRaw.length <= 1024) return packedRaw;
  392. }
  393. var params = mergeSearchAndHashParams();
  394. var mini = new URLSearchParams();
  395. var storeId = params.get('storeId') || params.get('id') || '';
  396. if (storeId) mini.set('storeId', storeId);
  397. var square = params.get('isShareCheckInSquare');
  398. if (square != null && String(square).trim() !== '') {
  399. mini.set('isShareCheckInSquare', String(square).trim());
  400. }
  401. var bs = params.get('businessStatus');
  402. if (bs != null && String(bs).trim() !== '') {
  403. mini.set('businessStatus', String(bs).trim());
  404. }
  405. var shortPage = path + '?' + mini.toString();
  406. if (shortPage.length <= 1024) return shortPage;
  407. var deep = buildAppDeepLink().replace(/^shopro:\/\//i, '');
  408. return deep.length <= 1024 ? deep : shortPage.slice(0, 1024);
  409. }
  410. function buildAppDeepLink() {
  411. var path = getAppUniPathForCheckInShare().replace(/^\//, '');
  412. var s = buildAppOpenQueryStringMerged();
  413. var root = APP_IOS_URL_SCHEME.replace(/\/$/, '');
  414. if (!s) {
  415. return root + '/' + path;
  416. }
  417. return root + '/' + path + s;
  418. }
  419. function isWeChatInAppBrowser() {
  420. return /MicroMessenger/i.test(navigator.userAgent || '');
  421. }
  422. function getWxShareEntryFrom() {
  423. var from = q('from');
  424. if (from) return String(from).trim().toLowerCase();
  425. try {
  426. var h = location.hash || '';
  427. var qi = h.indexOf('?');
  428. if (qi >= 0) {
  429. var hf = new URLSearchParams(h.slice(qi + 1)).get('from');
  430. if (hf) return String(hf).trim().toLowerCase();
  431. }
  432. } catch (eH) {}
  433. try {
  434. var sf = new URLSearchParams(location.search || '').get('from');
  435. if (sf) return String(sf).trim().toLowerCase();
  436. } catch (eS) {}
  437. return '';
  438. }
  439. function isIOSWeChatBrowser() {
  440. var ua = navigator.userAgent || '';
  441. return /MicroMessenger/i.test(ua) && /iPhone|iPad|iPod/i.test(ua);
  442. }
  443. function logWxEntryDiagnostics() {
  444. if (!isWeChatInAppBrowser()) return;
  445. console.log('[wx-entry]', {
  446. entryFrom: getWxShareEntryFrom() || '(无)',
  447. wxJssdkReady: weChatJssdkConfigured,
  448. signUrl: getWxConfigSignUrl()
  449. });
  450. }
  451. function readQueryParam(name) {
  452. return q(name);
  453. }
  454. function isWxDebugOn() {
  455. return readQueryParam('wxDebug') === '1';
  456. }
  457. function isWxForceDebug() {
  458. return readQueryParam('wxForce') === '1';
  459. }
  460. function isWxConfigOnClickDebug() {
  461. return readQueryParam('wxConfigOnClick') === '1';
  462. }
  463. function isWxPcAutoDebugHost() {
  464. var h = (location.hostname || '').toLowerCase();
  465. if (h === 'localhost' || h === '127.0.0.1') return true;
  466. for (var i = 0; i < WECHAT_JS_SAFE_HOSTS.length; i++) {
  467. if (WECHAT_JS_SAFE_HOSTS[i] === h) return true;
  468. }
  469. return false;
  470. }
  471. function isWxPcBrowser() {
  472. return !isWeChatInAppBrowser();
  473. }
  474. function shouldInitWeChatJssdkOnLoad() {
  475. if (isWeChatInAppBrowser()) return true;
  476. return isWxForceDebug() || isWxPcAutoDebugHost();
  477. }
  478. function shouldFetchWxConfig(fromUserClick) {
  479. if (isWeChatInAppBrowser()) return true;
  480. if (fromUserClick) return true;
  481. return isWxForceDebug() || isWxPcAutoDebugHost();
  482. }
  483. function getWxHtmlUrl() {
  484. var forced = String(q('wxSignUrl') || '').trim();
  485. if (forced) return forced.split('#')[0];
  486. return String(location.href || '').split('#')[0];
  487. }
  488. function getWxSignPageUrlForApi() {
  489. var htmlUrl = getWxHtmlUrl();
  490. if (htmlUrl && /^https?:\/\//i.test(htmlUrl)) return htmlUrl;
  491. return WX_GET_CONFIG_SIGN_URL;
  492. }
  493. function getWxHtmlUrlBase() {
  494. var htmlUrl = getWxSignPageUrlForApi();
  495. try {
  496. var u = new URL(htmlUrl);
  497. return u.origin + u.pathname;
  498. } catch (eU) {
  499. return WX_GET_CONFIG_SIGN_URL;
  500. }
  501. }
  502. function getWxConfigSignUrl() {
  503. if (String(q('wxSignBaseOnly') || '') === '1') return getWxHtmlUrlBase();
  504. return getWxSignPageUrlForApi();
  505. }
  506. function getWxGetConfigApiUrl() {
  507. return API_BASE.replace(/\/$/, '') + WECHAT_GET_WX_CONFIG_PATH;
  508. }
  509. function buildWxGetConfigRequestBody(htmlUrl) {
  510. return {
  511. url: String(htmlUrl || '').split('#')[0].trim()
  512. };
  513. }
  514. function resolveWxConfigAppIdFromSignData(d) {
  515. if (!d || typeof d !== 'object') return '';
  516. var mp =
  517. d.mpAppId ||
  518. d.mpAppid ||
  519. d.officialAppId ||
  520. d.gzhAppId ||
  521. d.serviceAppId;
  522. if (mp != null && String(mp).trim() !== '') return String(mp).trim();
  523. var fromQuery = String(q('wxMpAppId') || WECHAT_MP_APP_ID || '').trim();
  524. if (fromQuery) return fromQuery;
  525. var raw = d.appId || d.appid || d.wxAppId;
  526. return raw != null && String(raw).trim() !== '' ? String(raw).trim() : '';
  527. }
  528. function normalizeWxJssdkSignPayload(res, signUrlUsed) {
  529. if (!res || typeof res !== 'object') return null;
  530. var d = res.data != null && typeof res.data === 'object' ? res.data : res;
  531. if (!d || typeof d !== 'object') return null;
  532. var appId = resolveWxConfigAppIdFromSignData(d);
  533. var timestamp = d.timestamp != null ? d.timestamp : d.timeStamp;
  534. var nonceStr =
  535. d.nonceStr != null && String(d.nonceStr) !== ''
  536. ? d.nonceStr
  537. : d.noncestr != null && String(d.noncestr) !== ''
  538. ? d.noncestr
  539. : d.nonce;
  540. var signature = d.signature || d.sign;
  541. if (!appId || timestamp == null || nonceStr == null || nonceStr === '' || !signature) {
  542. return null;
  543. }
  544. return {
  545. appId: String(appId),
  546. timestamp: Number(timestamp),
  547. nonceStr: String(nonceStr),
  548. signature: String(signature),
  549. signUrl: String(signUrlUsed || '')
  550. .split('#')[0]
  551. .trim()
  552. };
  553. }
  554. function getWxErrMsg(err) {
  555. if (!err) return '';
  556. if (err.errMsg) return String(err.errMsg);
  557. if (typeof err === 'string') return err;
  558. try {
  559. return JSON.stringify(err);
  560. } catch (e) {
  561. return String(err);
  562. }
  563. }
  564. function formatWxConfigErrorTip(err, signPageUrl) {
  565. var errMsg = getWxErrMsg(err);
  566. var tip = '微信 JSSDK 配置失败';
  567. if (/invalid signature/i.test(errMsg)) {
  568. return (
  569. tip +
  570. ':签名无效。请核对:①后端用与前端相同的 url 签名;②url=' +
  571. (signPageUrl || getWxHtmlUrl()) +
  572. ';③nonceStr/timestamp 与接口返回一致;④appId=' +
  573. WECHAT_MP_APP_ID
  574. );
  575. }
  576. if (/require\s*subscribe/i.test(errMsg)) {
  577. return tip + ':' + errMsg + '(服务号需用户已关注)';
  578. }
  579. return errMsg ? tip + ':' + errMsg : tip;
  580. }
  581. function setWxInitError(msg) {
  582. wxInitLastError = String(msg || '').trim();
  583. if (wxInitLastError) console.warn('[wx]', wxInitLastError);
  584. }
  585. function requestWeChatJssdkSignAndConfig(htmlUrlOptional) {
  586. var htmlUrl = String(
  587. htmlUrlOptional != null ? htmlUrlOptional : getWxConfigSignUrl()
  588. )
  589. .split('#')[0]
  590. .trim();
  591. if (!htmlUrl || !/^https?:\/\//i.test(htmlUrl)) {
  592. htmlUrl = WX_GET_CONFIG_SIGN_URL;
  593. }
  594. if (isWxDebugOn()) {
  595. try {
  596. window.alert('htmlUrl(签名用):\n' + htmlUrl);
  597. } catch (eDbg) {}
  598. }
  599. var requestUrl = getWxGetConfigApiUrl();
  600. var requestBody = buildWxGetConfigRequestBody(htmlUrl);
  601. console.log('[wx] htmlUrl=', htmlUrl);
  602. console.log('[wx] POST getWxConfig →', requestUrl, requestBody);
  603. return fetch(requestUrl, {
  604. method: 'POST',
  605. mode: 'cors',
  606. credentials: 'omit',
  607. headers: {
  608. Accept: 'application/json',
  609. 'Content-Type': 'application/json;charset=UTF-8'
  610. },
  611. body: JSON.stringify(requestBody)
  612. })
  613. .then(function (r) {
  614. if (r.ok) return r.json();
  615. return r
  616. .text()
  617. .catch(function () {
  618. return '';
  619. })
  620. .then(function (text) {
  621. var hint = '';
  622. try {
  623. var j = JSON.parse(text);
  624. hint = j.msg || j.message || '';
  625. } catch (eP) {
  626. if (text) hint = text.slice(0, 120);
  627. }
  628. throw new Error('getWxConfig HTTP ' + r.status + (hint ? ':' + hint : ''));
  629. });
  630. })
  631. .then(function (res) {
  632. if (res && res.code != null) {
  633. var c = Number(res.code);
  634. if (c !== 200 && c !== 0 && res.success !== true) {
  635. throw new Error(res.msg || res.message || 'getWxConfig code ' + c);
  636. }
  637. }
  638. var sign = normalizeWxJssdkSignPayload(res, htmlUrl);
  639. if (!sign) {
  640. console.warn('[wx] getWxConfig 响应字段不全', res, 'htmlUrl=', htmlUrl);
  641. throw new Error(
  642. 'getWxConfig 缺少 appId/timestamp/nonceStr/signature(见控制台)'
  643. );
  644. }
  645. if (sign.appId !== WECHAT_MP_APP_ID) {
  646. console.warn(
  647. '[wx] 后端 appId=' + sign.appId + ',期望服务号 ' + WECHAT_MP_APP_ID
  648. );
  649. }
  650. if (typeof wx === 'undefined') {
  651. if (isWxPcBrowser()) {
  652. console.log('[wx] PC getWxConfig 成功(无 jweixin)', sign);
  653. return true;
  654. }
  655. setWxInitError('jweixin.js 未加载');
  656. return false;
  657. }
  658. return applyWxConfigFromSign(sign, htmlUrl);
  659. });
  660. }
  661. function applyWxConfigFromSign(sign, htmlUrl) {
  662. var wxConfigParams = {
  663. debug: isWxDebugOn(),
  664. appId: String(sign.appId),
  665. timestamp: sign.timestamp,
  666. nonceStr: String(sign.nonceStr),
  667. signature: String(sign.signature),
  668. jsApiList: [],
  669. openTagList: ['wx-open-launch-app']
  670. };
  671. return new Promise(function (resolve) {
  672. wx.config(wxConfigParams);
  673. wx.ready(function () {
  674. weChatJssdkConfigured = true;
  675. document.body.classList.add('wx-jssdk-ready');
  676. refreshWxLaunchTagAttrs();
  677. console.log('[wx.config] ready, htmlUrl=', htmlUrl);
  678. resolve(true);
  679. });
  680. wx.error(function (err) {
  681. weChatJssdkConfigured = false;
  682. document.body.classList.remove('wx-jssdk-ready');
  683. wxJssdkInitPromise = null;
  684. var errMsg = getWxErrMsg(err);
  685. setWxInitError(formatWxConfigErrorTip(err, htmlUrl));
  686. if (isWxDebugOn()) window.alert(wxInitLastError);
  687. console.warn('[wx.config]', errMsg, 'htmlUrl=', htmlUrl);
  688. var baseUrl = getWxHtmlUrlBase();
  689. var fullUrl = getWxSignPageUrlForApi();
  690. if (
  691. !/invalid signature/i.test(errMsg) ||
  692. wxConfigSignRetriedBaseUrl ||
  693. baseUrl === fullUrl ||
  694. htmlUrl === baseUrl
  695. ) {
  696. resolve(false);
  697. return;
  698. }
  699. wxConfigSignRetriedBaseUrl = true;
  700. requestWeChatJssdkSignAndConfig(baseUrl).then(resolve);
  701. });
  702. });
  703. }
  704. function refreshWxLaunchTagAttrs() {
  705. var tag = document.getElementById('launch-btn');
  706. if (!tag) return;
  707. try {
  708. tag.setAttribute('appid', WECHAT_OPEN_APP_ID);
  709. tag.setAttribute('extinfo', buildWeChatLaunchExtinfo());
  710. } catch (eA) {}
  711. }
  712. function bindWeChatLaunchTagEvents() {
  713. var tag = document.getElementById('launch-btn');
  714. if (!tag || tag._wxLaunchBound) return;
  715. tag._wxLaunchBound = true;
  716. refreshWxLaunchTagAttrs();
  717. tag.addEventListener('launch', function () {
  718. console.log('[wx-open-launch-app] launch ok');
  719. // showFabToast('正在打开 U店在哪…');
  720. });
  721. tag.addEventListener('error', function (e) {
  722. var detail = e && e.detail;
  723. var errMsg =
  724. detail && detail.errMsg
  725. ? String(detail.errMsg)
  726. : detail && detail.errmsg
  727. ? String(detail.errmsg)
  728. : '';
  729. console.warn('[wx-open-launch-app]', detail);
  730. if (/launch:fail/i.test(errMsg) && !getWxShareEntryFrom()) {
  731. showAppOpenFailTip(
  732. '当前环境无法直接打开 App,请使用 App「分享到微信」后点分享卡片进入'
  733. );
  734. } else {
  735. showAppOpenFailTip(
  736. errMsg
  737. ? '未能打开 App:' + errMsg
  738. : '未能打开 App,请确认已安装最新版「U店在哪」'
  739. );
  740. }
  741. });
  742. }
  743. function initWeChatOpenLaunchApp(fromUserClick) {
  744. if (!shouldFetchWxConfig(!!fromUserClick)) {
  745. console.log('[wx] 未调用 getWxConfig');
  746. return Promise.resolve(false);
  747. }
  748. if (isWxPcBrowser()) {
  749. console.warn(
  750. '[wx] PC:请求 getWxConfig' + (fromUserClick ? '(按钮)' : '(进页)')
  751. );
  752. }
  753. if (wxJssdkInitPromise && !fromUserClick) return wxJssdkInitPromise;
  754. wxConfigSignRetriedBaseUrl = false;
  755. wxInitLastError = '';
  756. var htmlUrl = getWxConfigSignUrl();
  757. bindWeChatLaunchTagEvents();
  758. wxJssdkInitPromise = requestWeChatJssdkSignAndConfig(htmlUrl)
  759. .then(function (ok) {
  760. if (ok === true) return true;
  761. if (!wxInitLastError) {
  762. setWxInitError('wx.config 失败,可加 ?wxDebug=1 查看 htmlUrl');
  763. }
  764. return false;
  765. })
  766. .catch(function (e) {
  767. var msg = e && e.message ? e.message : 'getWxConfig 请求失败';
  768. setWxInitError(msg);
  769. console.warn('[wx] requestWeChatJssdkSignAndConfig failed', msg, 'htmlUrl=', htmlUrl);
  770. if (isWeChatInAppBrowser() && isWxDebugOn()) window.alert(msg);
  771. return false;
  772. })
  773. .finally(function () {
  774. if (!weChatJssdkConfigured) wxJssdkInitPromise = null;
  775. });
  776. return wxJssdkInitPromise;
  777. }
  778. /** 进页即尝试拉签名;jweixin 晚到时自动重试 */
  779. function scheduleWeChatJssdkBootstrap() {
  780. if (!shouldInitWeChatJssdkOnLoad()) return;
  781. var attempts = 0;
  782. function tick() {
  783. attempts += 1;
  784. if (weChatJssdkConfigured) return;
  785. initWeChatOpenLaunchApp();
  786. if (!weChatJssdkConfigured && attempts < 8 && typeof wx === 'undefined') {
  787. setTimeout(tick, 400);
  788. }
  789. }
  790. if (isIOSWeChatBrowser()) {
  791. setTimeout(tick, 350);
  792. } else {
  793. tick();
  794. }
  795. }
  796. function showFabToast(msg, ms) {
  797. var tip = String(msg || '').trim();
  798. if (!tip) return;
  799. var el = document.getElementById('openAppToast');
  800. if (el) {
  801. el.textContent = tip;
  802. el.style.display = 'block';
  803. if (showFabToast._t) clearTimeout(showFabToast._t);
  804. showFabToast._t = setTimeout(function () {
  805. el.style.display = 'none';
  806. }, ms || 2800);
  807. }
  808. console.log('[openApp]', tip);
  809. }
  810. function showAppOpenFailTip(msg) {
  811. var tip = msg || '未能打开 App,请确认已安装最新版「U店在哪」。';
  812. if (typeof uni !== 'undefined' && typeof uni.showToast === 'function') {
  813. uni.showToast({ title: tip, icon: 'none', duration: 2800 });
  814. } else if (isWeChatInAppBrowser()) {
  815. window.alert(tip);
  816. } else {
  817. console.warn('[openApp]', tip);
  818. }
  819. }
  820. function tryFetchWxConfigOnPcClick() {
  821. if (!isWxPcBrowser()) return Promise.resolve(false);
  822. showFabToast('正在请求 getWxConfig…');
  823. wxJssdkInitPromise = null;
  824. return initWeChatOpenLaunchApp(true).then(function (ok) {
  825. if (ok) {
  826. showFabToast(
  827. weChatJssdkConfigured
  828. ? 'getWxConfig 成功,wx.config 已就绪'
  829. : 'getWxConfig 成功'
  830. );
  831. } else {
  832. showFabToast(wxInitLastError || 'getWxConfig 失败');
  833. }
  834. return ok;
  835. });
  836. }
  837. function launchAppDeepLink(deepLink) {
  838. try {
  839. var a = document.createElement('a');
  840. a.href = deepLink;
  841. a.setAttribute('target', '_self');
  842. document.body.appendChild(a);
  843. a.click();
  844. document.body.removeChild(a);
  845. } catch (e1) {}
  846. try {
  847. window.location.href = deepLink;
  848. } catch (e2) {}
  849. }
  850. function tryOpenHBuilderApp() {
  851. /* 微信内须直接点击 wx-open-launch-app,scheme 会被拦截 */
  852. if (isWeChatInAppBrowser()) return;
  853. tryFetchWxConfigOnPcClick().then(function () {
  854. if (isWxConfigOnClickDebug() && !isWxForceDebug() && !isWxPcAutoDebugHost()) {
  855. return;
  856. }
  857. tryOpenHBuilderAppViaScheme();
  858. });
  859. }
  860. function tryOpenHBuilderAppViaScheme() {
  861. // showFabToast('正在打开 U店在哪…');
  862. var deepLink = buildAppDeepLink();
  863. if (typeof plus !== 'undefined' && plus.runtime) {
  864. var installed = null;
  865. try {
  866. if (typeof plus.runtime.isApplicationExist === 'function') {
  867. installed = plus.runtime.isApplicationExist({
  868. pname: APP_ANDROID_PACKAGE,
  869. action: APP_IOS_URL_SCHEME
  870. });
  871. }
  872. } catch (e) {
  873. console.warn(e);
  874. }
  875. if (installed === false) {
  876. showDownloadTip();
  877. return;
  878. }
  879. try {
  880. plus.runtime.openURL(deepLink);
  881. } catch (e2) {
  882. console.warn(e2);
  883. showDownloadTip();
  884. }
  885. return;
  886. }
  887. var done = false;
  888. function finish() {
  889. if (done) return;
  890. done = true;
  891. document.removeEventListener('visibilitychange', onVis);
  892. window.removeEventListener('pagehide', onHide);
  893. }
  894. function onVis() {
  895. if (document.visibilityState === 'hidden') finish();
  896. }
  897. function onHide() {
  898. finish();
  899. }
  900. document.addEventListener('visibilitychange', onVis);
  901. window.addEventListener('pagehide', onHide);
  902. try {
  903. launchAppDeepLink(deepLink);
  904. } catch (e3) {
  905. finish();
  906. showDownloadTip();
  907. return;
  908. }
  909. window.setTimeout(function () {
  910. finish();
  911. }, 2600);
  912. }
  913. function boot() {
  914. var launchTag = document.getElementById('launch-btn');
  915. if (launchTag) launchTag.setAttribute('appid', WECHAT_OPEN_APP_ID);
  916. bindWeChatLaunchTagEvents();
  917. if (isWeChatInAppBrowser()) {
  918. document.body.classList.add('is-wechat');
  919. logWxEntryDiagnostics();
  920. }
  921. if (shouldInitWeChatJssdkOnLoad()) {
  922. if (isWxPcBrowser() && (isWxForceDebug() || isWxPcAutoDebugHost())) {
  923. document.body.classList.add('wx-pc-debug');
  924. }
  925. scheduleWeChatJssdkBootstrap();
  926. }
  927. document.addEventListener('WeixinOpenTagsError', function (e) {
  928. console.warn('[WeixinOpenTagsError]', e && e.detail);
  929. });
  930. applyEmptyHeroState();
  931. if (isWeChatInAppBrowser()) {
  932. var openBtnWx = document.getElementById('openApp');
  933. if (openBtnWx) {
  934. openBtnWx.addEventListener('click', function () {
  935. if (!weChatJssdkConfigured) {
  936. showFabToast(
  937. wxInitLastError || '微信 SDK 初始化中,请稍候再点底部按钮'
  938. );
  939. return;
  940. }
  941. });
  942. }
  943. } else {
  944. var openBtn = document.getElementById('openApp');
  945. if (openBtn) {
  946. openBtn.addEventListener('click', tryOpenHBuilderApp);
  947. }
  948. }
  949. }
  950. if (document.readyState === 'complete') {
  951. boot();
  952. } else {
  953. window.onload = boot;
  954. }
  955. })();
  956. </script>
  957. </body>
  958. </html>