index.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605
  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. if (!existingParams.has('source')) {
  260. append.push('source=wechat-miniprogram');
  261. }
  262. let token = null;
  263. let userId = null;
  264. let mobile = null;
  265. try {
  266. const currentUser = Parse && Parse.User ? Parse.User.current() : null;
  267. if (currentUser) {
  268. token = currentUser.getSessionToken() || null;
  269. userId = currentUser.id || null;
  270. mobile = currentUser.get('mobile') || null;
  271. }
  272. } catch (e) {
  273. // ignore
  274. }
  275. try {
  276. if (!token) token = wx.getStorageSync('sessionToken') || null;
  277. if (!userId) userId = wx.getStorageSync('userLogin') || null;
  278. if (!mobile) {
  279. const userInfo = wx.getStorageSync('userInfo') || {};
  280. mobile = userInfo.mobile || null;
  281. }
  282. } catch (e) {
  283. // ignore
  284. }
  285. if (token && !existingParams.has('token')) {
  286. append.push('token=' + encodeURIComponent(token));
  287. }
  288. if (userId && !existingParams.has('userId')) {
  289. append.push('userId=' + encodeURIComponent(userId));
  290. }
  291. if (mobile && !existingParams.has('mobile')) {
  292. append.push('mobile=' + encodeURIComponent(mobile));
  293. }
  294. if (append.length === 0) return path;
  295. return path + (hasQuery ? '&' : '?') + append.join('&');
  296. } catch (e) {
  297. return path;
  298. }
  299. },
  300. /**
  301. * 处理来自 H5 页面的消息
  302. */
  303. handleMessage: function (e) {
  304. try {
  305. const messages = e.detail.data || [];
  306. // 找到最后一个标题更新消息
  307. let lastTitleMessage = null;
  308. let lastPayMessage = null;
  309. for (let i = messages.length - 1; i >= 0; i--) {
  310. const msg = messages[i];
  311. if (msg.type === 'updateTitle' && msg.title) {
  312. lastTitleMessage = msg;
  313. }
  314. if (!lastPayMessage && msg.type === 'requestMiniPay') {
  315. lastPayMessage = msg;
  316. }
  317. if (lastTitleMessage && lastPayMessage) {
  318. break;
  319. }
  320. }
  321. // 更新标题
  322. if (lastTitleMessage) {
  323. this.setNavigationTitle(lastTitleMessage.title);
  324. }
  325. if (lastPayMessage) {
  326. this.handleMiniPayRequest(lastPayMessage.payload || {});
  327. }
  328. } catch (error) {
  329. console.error('❌ 处理消息失败:', error);
  330. }
  331. },
  332. normalizeMiniPayPayload(payload = {}) {
  333. const price = Number(payload.price);
  334. return {
  335. tradeNo: payload.tradeNo || '',
  336. price: Number.isFinite(price) ? price : 0,
  337. orderId: payload.orderId || '',
  338. orderType: payload.orderType || 'shopgoods',
  339. showType: payload.showType || 'all',
  340. showBonus: !!payload.showBonus,
  341. profileId: payload.profileId || '',
  342. scene: payload.scene || '',
  343. bizId: payload.bizId || '',
  344. callbackUrl: payload.callbackUrl || ''
  345. };
  346. },
  347. handleMiniPayRequest(payload = {}) {
  348. const parsed = this.normalizeMiniPayPayload(payload);
  349. if (!parsed.tradeNo) {
  350. wx.showToast({
  351. title: '支付参数缺少tradeNo',
  352. icon: 'none'
  353. });
  354. return;
  355. }
  356. if (parsed.price < 0) {
  357. wx.showToast({
  358. title: '支付金额无效',
  359. icon: 'none'
  360. });
  361. return;
  362. }
  363. if (this.data.miniPayProcessing) {
  364. wx.showToast({
  365. title: '支付进行中,请稍后',
  366. icon: 'none'
  367. });
  368. return;
  369. }
  370. this.setData({
  371. miniPayVisible: false,
  372. miniPayPrice: parsed.price,
  373. miniPayTradeNo: parsed.tradeNo,
  374. miniPayOrderId: parsed.orderId,
  375. miniPayOrderType: parsed.orderType,
  376. miniPayShowType: parsed.showType,
  377. miniPayShowBonus: parsed.showBonus,
  378. miniPayProfileId: parsed.profileId,
  379. miniPayProcessing: true,
  380. miniPayRequestContext: parsed
  381. }, () => {
  382. const paymentComp = this.selectComponent('#miniPayComponent');
  383. if (!paymentComp || typeof paymentComp.pay !== 'function') {
  384. this.setData({ miniPayProcessing: false });
  385. wx.showToast({
  386. title: '支付组件未就绪',
  387. icon: 'none'
  388. });
  389. return;
  390. }
  391. paymentComp.pay();
  392. });
  393. },
  394. onMiniPayResult(e) {
  395. const detail = e.detail || {};
  396. const payState = detail.params;
  397. const result = {
  398. type: 'miniPayResult',
  399. payload: {
  400. success: payState === 'ok',
  401. tradeNo: detail.no || this.data.miniPayTradeNo,
  402. payType: detail.type || 'wxpay',
  403. cancelled: payState === 'Cancel the payment',
  404. errMsg: payState && payState !== 'ok' && payState !== 'Cancel the payment'
  405. ? (typeof payState === 'string' ? payState : (payState.errMsg || ''))
  406. : ''
  407. }
  408. };
  409. this.setData({
  410. miniPayVisible: false,
  411. miniPayProcessing: false
  412. });
  413. this.notifyH5MiniPayResult(result);
  414. },
  415. notifyH5MiniPayResult(result) {
  416. const ctx = this.data.miniPayRequestContext || {};
  417. console.log('miniPayResult:', result);
  418. // web-view 不支持直接由小程序向 H5 反向 postMessage,
  419. // 若 H5 传入 callbackUrl,则通过刷新 web-view URL 回传支付结果。
  420. if (!ctx.callbackUrl) return;
  421. try {
  422. const separator = ctx.callbackUrl.includes('?') ? '&' : '?';
  423. const query = [
  424. 'miniPayResult=1',
  425. `success=${result.payload.success ? 1 : 0}`,
  426. `tradeNo=${encodeURIComponent(result.payload.tradeNo || '')}`,
  427. `payType=${encodeURIComponent(result.payload.payType || '')}`,
  428. `cancelled=${result.payload.cancelled ? 1 : 0}`,
  429. `errMsg=${encodeURIComponent(result.payload.errMsg || '')}`
  430. ].join('&');
  431. const callbackPath = `${ctx.callbackUrl}${separator}${query}`;
  432. this.setData({ path: callbackPath });
  433. } catch (error) {
  434. console.error('❌ 回传支付结果失败:', error);
  435. }
  436. },
  437. /**
  438. * 设置导航栏标题(统一方法)
  439. */
  440. setNavigationTitle: function (title) {
  441. // 当前页面使用 custom 导航,仅保留系统胶囊,不更新标题栏。
  442. return;
  443. if (!title) {
  444. return;
  445. }
  446. // 若与当前标题一致则跳过,避免频繁触发
  447. if (title === this.data.currentTitle) {
  448. return;
  449. }
  450. // 简单节流:500ms 内重复更新跳过
  451. if (!this._lastTitleUpdateTs) {
  452. this._lastTitleUpdateTs = 0;
  453. }
  454. const now = Date.now();
  455. if (now - this._lastTitleUpdateTs < 500) {
  456. return;
  457. }
  458. this._lastTitleUpdateTs = now;
  459. // 更新当前标题记录
  460. this.setData({
  461. currentTitle: title
  462. });
  463. // 延迟调用微信 API 设置标题,确保页面已准备好
  464. setTimeout(() => {
  465. wx.setNavigationBarTitle({
  466. title: title,
  467. success: () => {
  468. console.log('✅ web-view 标题设置成功:', title);
  469. },
  470. fail: (err) => {
  471. console.warn('⚠️ web-view 标题设置失败(可忽略):', err.errMsg);
  472. // 不影响主流程,静默失败
  473. }
  474. });
  475. }, 100);
  476. },
  477. startTitlePolling: function () {
  478. this.stopTitlePolling();
  479. },
  480. stopTitlePolling: function () {
  481. if (this.titlePollingTimer) {
  482. clearInterval(this.titlePollingTimer);
  483. this.titlePollingTimer = null;
  484. }
  485. },
  486. /**
  487. * 加载店铺信息并设置页面标题
  488. */
  489. loadAndSetStoreTitle: async function (storeId = '', storeName = '') {
  490. try {
  491. let finalTitle = storeName;
  492. if (!finalTitle) {
  493. // 如果没有传入名字,按传入的 storeId 精确查询;再不行按 company 兜底
  494. if (storeId) {
  495. const q = new Parse.Query('ShopStore');
  496. const s = await q.get(storeId);
  497. if (s) {
  498. // 优先使用门店地址,如果没有地址则使用门店名称
  499. const address = s.get('address');
  500. const name = s.get('storeName');
  501. finalTitle = address || name || '';
  502. console.log('📍 web-view 门店信息:', {
  503. id: storeId,
  504. name: name,
  505. address: address,
  506. displayTitle: finalTitle
  507. });
  508. }
  509. }
  510. if (!finalTitle) {
  511. const storeQuery = new Parse.Query('ShopStore');
  512. storeQuery.equalTo('company', company);
  513. storeQuery.ascending('score');
  514. storeQuery.limit(1);
  515. const store = await storeQuery.first();
  516. if (store) {
  517. // 优先使用门店地址,如果没有地址则使用门店名称
  518. const address = store.get('address');
  519. const name = store.get('storeName');
  520. finalTitle = address || name || '';
  521. }
  522. }
  523. }
  524. if (!finalTitle) return;
  525. // 使用统一的设置标题方法
  526. this.setNavigationTitle(finalTitle);
  527. } catch (e) {
  528. console.error('设置 web-view 标题失败:', e);
  529. }
  530. }
  531. })