index.js 17 KB

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