/** * 微信小程序真实支付(APIv3 JSAPI)与师傅端新版商家转账确认收款封装 */ import api from './api.js'; /** * 安全获取当前微信登录凭证 code(非微信小程序环境或获取失败时返回空串) * @returns {Promise} */ export function getSafeWxCode() { // #ifdef MP-WEIXIN return new Promise((resolve, reject) => { let settled = false; const finishErr = (msg) => { if (settled) return; settled = true; uni.showToast({ title: msg, icon: 'none' }); reject(Object.assign(new Error(msg), { handledToast: true })); }; const finishOk = (code) => { if (settled) return; settled = true; resolve(code); }; const timer = setTimeout(() => finishErr('获取微信登录凭证超时,请检查网络后重试'), 5000); try { uni.login({ provider: 'weixin', success: (res) => { clearTimeout(timer); const code = res && res.code ? String(res.code).trim() : ''; if (!code) { finishErr('未能获取到微信登录凭证,请重新进入小程序再试'); return; } finishOk(code); }, fail: (err) => { clearTimeout(timer); const detail = err && err.errMsg ? `(${err.errMsg})` : ''; finishErr(`获取微信登录凭证失败${detail},请重试`); } }); } catch (e) { clearTimeout(timer); finishErr('调起微信登录失败,请重试'); } }); // #endif // #ifndef MP-WEIXIN return Promise.resolve(''); // #endif } /** * 统一发起用户端订单微信支付并完成主动查单核销 * 适用场景:订单首次支付(api.orderPay)、选定师傅报价支付(api.orderChooseQuote)、施工现场增项补差价支付(api.orderPayDiff) * * @param {Function} createPayApiFn 后端统一下单接口方法 * @param {Object} params 业务入参(如 { order_id } 或 { order_id, quote_id }) * @returns {Promise} */ export async function executeOrderWxPay(createPayApiFn, params = {}, promptPaymentPassword) { const payload = Object.assign({}, params); if (payload.pay_type === 'balance') { if (typeof promptPaymentPassword !== 'function') throw new Error('支付密码输入不可用'); payload.payment_password = await promptPaymentPassword(); if (!payload.payment_password) throw Object.assign(new Error('支付已取消'), { cancelled: true }); } // 纯余额支付无需向微信换取登录凭证 code,直接请求后端原子核销入账 if (payload.pay_type !== 'balance') { const wxCode = await getSafeWxCode(); if (wxCode) { payload.wx_code = wxCode; } } const res = await createPayApiFn(payload); // 0 元优惠券全额抵扣或已付足无需补付时,后端直接完成核销并返回 paid: true if (res && (res.paid === true || res.need_wxpay === false)) { return res; } if (!res || !res.pay_params) { const msg = '未获取到有效的微信支付参数,请稍后重试'; uni.showToast({ title: msg, icon: 'none' }); throw new Error(msg); } // #ifdef MP-WEIXIN // 核心修复:调用微信原生支付组件前,必须先关闭前端自定义 loading,杜绝与微信官方加载浮层重叠 try { uni.hideLoading(); } catch (e) {} const p = res.pay_params; await new Promise((resolve, reject) => { uni.requestPayment({ provider: 'weixin', timeStamp: String(p.timeStamp), nonceStr: String(p.nonceStr), package: String(p.package), signType: String(p.signType || 'RSA'), paySign: String(p.paySign), success: () => resolve(true), fail: (err) => { const errMsg = String((err && err.errMsg) || ''); const isCancel = errMsg.indexOf('cancel') !== -1; const tip = isCancel ? '已取消微信支付' : '微信支付未完成,请重试'; uni.showToast({ title: tip, icon: 'none' }); reject(Object.assign(new Error(tip), { cancelled: isCancel, raw: err })); } }); }); // 收银台扣款成功后,展示明确的查单核销状态 try { uni.showLoading({ title: '正在确认支付结果...', mask: true }); } catch (e) {} // 主动请求后端向微信网关查单核销(绝不返回伪造的已支付状态) const verifyOnce = () => api.orderConfirmPay({ out_trade_no: res.out_trade_no, order_id: res.order_id }); let confirmRes; try { confirmRes = await verifyOnce(); if (confirmRes && confirmRes.paid !== true && ['USERPAYING', 'NOTPAY'].includes(confirmRes.trade_state)) { await new Promise((r) => setTimeout(r, 900)); confirmRes = await verifyOnce(); } } catch (firstErr) { // 仅当为网络层临时中断(无业务响应码)时等待 900ms 复查一次;业务明确报错直接透传 if (firstErr && firstErr.code === undefined) { await new Promise((r) => setTimeout(r, 900)); try { confirmRes = await verifyOnce(); } catch (secondErr) { try { uni.hideLoading(); } catch (e) {} const errMsg = (secondErr && secondErr.message) || '向微信核销支付状态失败,请在订单详情刷新确认'; uni.showToast({ title: errMsg, icon: 'none' }); throw Object.assign(new Error(errMsg), { handledToast: true, raw: secondErr }); } } else { try { uni.hideLoading(); } catch (e) {} const errMsg = (firstErr && firstErr.message) || '支付核销失败,请查看订单详情或联系客服'; uni.showToast({ title: errMsg, icon: 'none' }); throw Object.assign(new Error(errMsg), { handledToast: true, raw: firstErr }); } } finally { try { uni.hideLoading(); } catch (e) {} } if (!confirmRes || confirmRes.paid !== true) { const stateText = confirmRes && confirmRes.trade_state_text ? confirmRes.trade_state_text : '尚未确认到账'; const msg = `支付暂未确认入账(${stateText}),请在订单详情刷新核实`; uni.showToast({ title: msg, icon: 'none' }); throw Object.assign(new Error(msg), { handledToast: true, unconfirmed: true, data: confirmRes }); } return Object.assign({}, confirmRes, { out_trade_no: res.out_trade_no }); // #endif // #ifndef MP-WEIXIN uni.showModal({ title: '请在微信小程序内支付', content: '当前运行环境不支持调起微信小程序收银台,请在微信小程序中打开订单完成支付。', showCancel: false, confirmText: '知道了' }); throw Object.assign(new Error('请在微信小程序内完成支付'), { unsupportedEnv: true }); // #endif } /** 支付确认后打开结果页,订单和支付详情由结果页重新向服务端核实。 */ export function openOrderPaymentResult(orderId, result, replace = false) { const url = `/pages/order/payment-success?order_id=${encodeURIComponent(orderId)}&out_trade_no=${encodeURIComponent((result && result.out_trade_no) || '')}`; const options = { url, fail: () => uni.redirectTo({ url: `/pages/order/detail?id=${encodeURIComponent(orderId)}` }) }; if (replace) uni.redirectTo(options); else uni.navigateTo(options); } /** * 师傅端调起微信官方「商家转账」确认收款页(wx.requestMerchantTransfer)并在返回后同步真实入账状态 * * @param {Number} withdrawId 提现申请记录 ID * @returns {Promise<{ done: boolean, withdraw: Object|null }>} */ export async function invokeMerchantTransferConfirm(withdrawId) { const pkg = await api.masterTransferPackage({ withdraw_id: withdrawId }); if (pkg && pkg.already_done) { uni.showToast({ title: '该笔提现已到账微信零钱', icon: 'none' }); return { done: true, withdraw: pkg.withdraw || null }; } if (!pkg || !pkg.package_info || !pkg.mch_id || !pkg.app_id) { const msg = '未获取到收款确认凭证,请稍后刷新重试'; uni.showToast({ title: msg, icon: 'none' }); throw new Error(msg); } // #ifdef MP-WEIXIN const canUseTransfer = typeof wx !== 'undefined' && typeof wx.requestMerchantTransfer === 'function' && (!wx.canIUse || wx.canIUse('requestMerchantTransfer')); if (!canUseTransfer) { uni.showModal({ title: '请升级微信版本', content: '当前微信客户端版本过低,暂不支持商家转账确认收款,请升级至最新版微信后再试。', showCancel: false, confirmText: '知道了' }); throw new Error('微信版本过低'); } let transferInvokeError = null; await new Promise((resolve) => { wx.requestMerchantTransfer({ mchId: String(pkg.mch_id), appId: String(pkg.app_id), package: String(pkg.package_info), success: () => { resolve(); }, fail: (err) => { transferInvokeError = err || null; resolve(); } }); }); // 无论用户点击确认收款还是左上角返回,均向后端发起一次真实网关状态同步,失败直接抛出真实原因 try { const syncRes = await api.masterSyncWithdraw({ withdraw_id: withdrawId }); if (syncRes && syncRes.done) { uni.showToast({ title: '收款成功,已入账微信零钱', icon: 'success' }); return { done: true, withdraw: syncRes.withdraw || null }; } const wd = syncRes ? syncRes.withdraw : null; if (wd && wd.status === 'reject') { const rejectReason = wd.fail_reason || wd.audit_msg || '微信转账失败或已失效'; uni.showModal({ title: '收款未能完成', content: rejectReason, showCancel: false, confirmText: '知道了' }); return { done: false, withdraw: wd }; } if (transferInvokeError) { const rawMsg = String(transferInvokeError.errMsg || ''); const isCancel = rawMsg.indexOf('cancel') !== -1; uni.showToast({ title: isCancel ? '您已取消确认收款,可随时再次点击领取' : `调起收款确认未完成(${rawMsg || '未知原因'})`, icon: 'none' }); } else { const stTxt = wd && wd.status_text ? wd.status_text : '待确认收款'; uni.showToast({ title: `当前状态:${stTxt}`, icon: 'none' }); } return { done: false, withdraw: wd }; } catch (syncErr) { const errMsg = (syncErr && syncErr.message) || '向微信同步收款状态失败,请稍后重试'; uni.showToast({ title: errMsg, icon: 'none' }); throw Object.assign(syncErr instanceof Error ? syncErr : new Error(errMsg), { handledToast: true }); } // #endif // #ifndef MP-WEIXIN uni.showModal({ title: '请在微信小程序内确认收款', content: '微信零钱商家转账需在微信小程序内拉起官方收款页,请使用微信小程序打开「我的钱包」领取。', showCancel: false, confirmText: '知道了' }); throw Object.assign(new Error('请在微信小程序内确认收款'), { unsupportedEnv: true }); // #endif } /** * 发起用户端在线微信充值并核销 * @param {number|string} amount 充值金额(元) * @returns {Promise} */ export async function executeUserRecharge(amount) { const amt = Number(amount); if (isNaN(amt) || amt <= 0) { const msg = '请输入有效的充值金额'; uni.showToast({ title: msg, icon: 'none' }); throw new Error(msg); } const wxCode = await getSafeWxCode(); const payload = { amount: amt }; if (wxCode) { payload.wx_code = wxCode; } const res = await api.userRecharge(payload); if (!res || !res.pay_params) { const msg = '未获取到微信充值支付参数,请稍后重试'; uni.showToast({ title: msg, icon: 'none' }); throw new Error(msg); } // #ifdef MP-WEIXIN // 核心修复:调用微信原生支付组件前,必须先关闭前端自定义 loading,杜绝与微信官方加载浮层重叠 try { uni.hideLoading(); } catch (e) {} const p = res.pay_params; await new Promise((resolve, reject) => { uni.requestPayment({ provider: 'weixin', timeStamp: String(p.timeStamp), nonceStr: String(p.nonceStr), package: String(p.package), signType: String(p.signType || 'RSA'), paySign: String(p.paySign), success: () => resolve(true), fail: (err) => { const errMsg = String((err && err.errMsg) || ''); const isCancel = errMsg.indexOf('cancel') !== -1; const tip = isCancel ? '已取消充值' : '微信支付未完成,请重试'; uni.showToast({ title: tip, icon: 'none' }); reject(Object.assign(new Error(tip), { cancelled: isCancel, raw: err })); } }); }); // 微信支付成功后,展示明确的核销中 loading 状态 try { uni.showLoading({ title: '正在确认到账...', mask: true }); } catch (e) {} let confirmRes; try { confirmRes = await api.userConfirmRecharge({ out_trade_no: res.out_trade_no }); } finally { try { uni.hideLoading(); } catch (e) {} } return confirmRes; // #endif // #ifndef MP-WEIXIN return res; // #endif }