index.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  1. // common-page/pages/web-view/index.js
  2. const Parse = getApp().Parse;
  3. const company = getApp().globalData.company;
  4. const DEBUG_WEBVIEW = false;
  5. const debugLog = (...args) => {
  6. if (DEBUG_WEBVIEW) {
  7. console.log(...args);
  8. }
  9. };
  10. Page({
  11. /**
  12. * 页面的初始数据
  13. */
  14. data: {
  15. path: "",
  16. currentTitle: "", // 当前标题
  17. miniPayVisible: false,
  18. miniPayPrice: 0,
  19. miniPayTradeNo: "",
  20. miniPayOrderId: "",
  21. miniPayOrderType: "shopgoods",
  22. miniPayShowType: "all",
  23. miniPayShowBonus: false,
  24. miniPayProfileId: "",
  25. miniPayProcessing: false,
  26. miniPayRequestContext: null,
  27. },
  28. // 标题轮询定时器
  29. titlePollingTimer: null,
  30. /**
  31. * 生命周期函数--监听页面加载
  32. */
  33. onLoad: async function (options) {
  34. debugLog('======= web-view 页面加载 =======');
  35. // 1. 先检查用户登录状态
  36. const loginCheck = await this.checkUserLogin(options);
  37. if (!loginCheck) {
  38. debugLog('⚠️ 用户未登录或没有手机号,已跳转到授权页面');
  39. return; // 停止后续加载
  40. }
  41. debugLog('✅ 用户已登录且有手机号,继续加载 web-view');
  42. // 2. 解码 URL
  43. let path = decodeURIComponent(options.path || '');
  44. const isSkipAuth = options.skipAuth === 'true';
  45. const isHomePath = /^https?:\/\/www\.yuban\.co\/home([/?#]|$)/.test(path);
  46. // 引导页直达 H5 首页时走快速路径:
  47. // 仅补齐缺失的登录/欢迎参数,避免额外 Parse 查询造成首开延迟。
  48. if (isSkipAuth && isHomePath) {
  49. path = this.ensureHomeAuthQuery(path);
  50. this.setData({ path });
  51. return;
  52. }
  53. debugLog('原始 options.path:', options.path);
  54. debugLog('解码后的 path:', path);
  55. // 拼接额外参数(避免重复添加已存在的参数)
  56. let hasQuery = path.indexOf('?') !== -1;
  57. let parsm = hasQuery ? '&' : '?';
  58. let params = [];
  59. // 提取 path 中已有的参数
  60. let existingParams = new Set();
  61. if (hasQuery) {
  62. const queryString = path.split('?')[1];
  63. if (queryString) {
  64. queryString.split('&').forEach(param => {
  65. const key = param.split('=')[0];
  66. existingParams.add(key);
  67. });
  68. }
  69. }
  70. // 只添加 path 中不存在的参数
  71. for (const key in options) {
  72. if(key != 'path' && key != 'url' && !existingParams.has(key)){
  73. params.push(key + '=' + options[key]);
  74. }
  75. }
  76. // 添加用户信息,确保 H5 能获取到当前用户身份(用于扣减流量等操作)
  77. const currentUser = Parse.User.current();
  78. if (currentUser) {
  79. // 添加 userId
  80. if (!existingParams.has('userId')) {
  81. params.push('userId=' + currentUser.id);
  82. }
  83. // 添加 token (sessionToken)
  84. const sessionToken = currentUser.getSessionToken();
  85. if (sessionToken && !existingParams.has('token')) {
  86. params.push('token=' + sessionToken);
  87. }
  88. // 添加 mobile
  89. const mobile = currentUser.get('mobile');
  90. if (mobile && !existingParams.has('mobile')) {
  91. params.push('mobile=' + mobile);
  92. }
  93. }
  94. if(params.length > 0) {
  95. parsm = parsm + params.join('&');
  96. path = path + parsm;
  97. }
  98. debugLog('最终 web-view URL:', path);
  99. debugLog('URL 长度:', path.length);
  100. this.setData({
  101. path: path
  102. })
  103. // 立即设置标题
  104. const passedStoreName = options.storeName ? decodeURIComponent(options.storeName) : '';
  105. const passedStoreId = options.storeId || '';
  106. // /home 场景下默认不需要门店标题:跳过 ShopStore 的 Parse 查询以提速。
  107. // 这里根据 H5 path 判断:例如 https://www.yuban.co/home?token=...&skipAuth=true...
  108. const isHome = isHomePath;
  109. if (passedStoreName) {
  110. this.setNavigationTitle(passedStoreName);
  111. }
  112. // 异步加载完整店铺信息(作为备份)
  113. // 仅当不是 /home 或者传了门店参数时才查询。
  114. if (!(isHome && !passedStoreId && !passedStoreName)) {
  115. this.loadAndSetStoreTitle(passedStoreId, passedStoreName);
  116. }
  117. // 启动标题轮询监听
  118. this.startTitlePolling();
  119. },
  120. /**
  121. * 检查用户登录状态
  122. * @returns {Promise<boolean>} true: 已登录且有手机号,false: 需要登录
  123. */
  124. checkUserLogin: async function(options) {
  125. try {
  126. debugLog('🔍 开始检查用户登录状态...');
  127. // 检查是否有 skipAuth 参数(用于跳过登录检查)
  128. if (options.skipAuth === 'true') {
  129. debugLog('ℹ️ 检测到 skipAuth 参数,跳过登录检查');
  130. return true;
  131. }
  132. // 检查是否是扫码进入
  133. const isScanEntry = options && (options.storeId && (options.scanCount || options.partnerId || options.userId || options.employeeId));
  134. if (isScanEntry) {
  135. debugLog('🚀 检测到扫码进入,准备强制登录以确保流量扣减');
  136. }
  137. // 1. 先调用 checkAuth 初始化用户(扫码进入时强制授权)
  138. debugLog('📱 调用 checkAuth 初始化用户...');
  139. try {
  140. // 如果是扫码进入,则强制授权;否则不强制(由后面逻辑决定)
  141. await getApp().checkAuth(isScanEntry);
  142. debugLog('✅ checkAuth 调用成功');
  143. } catch (err) {
  144. console.warn('⚠️ checkAuth 调用失败:', err);
  145. }
  146. // 2. 检查用户状态
  147. const currentUser = Parse.User.current();
  148. const hasMobile = currentUser?.get('mobile');
  149. const userLogin = wx.getStorageSync('userLogin');
  150. debugLog('📊 用户状态:');
  151. debugLog(' - 当前用户:', currentUser ? currentUser.id : '无');
  152. debugLog(' - 手机号:', hasMobile || '无');
  153. debugLog(' - userLogin 存储:', userLogin || '无');
  154. // 只有同时满足以下条件才认为已完整登录:
  155. // 1. Parse.User.current() 存在
  156. // 2. 用户有手机号
  157. // 3. userLogin 存储存在
  158. if (currentUser && hasMobile && userLogin) {
  159. debugLog('✅ 用户已完整登录');
  160. return true;
  161. }
  162. // 用户未登录或没有手机号,跳转到授权页面
  163. debugLog('⚠️ 用户未完整登录,准备跳转到授权页面');
  164. // 构建返回 URL(登录成功后返回当前页面)
  165. const currentPath = options.path || '';
  166. const returnUrl = encodeURIComponent(currentPath);
  167. debugLog('🔗 returnUrl:', returnUrl);
  168. // 跳转到授权页面,并传递 returnUrl
  169. wx.redirectTo({
  170. url: `/components/app-auth/index?returnUrl=${returnUrl}`,
  171. success: () => {
  172. debugLog('✅ redirectTo 到授权页面成功');
  173. },
  174. fail: (err) => {
  175. console.error('❌ redirectTo 失败:', err);
  176. // 降级:使用 navigateTo
  177. wx.navigateTo({
  178. url: `/components/app-auth/index?returnUrl=${returnUrl}`,
  179. success: () => {
  180. debugLog('✅ navigateTo 到授权页面成功');
  181. },
  182. fail: (err2) => {
  183. console.error('❌ navigateTo 也失败:', err2);
  184. // 最后降级:使用 reLaunch
  185. wx.reLaunch({
  186. url: `/components/app-auth/index?returnUrl=${returnUrl}`,
  187. success: () => {
  188. debugLog('✅ reLaunch 到授权页面成功');
  189. },
  190. fail: (err3) => {
  191. console.error('❌ 所有跳转方式都失败:', err3);
  192. }
  193. });
  194. }
  195. });
  196. }
  197. });
  198. return false;
  199. } catch (err) {
  200. console.error('❌ 检查登录状态失败:', err);
  201. debugLog('checkUserLogin error');
  202. // 出错时也跳转到授权页面
  203. const returnUrl = options.path ? encodeURIComponent(options.path) : '';
  204. wx.redirectTo({
  205. url: `/components/app-auth/index?returnUrl=${returnUrl}`,
  206. fail: () => {
  207. wx.navigateTo({
  208. url: `/components/app-auth/index?returnUrl=${returnUrl}`
  209. });
  210. }
  211. });
  212. return false;
  213. }
  214. },
  215. onReady: function () {
  216. },
  217. onShow: function () {
  218. this.startTitlePolling();
  219. },
  220. onHide: function () {
  221. this.stopTitlePolling();
  222. },
  223. onUnload: function () {
  224. this.stopTitlePolling();
  225. },
  226. /**
  227. * 页面相关事件处理函数--监听用户下拉动作
  228. */
  229. onPullDownRefresh: function () {
  230. },
  231. /**
  232. * 页面上拉触底事件的处理函数
  233. */
  234. onReachBottom: function () {
  235. },
  236. /**
  237. * 用户点击右上角分享
  238. */
  239. onShareAppMessage: function () {
  240. },
  241. /**
  242. * 直达 /home 时补齐 token/userId/mobile/fromStartup,不覆盖 URL 已有值。
  243. */
  244. ensureHomeAuthQuery: function (path) {
  245. try {
  246. const hasQuery = path.indexOf('?') !== -1;
  247. const existingParams = new Set();
  248. if (hasQuery) {
  249. const queryString = path.split('?')[1] || '';
  250. queryString.split('&').forEach((param) => {
  251. const key = param.split('=')[0];
  252. if (key) existingParams.add(key);
  253. });
  254. }
  255. const append = [];
  256. if (!existingParams.has('fromStartup')) {
  257. append.push('fromStartup=1');
  258. }
  259. let token = null;
  260. let userId = null;
  261. let mobile = null;
  262. try {
  263. const currentUser = Parse && Parse.User ? Parse.User.current() : null;
  264. if (currentUser) {
  265. token = currentUser.getSessionToken() || null;
  266. userId = currentUser.id || null;
  267. mobile = currentUser.get('mobile') || null;
  268. }
  269. } catch (e) {
  270. // ignore
  271. }
  272. try {
  273. if (!token) token = wx.getStorageSync('sessionToken') || null;
  274. if (!userId) userId = wx.getStorageSync('userLogin') || null;
  275. if (!mobile) {
  276. const userInfo = wx.getStorageSync('userInfo') || {};
  277. mobile = userInfo.mobile || null;
  278. }
  279. } catch (e) {
  280. // ignore
  281. }
  282. if (token && !existingParams.has('token')) {
  283. append.push('token=' + encodeURIComponent(token));
  284. }
  285. if (userId && !existingParams.has('userId')) {
  286. append.push('userId=' + encodeURIComponent(userId));
  287. }
  288. if (mobile && !existingParams.has('mobile')) {
  289. append.push('mobile=' + encodeURIComponent(mobile));
  290. }
  291. if (append.length === 0) return path;
  292. return path + (hasQuery ? '&' : '?') + append.join('&');
  293. } catch (e) {
  294. return path;
  295. }
  296. },
  297. /**
  298. * 处理来自 H5 页面的消息
  299. */
  300. handleMessage: function (e) {
  301. try {
  302. const messages = e.detail.data || [];
  303. // 找到最后一个标题更新消息
  304. let lastTitleMessage = null;
  305. let lastPayMessage = null;
  306. for (let i = messages.length - 1; i >= 0; i--) {
  307. const msg = messages[i];
  308. if (msg.type === 'updateTitle' && msg.title) {
  309. lastTitleMessage = msg;
  310. }
  311. if (!lastPayMessage && msg.type === 'requestMiniPay') {
  312. lastPayMessage = msg;
  313. }
  314. if (lastTitleMessage && lastPayMessage) {
  315. break;
  316. }
  317. }
  318. // 更新标题
  319. if (lastTitleMessage) {
  320. this.setNavigationTitle(lastTitleMessage.title);
  321. }
  322. if (lastPayMessage) {
  323. this.handleMiniPayRequest(lastPayMessage.payload || {});
  324. }
  325. } catch (error) {
  326. console.error('❌ 处理消息失败:', error);
  327. }
  328. },
  329. normalizeMiniPayPayload(payload = {}) {
  330. const price = Number(payload.price);
  331. return {
  332. tradeNo: payload.tradeNo || '',
  333. price: Number.isFinite(price) ? price : 0,
  334. orderId: payload.orderId || '',
  335. orderType: payload.orderType || 'shopgoods',
  336. showType: payload.showType || 'all',
  337. showBonus: !!payload.showBonus,
  338. profileId: payload.profileId || '',
  339. scene: payload.scene || '',
  340. bizId: payload.bizId || '',
  341. callbackUrl: payload.callbackUrl || ''
  342. };
  343. },
  344. handleMiniPayRequest(payload = {}) {
  345. const parsed = this.normalizeMiniPayPayload(payload);
  346. if (!parsed.tradeNo) {
  347. wx.showToast({
  348. title: '支付参数缺少tradeNo',
  349. icon: 'none'
  350. });
  351. return;
  352. }
  353. if (parsed.price < 0) {
  354. wx.showToast({
  355. title: '支付金额无效',
  356. icon: 'none'
  357. });
  358. return;
  359. }
  360. if (this.data.miniPayProcessing) {
  361. wx.showToast({
  362. title: '支付进行中,请稍后',
  363. icon: 'none'
  364. });
  365. return;
  366. }
  367. this.setData({
  368. miniPayVisible: false,
  369. miniPayPrice: parsed.price,
  370. miniPayTradeNo: parsed.tradeNo,
  371. miniPayOrderId: parsed.orderId,
  372. miniPayOrderType: parsed.orderType,
  373. miniPayShowType: parsed.showType,
  374. miniPayShowBonus: parsed.showBonus,
  375. miniPayProfileId: parsed.profileId,
  376. miniPayProcessing: true,
  377. miniPayRequestContext: parsed
  378. }, () => {
  379. const paymentComp = this.selectComponent('#miniPayComponent');
  380. if (!paymentComp || typeof paymentComp.pay !== 'function') {
  381. this.setData({ miniPayProcessing: false });
  382. wx.showToast({
  383. title: '支付组件未就绪',
  384. icon: 'none'
  385. });
  386. return;
  387. }
  388. paymentComp.pay();
  389. });
  390. },
  391. onMiniPayResult(e) {
  392. const detail = e.detail || {};
  393. const payState = detail.params;
  394. const result = {
  395. type: 'miniPayResult',
  396. payload: {
  397. success: payState === 'ok',
  398. tradeNo: detail.no || this.data.miniPayTradeNo,
  399. payType: detail.type || 'wxpay',
  400. cancelled: payState === 'Cancel the payment',
  401. errMsg: payState && payState !== 'ok' && payState !== 'Cancel the payment'
  402. ? (typeof payState === 'string' ? payState : (payState.errMsg || ''))
  403. : ''
  404. }
  405. };
  406. this.setData({
  407. miniPayVisible: false,
  408. miniPayProcessing: false
  409. });
  410. this.notifyH5MiniPayResult(result);
  411. },
  412. notifyH5MiniPayResult(result) {
  413. const ctx = this.data.miniPayRequestContext || {};
  414. console.log('miniPayResult:', result);
  415. // web-view 不支持直接由小程序向 H5 反向 postMessage,
  416. // 若 H5 传入 callbackUrl,则通过刷新 web-view URL 回传支付结果。
  417. if (!ctx.callbackUrl) return;
  418. try {
  419. const separator = ctx.callbackUrl.includes('?') ? '&' : '?';
  420. const query = [
  421. 'miniPayResult=1',
  422. `success=${result.payload.success ? 1 : 0}`,
  423. `tradeNo=${encodeURIComponent(result.payload.tradeNo || '')}`,
  424. `payType=${encodeURIComponent(result.payload.payType || '')}`,
  425. `cancelled=${result.payload.cancelled ? 1 : 0}`,
  426. `errMsg=${encodeURIComponent(result.payload.errMsg || '')}`
  427. ].join('&');
  428. const callbackPath = `${ctx.callbackUrl}${separator}${query}`;
  429. this.setData({ path: callbackPath });
  430. } catch (error) {
  431. console.error('❌ 回传支付结果失败:', error);
  432. }
  433. },
  434. /**
  435. * 设置导航栏标题(统一方法)
  436. */
  437. setNavigationTitle: function (title) {
  438. // 当前页面使用 custom 导航,仅保留系统胶囊,不更新标题栏。
  439. return;
  440. if (!title) {
  441. return;
  442. }
  443. // 若与当前标题一致则跳过,避免频繁触发
  444. if (title === this.data.currentTitle) {
  445. return;
  446. }
  447. // 简单节流:500ms 内重复更新跳过
  448. if (!this._lastTitleUpdateTs) {
  449. this._lastTitleUpdateTs = 0;
  450. }
  451. const now = Date.now();
  452. if (now - this._lastTitleUpdateTs < 500) {
  453. return;
  454. }
  455. this._lastTitleUpdateTs = now;
  456. // 更新当前标题记录
  457. this.setData({
  458. currentTitle: title
  459. });
  460. // 延迟调用微信 API 设置标题,确保页面已准备好
  461. setTimeout(() => {
  462. wx.setNavigationBarTitle({
  463. title: title,
  464. success: () => {
  465. console.log('✅ web-view 标题设置成功:', title);
  466. },
  467. fail: (err) => {
  468. console.warn('⚠️ web-view 标题设置失败(可忽略):', err.errMsg);
  469. // 不影响主流程,静默失败
  470. }
  471. });
  472. }, 100);
  473. },
  474. startTitlePolling: function () {
  475. this.stopTitlePolling();
  476. },
  477. stopTitlePolling: function () {
  478. if (this.titlePollingTimer) {
  479. clearInterval(this.titlePollingTimer);
  480. this.titlePollingTimer = null;
  481. }
  482. },
  483. /**
  484. * 加载店铺信息并设置页面标题
  485. */
  486. loadAndSetStoreTitle: async function (storeId = '', storeName = '') {
  487. try {
  488. let finalTitle = storeName;
  489. if (!finalTitle) {
  490. // 如果没有传入名字,按传入的 storeId 精确查询;再不行按 company 兜底
  491. if (storeId) {
  492. const q = new Parse.Query('ShopStore');
  493. const s = await q.get(storeId);
  494. if (s) {
  495. // 优先使用门店地址,如果没有地址则使用门店名称
  496. const address = s.get('address');
  497. const name = s.get('storeName');
  498. finalTitle = address || name || '';
  499. console.log('📍 web-view 门店信息:', {
  500. id: storeId,
  501. name: name,
  502. address: address,
  503. displayTitle: finalTitle
  504. });
  505. }
  506. }
  507. if (!finalTitle) {
  508. const storeQuery = new Parse.Query('ShopStore');
  509. storeQuery.equalTo('company', company);
  510. storeQuery.ascending('score');
  511. storeQuery.limit(1);
  512. const store = await storeQuery.first();
  513. if (store) {
  514. // 优先使用门店地址,如果没有地址则使用门店名称
  515. const address = store.get('address');
  516. const name = store.get('storeName');
  517. finalTitle = address || name || '';
  518. }
  519. }
  520. }
  521. if (!finalTitle) return;
  522. // 使用统一的设置标题方法
  523. this.setNavigationTitle(finalTitle);
  524. } catch (e) {
  525. console.error('设置 web-view 标题失败:', e);
  526. }
  527. }
  528. })