shareCheckInUndefined.html 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040
  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_DOWNLOAD_URL = 'https://a.app.qq.com/o/simple.jsp?pkgname=com.alien.Udianzaina';
  262. var APP_IOS_URL_SCHEME = 'shopro://';
  263. var APP_UNI_STORE_PATH = 'pages/checkIn/index';
  264. function q(name) {
  265. var v = mergeSearchAndHashParams().get(name);
  266. return v == null ? '' : String(v);
  267. }
  268. function showDownloadTip() {
  269. window.location.href = APP_DOWNLOAD_URL;
  270. }
  271. function mergeSearchAndHashParams() {
  272. var params = new URLSearchParams();
  273. function ingestAppend(querySlice) {
  274. if (!querySlice) return;
  275. var p = new URLSearchParams(querySlice);
  276. p.forEach(function (val, key) {
  277. params.append(key, val);
  278. });
  279. }
  280. function ingestSet(querySlice) {
  281. if (!querySlice) return;
  282. var p = new URLSearchParams(querySlice);
  283. p.forEach(function (val, key) {
  284. params.set(key, val);
  285. });
  286. }
  287. if (location.search && location.search.length > 1) {
  288. ingestAppend(location.search.slice(1));
  289. }
  290. var hash = location.hash || '';
  291. var qi = hash.indexOf('?');
  292. if (qi >= 0) {
  293. ingestSet(hash.slice(qi + 1));
  294. }
  295. return params;
  296. }
  297. function getRawMergedQueryForAppOpen() {
  298. var rawSearch =
  299. location.search && location.search.length > 1 ? location.search.slice(1) : '';
  300. var hash0 = location.hash || '';
  301. var hqi0 = hash0.indexOf('?');
  302. var rawHashQ = hqi0 >= 0 ? hash0.slice(hqi0 + 1) : '';
  303. if (!rawSearch && !rawHashQ) return '';
  304. if (rawHashQ && rawSearch) {
  305. return rawHashQ;
  306. }
  307. return rawHashQ || rawSearch;
  308. }
  309. /**
  310. * 关店 businessStatus=99:URL(含 hash)带 businessStatus=99 时,唤起 App 进 pages/index/login(与 shareIndex.html isClosedMerchantForAppOpen)。
  311. */
  312. function isClosedMerchantForAppOpen() {
  313. try {
  314. var bs = String(mergeSearchAndHashParams().get('businessStatus') || '').trim();
  315. if (bs === '99' || Number(bs) === 99) return true;
  316. } catch (e0) {}
  317. return false;
  318. }
  319. function getAppUniPathForCheckInShare() {
  320. if (isClosedMerchantForAppOpen()) {
  321. return 'pages/index/login';
  322. }
  323. var p = mergeSearchAndHashParams();
  324. if (!p.has('isShareCheckInSquare')) {
  325. return String(APP_UNI_STORE_PATH || 'pages/checkIn/index').replace(/^\//, '');
  326. }
  327. var v = String(p.get('isShareCheckInSquare') || '').trim().toLowerCase();
  328. if (v === '' || v === '0' || v === 'false' || v === 'no') {
  329. return String(APP_UNI_STORE_PATH || 'pages/checkIn/index').replace(/^\//, '');
  330. }
  331. return 'pages/checkIn/details';
  332. }
  333. /** businessStatus=99(商户关闭):插图与文案;否则为「内容已删除」 */
  334. function applyEmptyHeroState() {
  335. var merged = mergeSearchAndHashParams();
  336. var bsRaw = merged.get('businessStatus');
  337. var bs = bsRaw == null ? '' : String(bsRaw).trim();
  338. var isClosed = Number(bs) === 99 || bs === '99';
  339. var img = document.getElementById('heroEmptyIllustration');
  340. var tip = document.getElementById('heroEmptyTip');
  341. if (!img || !tip) return;
  342. if (isClosed) {
  343. img.src = 'images/storeNone.png';
  344. img.alt = '';
  345. tip.textContent = '抱歉商户已关闭,看看别的吧';
  346. } else {
  347. img.src = 'images/empty.png';
  348. img.alt = '';
  349. tip.textContent = '内容已删除';
  350. }
  351. img.onerror = function () {
  352. this.onerror = null;
  353. this.src = 'images/empty.png';
  354. };
  355. if (weChatJssdkConfigured) {
  356. refreshWxLaunchTagAttrs();
  357. }
  358. }
  359. function buildAppOpenQueryStringMerged() {
  360. var rawQs = getRawMergedQueryForAppOpen();
  361. if (rawQs) {
  362. return '?' + rawQs;
  363. }
  364. var params = mergeSearchAndHashParams();
  365. var sid = params.get('storeId') || params.get('id') || '';
  366. if (sid && !params.has('storeId')) {
  367. params.set('storeId', sid);
  368. }
  369. var qsOut = params.toString();
  370. return qsOut ? ('?' + qsOut) : '';
  371. }
  372. function buildAppUniPageLaunchUrl() {
  373. var path = getAppUniPathForCheckInShare().replace(/^\//, '');
  374. var qs = buildAppOpenQueryStringMerged().replace(/^\?/, '');
  375. return qs ? path + '?' + qs : path;
  376. }
  377. /**
  378. * wx-open-launch-app extinfo:pages/checkIn/index、pages/checkIn/details 或关店 pages/index/login
  379. */
  380. function buildWeChatLaunchExtinfo() {
  381. var uniPage = buildAppUniPageLaunchUrl();
  382. if (uniPage.length <= 1024) return uniPage;
  383. var path = getAppUniPathForCheckInShare().replace(/^\//, '');
  384. var rawQs = getRawMergedQueryForAppOpen();
  385. if (rawQs) {
  386. var packedRaw = path + '?' + rawQs;
  387. if (packedRaw.length <= 1024) return packedRaw;
  388. }
  389. var params = mergeSearchAndHashParams();
  390. var mini = new URLSearchParams();
  391. var storeId = params.get('storeId') || params.get('id') || '';
  392. if (storeId) mini.set('storeId', storeId);
  393. var square = params.get('isShareCheckInSquare');
  394. if (square != null && String(square).trim() !== '') {
  395. mini.set('isShareCheckInSquare', String(square).trim());
  396. }
  397. var bs = params.get('businessStatus');
  398. if (bs != null && String(bs).trim() !== '') {
  399. mini.set('businessStatus', String(bs).trim());
  400. }
  401. var shortPage = path + '?' + mini.toString();
  402. if (shortPage.length <= 1024) return shortPage;
  403. var deep = buildAppDeepLink().replace(/^shopro:\/\//i, '');
  404. return deep.length <= 1024 ? deep : shortPage.slice(0, 1024);
  405. }
  406. function buildAppDeepLink() {
  407. var path = getAppUniPathForCheckInShare().replace(/^\//, '');
  408. var s = buildAppOpenQueryStringMerged();
  409. var root = APP_IOS_URL_SCHEME.replace(/\/$/, '');
  410. if (!s) {
  411. return root + '/' + path;
  412. }
  413. return root + '/' + path + s;
  414. }
  415. function isWeChatInAppBrowser() {
  416. return /MicroMessenger/i.test(navigator.userAgent || '');
  417. }
  418. function getWxShareEntryFrom() {
  419. var from = q('from');
  420. if (from) return String(from).trim().toLowerCase();
  421. try {
  422. var h = location.hash || '';
  423. var qi = h.indexOf('?');
  424. if (qi >= 0) {
  425. var hf = new URLSearchParams(h.slice(qi + 1)).get('from');
  426. if (hf) return String(hf).trim().toLowerCase();
  427. }
  428. } catch (eH) {}
  429. try {
  430. var sf = new URLSearchParams(location.search || '').get('from');
  431. if (sf) return String(sf).trim().toLowerCase();
  432. } catch (eS) {}
  433. return '';
  434. }
  435. function isIOSWeChatBrowser() {
  436. var ua = navigator.userAgent || '';
  437. return /MicroMessenger/i.test(ua) && /iPhone|iPad|iPod/i.test(ua);
  438. }
  439. function logWxEntryDiagnostics() {
  440. if (!isWeChatInAppBrowser()) return;
  441. console.log('[wx-entry]', {
  442. entryFrom: getWxShareEntryFrom() || '(无)',
  443. wxJssdkReady: weChatJssdkConfigured,
  444. signUrl: getWxConfigSignUrl()
  445. });
  446. }
  447. function readQueryParam(name) {
  448. return q(name);
  449. }
  450. function isWxDebugOn() {
  451. return readQueryParam('wxDebug') === '1';
  452. }
  453. function isWxForceDebug() {
  454. return readQueryParam('wxForce') === '1';
  455. }
  456. function isWxConfigOnClickDebug() {
  457. return readQueryParam('wxConfigOnClick') === '1';
  458. }
  459. function isWxPcAutoDebugHost() {
  460. var h = (location.hostname || '').toLowerCase();
  461. if (h === 'localhost' || h === '127.0.0.1') return true;
  462. for (var i = 0; i < WECHAT_JS_SAFE_HOSTS.length; i++) {
  463. if (WECHAT_JS_SAFE_HOSTS[i] === h) return true;
  464. }
  465. return false;
  466. }
  467. function isWxPcBrowser() {
  468. return !isWeChatInAppBrowser();
  469. }
  470. function shouldInitWeChatJssdkOnLoad() {
  471. if (isWeChatInAppBrowser()) return true;
  472. return isWxForceDebug() || isWxPcAutoDebugHost();
  473. }
  474. function shouldFetchWxConfig(fromUserClick) {
  475. if (isWeChatInAppBrowser()) return true;
  476. if (fromUserClick) return true;
  477. return isWxForceDebug() || isWxPcAutoDebugHost();
  478. }
  479. function getWxHtmlUrl() {
  480. var forced = String(q('wxSignUrl') || '').trim();
  481. if (forced) return forced.split('#')[0];
  482. return String(location.href || '').split('#')[0];
  483. }
  484. function getWxSignPageUrlForApi() {
  485. var htmlUrl = getWxHtmlUrl();
  486. if (htmlUrl && /^https?:\/\//i.test(htmlUrl)) return htmlUrl;
  487. return WX_GET_CONFIG_SIGN_URL;
  488. }
  489. function getWxHtmlUrlBase() {
  490. var htmlUrl = getWxSignPageUrlForApi();
  491. try {
  492. var u = new URL(htmlUrl);
  493. return u.origin + u.pathname;
  494. } catch (eU) {
  495. return WX_GET_CONFIG_SIGN_URL;
  496. }
  497. }
  498. function getWxConfigSignUrl() {
  499. if (String(q('wxSignBaseOnly') || '') === '1') return getWxHtmlUrlBase();
  500. return getWxSignPageUrlForApi();
  501. }
  502. function getWxGetConfigApiUrl() {
  503. return API_BASE.replace(/\/$/, '') + WECHAT_GET_WX_CONFIG_PATH;
  504. }
  505. function buildWxGetConfigRequestBody(htmlUrl) {
  506. return {
  507. url: String(htmlUrl || '').split('#')[0].trim()
  508. };
  509. }
  510. function resolveWxConfigAppIdFromSignData(d) {
  511. if (!d || typeof d !== 'object') return '';
  512. var mp =
  513. d.mpAppId ||
  514. d.mpAppid ||
  515. d.officialAppId ||
  516. d.gzhAppId ||
  517. d.serviceAppId;
  518. if (mp != null && String(mp).trim() !== '') return String(mp).trim();
  519. var fromQuery = String(q('wxMpAppId') || WECHAT_MP_APP_ID || '').trim();
  520. if (fromQuery) return fromQuery;
  521. var raw = d.appId || d.appid || d.wxAppId;
  522. return raw != null && String(raw).trim() !== '' ? String(raw).trim() : '';
  523. }
  524. function normalizeWxJssdkSignPayload(res, signUrlUsed) {
  525. if (!res || typeof res !== 'object') return null;
  526. var d = res.data != null && typeof res.data === 'object' ? res.data : res;
  527. if (!d || typeof d !== 'object') return null;
  528. var appId = resolveWxConfigAppIdFromSignData(d);
  529. var timestamp = d.timestamp != null ? d.timestamp : d.timeStamp;
  530. var nonceStr =
  531. d.nonceStr != null && String(d.nonceStr) !== ''
  532. ? d.nonceStr
  533. : d.noncestr != null && String(d.noncestr) !== ''
  534. ? d.noncestr
  535. : d.nonce;
  536. var signature = d.signature || d.sign;
  537. if (!appId || timestamp == null || nonceStr == null || nonceStr === '' || !signature) {
  538. return null;
  539. }
  540. return {
  541. appId: String(appId),
  542. timestamp: Number(timestamp),
  543. nonceStr: String(nonceStr),
  544. signature: String(signature),
  545. signUrl: String(signUrlUsed || '')
  546. .split('#')[0]
  547. .trim()
  548. };
  549. }
  550. function getWxErrMsg(err) {
  551. if (!err) return '';
  552. if (err.errMsg) return String(err.errMsg);
  553. if (typeof err === 'string') return err;
  554. try {
  555. return JSON.stringify(err);
  556. } catch (e) {
  557. return String(err);
  558. }
  559. }
  560. function formatWxConfigErrorTip(err, signPageUrl) {
  561. var errMsg = getWxErrMsg(err);
  562. var tip = '微信 JSSDK 配置失败';
  563. if (/invalid signature/i.test(errMsg)) {
  564. return (
  565. tip +
  566. ':签名无效。请核对:①后端用与前端相同的 url 签名;②url=' +
  567. (signPageUrl || getWxHtmlUrl()) +
  568. ';③nonceStr/timestamp 与接口返回一致;④appId=' +
  569. WECHAT_MP_APP_ID
  570. );
  571. }
  572. if (/require\s*subscribe/i.test(errMsg)) {
  573. return tip + ':' + errMsg + '(服务号需用户已关注)';
  574. }
  575. return errMsg ? tip + ':' + errMsg : tip;
  576. }
  577. function setWxInitError(msg) {
  578. wxInitLastError = String(msg || '').trim();
  579. if (wxInitLastError) console.warn('[wx]', wxInitLastError);
  580. }
  581. function requestWeChatJssdkSignAndConfig(htmlUrlOptional) {
  582. var htmlUrl = String(
  583. htmlUrlOptional != null ? htmlUrlOptional : getWxConfigSignUrl()
  584. )
  585. .split('#')[0]
  586. .trim();
  587. if (!htmlUrl || !/^https?:\/\//i.test(htmlUrl)) {
  588. htmlUrl = WX_GET_CONFIG_SIGN_URL;
  589. }
  590. if (isWxDebugOn()) {
  591. try {
  592. window.alert('htmlUrl(签名用):\n' + htmlUrl);
  593. } catch (eDbg) {}
  594. }
  595. var requestUrl = getWxGetConfigApiUrl();
  596. var requestBody = buildWxGetConfigRequestBody(htmlUrl);
  597. console.log('[wx] htmlUrl=', htmlUrl);
  598. console.log('[wx] POST getWxConfig →', requestUrl, requestBody);
  599. return fetch(requestUrl, {
  600. method: 'POST',
  601. mode: 'cors',
  602. credentials: 'omit',
  603. headers: {
  604. Accept: 'application/json',
  605. 'Content-Type': 'application/json;charset=UTF-8'
  606. },
  607. body: JSON.stringify(requestBody)
  608. })
  609. .then(function (r) {
  610. if (r.ok) return r.json();
  611. return r
  612. .text()
  613. .catch(function () {
  614. return '';
  615. })
  616. .then(function (text) {
  617. var hint = '';
  618. try {
  619. var j = JSON.parse(text);
  620. hint = j.msg || j.message || '';
  621. } catch (eP) {
  622. if (text) hint = text.slice(0, 120);
  623. }
  624. throw new Error('getWxConfig HTTP ' + r.status + (hint ? ':' + hint : ''));
  625. });
  626. })
  627. .then(function (res) {
  628. if (res && res.code != null) {
  629. var c = Number(res.code);
  630. if (c !== 200 && c !== 0 && res.success !== true) {
  631. throw new Error(res.msg || res.message || 'getWxConfig code ' + c);
  632. }
  633. }
  634. var sign = normalizeWxJssdkSignPayload(res, htmlUrl);
  635. if (!sign) {
  636. console.warn('[wx] getWxConfig 响应字段不全', res, 'htmlUrl=', htmlUrl);
  637. throw new Error(
  638. 'getWxConfig 缺少 appId/timestamp/nonceStr/signature(见控制台)'
  639. );
  640. }
  641. if (sign.appId !== WECHAT_MP_APP_ID) {
  642. console.warn(
  643. '[wx] 后端 appId=' + sign.appId + ',期望服务号 ' + WECHAT_MP_APP_ID
  644. );
  645. }
  646. if (typeof wx === 'undefined') {
  647. if (isWxPcBrowser()) {
  648. console.log('[wx] PC getWxConfig 成功(无 jweixin)', sign);
  649. return true;
  650. }
  651. setWxInitError('jweixin.js 未加载');
  652. return false;
  653. }
  654. return applyWxConfigFromSign(sign, htmlUrl);
  655. });
  656. }
  657. function applyWxConfigFromSign(sign, htmlUrl) {
  658. var wxConfigParams = {
  659. debug: isWxDebugOn(),
  660. appId: String(sign.appId),
  661. timestamp: sign.timestamp,
  662. nonceStr: String(sign.nonceStr),
  663. signature: String(sign.signature),
  664. jsApiList: [],
  665. openTagList: ['wx-open-launch-app']
  666. };
  667. return new Promise(function (resolve) {
  668. wx.config(wxConfigParams);
  669. wx.ready(function () {
  670. weChatJssdkConfigured = true;
  671. document.body.classList.add('wx-jssdk-ready');
  672. refreshWxLaunchTagAttrs();
  673. console.log('[wx.config] ready, htmlUrl=', htmlUrl);
  674. resolve(true);
  675. });
  676. wx.error(function (err) {
  677. weChatJssdkConfigured = false;
  678. document.body.classList.remove('wx-jssdk-ready');
  679. wxJssdkInitPromise = null;
  680. var errMsg = getWxErrMsg(err);
  681. setWxInitError(formatWxConfigErrorTip(err, htmlUrl));
  682. if (isWxDebugOn()) window.alert(wxInitLastError);
  683. console.warn('[wx.config]', errMsg, 'htmlUrl=', htmlUrl);
  684. var baseUrl = getWxHtmlUrlBase();
  685. var fullUrl = getWxSignPageUrlForApi();
  686. if (
  687. !/invalid signature/i.test(errMsg) ||
  688. wxConfigSignRetriedBaseUrl ||
  689. baseUrl === fullUrl ||
  690. htmlUrl === baseUrl
  691. ) {
  692. resolve(false);
  693. return;
  694. }
  695. wxConfigSignRetriedBaseUrl = true;
  696. requestWeChatJssdkSignAndConfig(baseUrl).then(resolve);
  697. });
  698. });
  699. }
  700. function refreshWxLaunchTagAttrs() {
  701. var tag = document.getElementById('launch-btn');
  702. if (!tag) return;
  703. try {
  704. tag.setAttribute('appid', WECHAT_OPEN_APP_ID);
  705. tag.setAttribute('extinfo', buildWeChatLaunchExtinfo());
  706. } catch (eA) {}
  707. }
  708. function bindWeChatLaunchTagEvents() {
  709. var tag = document.getElementById('launch-btn');
  710. if (!tag || tag._wxLaunchBound) return;
  711. tag._wxLaunchBound = true;
  712. refreshWxLaunchTagAttrs();
  713. tag.addEventListener('launch', function () {
  714. console.log('[wx-open-launch-app] launch ok');
  715. // showFabToast('正在打开 U店在哪…');
  716. });
  717. tag.addEventListener('error', function (e) {
  718. var detail = e && e.detail;
  719. var errMsg =
  720. detail && detail.errMsg
  721. ? String(detail.errMsg)
  722. : detail && detail.errmsg
  723. ? String(detail.errmsg)
  724. : '';
  725. console.warn('[wx-open-launch-app]', detail);
  726. if (/launch:fail/i.test(errMsg) && !getWxShareEntryFrom()) {
  727. showDownloadTip();
  728. } else {
  729. showAppOpenFailTip(
  730. errMsg
  731. ? '未能打开 App:' + errMsg
  732. : '未能打开 App,请确认已安装最新版「U店在哪」'
  733. );
  734. }
  735. });
  736. }
  737. function initWeChatOpenLaunchApp(fromUserClick) {
  738. if (!shouldFetchWxConfig(!!fromUserClick)) {
  739. console.log('[wx] 未调用 getWxConfig');
  740. return Promise.resolve(false);
  741. }
  742. if (isWxPcBrowser()) {
  743. console.warn(
  744. '[wx] PC:请求 getWxConfig' + (fromUserClick ? '(按钮)' : '(进页)')
  745. );
  746. }
  747. if (wxJssdkInitPromise && !fromUserClick) return wxJssdkInitPromise;
  748. wxConfigSignRetriedBaseUrl = false;
  749. wxInitLastError = '';
  750. var htmlUrl = getWxConfigSignUrl();
  751. bindWeChatLaunchTagEvents();
  752. wxJssdkInitPromise = requestWeChatJssdkSignAndConfig(htmlUrl)
  753. .then(function (ok) {
  754. if (ok === true) return true;
  755. if (!wxInitLastError) {
  756. setWxInitError('wx.config 失败,可加 ?wxDebug=1 查看 htmlUrl');
  757. }
  758. return false;
  759. })
  760. .catch(function (e) {
  761. var msg = e && e.message ? e.message : 'getWxConfig 请求失败';
  762. setWxInitError(msg);
  763. console.warn('[wx] requestWeChatJssdkSignAndConfig failed', msg, 'htmlUrl=', htmlUrl);
  764. if (isWeChatInAppBrowser() && isWxDebugOn()) window.alert(msg);
  765. return false;
  766. })
  767. .finally(function () {
  768. if (!weChatJssdkConfigured) wxJssdkInitPromise = null;
  769. });
  770. return wxJssdkInitPromise;
  771. }
  772. /** 进页即尝试拉签名;jweixin 晚到时自动重试 */
  773. function scheduleWeChatJssdkBootstrap() {
  774. if (!shouldInitWeChatJssdkOnLoad()) return;
  775. var attempts = 0;
  776. function tick() {
  777. attempts += 1;
  778. if (weChatJssdkConfigured) return;
  779. initWeChatOpenLaunchApp();
  780. if (!weChatJssdkConfigured && attempts < 8 && typeof wx === 'undefined') {
  781. setTimeout(tick, 400);
  782. }
  783. }
  784. if (isIOSWeChatBrowser()) {
  785. setTimeout(tick, 350);
  786. } else {
  787. tick();
  788. }
  789. }
  790. function showFabToast(msg, ms) {
  791. var tip = String(msg || '').trim();
  792. if (!tip) return;
  793. var el = document.getElementById('openAppToast');
  794. if (el) {
  795. el.textContent = tip;
  796. el.style.display = 'block';
  797. if (showFabToast._t) clearTimeout(showFabToast._t);
  798. showFabToast._t = setTimeout(function () {
  799. el.style.display = 'none';
  800. }, ms || 2800);
  801. }
  802. console.log('[openApp]', tip);
  803. }
  804. function showAppOpenFailTip(msg) {
  805. var tip = msg || '未能打开 App,请确认已安装最新版「U店在哪」。';
  806. if (typeof uni !== 'undefined' && typeof uni.showToast === 'function') {
  807. uni.showToast({ title: tip, icon: 'none', duration: 2800 });
  808. } else if (isWeChatInAppBrowser()) {
  809. window.alert(tip);
  810. } else {
  811. console.warn('[openApp]', tip);
  812. }
  813. }
  814. function tryFetchWxConfigOnPcClick() {
  815. if (!isWxPcBrowser()) return Promise.resolve(false);
  816. showFabToast('正在请求 getWxConfig…');
  817. wxJssdkInitPromise = null;
  818. return initWeChatOpenLaunchApp(true).then(function (ok) {
  819. if (ok) {
  820. showFabToast(
  821. weChatJssdkConfigured
  822. ? 'getWxConfig 成功,wx.config 已就绪'
  823. : 'getWxConfig 成功'
  824. );
  825. } else {
  826. showFabToast(wxInitLastError || 'getWxConfig 失败');
  827. }
  828. return ok;
  829. });
  830. }
  831. function launchAppDeepLink(deepLink) {
  832. try {
  833. var a = document.createElement('a');
  834. a.href = deepLink;
  835. a.setAttribute('target', '_self');
  836. document.body.appendChild(a);
  837. a.click();
  838. document.body.removeChild(a);
  839. } catch (e1) {}
  840. try {
  841. window.location.href = deepLink;
  842. } catch (e2) {}
  843. }
  844. function tryOpenHBuilderApp() {
  845. /* 微信内须直接点击 wx-open-launch-app,scheme 会被拦截 */
  846. if (isWeChatInAppBrowser()) return;
  847. tryFetchWxConfigOnPcClick().then(function () {
  848. if (isWxConfigOnClickDebug() && !isWxForceDebug() && !isWxPcAutoDebugHost()) {
  849. return;
  850. }
  851. tryOpenHBuilderAppViaScheme();
  852. });
  853. }
  854. function tryOpenHBuilderAppViaScheme() {
  855. // showFabToast('正在打开 U店在哪…');
  856. var deepLink = buildAppDeepLink();
  857. if (typeof plus !== 'undefined' && plus.runtime) {
  858. var installed = null;
  859. try {
  860. if (typeof plus.runtime.isApplicationExist === 'function') {
  861. installed = plus.runtime.isApplicationExist({
  862. pname: APP_ANDROID_PACKAGE,
  863. action: APP_IOS_URL_SCHEME
  864. });
  865. }
  866. } catch (e) {
  867. console.warn(e);
  868. }
  869. if (installed === false) {
  870. showDownloadTip();
  871. return;
  872. }
  873. try {
  874. plus.runtime.openURL(deepLink);
  875. } catch (e2) {
  876. console.warn(e2);
  877. showDownloadTip();
  878. }
  879. return;
  880. }
  881. var done = false;
  882. function finish() {
  883. if (done) return;
  884. done = true;
  885. document.removeEventListener('visibilitychange', onVis);
  886. window.removeEventListener('pagehide', onHide);
  887. }
  888. function onVis() {
  889. if (document.visibilityState === 'hidden') finish();
  890. }
  891. function onHide() {
  892. finish();
  893. }
  894. document.addEventListener('visibilitychange', onVis);
  895. window.addEventListener('pagehide', onHide);
  896. try {
  897. launchAppDeepLink(deepLink);
  898. } catch (e3) {
  899. finish();
  900. showDownloadTip();
  901. return;
  902. }
  903. window.setTimeout(function () {
  904. if (done) return;
  905. finish();
  906. showDownloadTip();
  907. }, 2600);
  908. }
  909. function boot() {
  910. var launchTag = document.getElementById('launch-btn');
  911. if (launchTag) launchTag.setAttribute('appid', WECHAT_OPEN_APP_ID);
  912. bindWeChatLaunchTagEvents();
  913. if (isWeChatInAppBrowser()) {
  914. document.body.classList.add('is-wechat');
  915. logWxEntryDiagnostics();
  916. }
  917. if (shouldInitWeChatJssdkOnLoad()) {
  918. if (isWxPcBrowser() && (isWxForceDebug() || isWxPcAutoDebugHost())) {
  919. document.body.classList.add('wx-pc-debug');
  920. }
  921. scheduleWeChatJssdkBootstrap();
  922. }
  923. document.addEventListener('WeixinOpenTagsError', function (e) {
  924. console.warn('[WeixinOpenTagsError]', e && e.detail);
  925. });
  926. applyEmptyHeroState();
  927. if (isWeChatInAppBrowser()) {
  928. var openBtnWx = document.getElementById('openApp');
  929. if (openBtnWx) {
  930. openBtnWx.addEventListener('click', function () {
  931. if (!weChatJssdkConfigured) {
  932. showFabToast(
  933. wxInitLastError || '微信 SDK 初始化中,请稍候再点底部按钮'
  934. );
  935. return;
  936. }
  937. });
  938. }
  939. } else {
  940. var openBtn = document.getElementById('openApp');
  941. if (openBtn) {
  942. openBtn.addEventListener('click', tryOpenHBuilderApp);
  943. }
  944. }
  945. }
  946. if (document.readyState === 'complete') {
  947. boot();
  948. } else {
  949. window.onload = boot;
  950. }
  951. })();
  952. </script>
  953. </body>
  954. </html>