index.js 19 KB

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