/** * 微信H5支付工具 * 统一处理微信JSAPI支付逻辑 */ /** * 调起微信H5支付 * @param {Object} payConfig - 支付配置对象 * @param {string} payConfig.app_id - 微信公众号appid * @param {string} payConfig.timestamp - 时间戳 * @param {string} payConfig.nonce_str - 随机字符串 * @param {string} payConfig.package - 预支付交易会话标识 * @param {string} payConfig.sign_type - 签名方式 * @param {string} payConfig.pay_sign - 签名 * @returns {Promise} 支付结果 */ export function wechatH5Pay(payConfig) { return new Promise((resolve, reject) => { // 验证支付配置 if (!payConfig || !payConfig.package) { reject(new Error('支付参数无效')); return; } // 验证 package 格式 if (!payConfig.package.startsWith('prepay_id=')) { reject(new Error('支付参数无效')); return; } // 检查是否在微信环境中 if (typeof WeixinJSBridge === 'undefined') { reject(new Error('请在微信中打开')); return; } // 调起微信支付 WeixinJSBridge.invoke('getBrandWCPayRequest', { appId: payConfig.app_id, timeStamp: payConfig.timestamp, nonceStr: payConfig.nonce_str, package: payConfig.package, signType: payConfig.sign_type, paySign: payConfig.pay_sign }, function(res) { if (res.err_msg === 'get_brand_wcpay_request:ok') { // 支付成功 resolve({ success: true, message: '支付成功' }); } else if (res.err_msg === 'get_brand_wcpay_request:cancel') { // 用户取消支付 reject({ cancelled: true, message: '已取消支付' }); } else { // 支付失败 reject({ success: false, message: '支付失败', error: res }); } }); }); } /** * 显示支付结果提示 * @param {boolean} success - 是否成功 * @param {string} message - 提示消息 */ export function showPaymentToast(success, message) { uni.showToast({ title: message || (success ? '支付成功' : '支付失败'), icon: success ? 'success' : 'none', duration: 2000 }); } /** * 处理支付错误 * @param {Error|Object} error - 错误对象 */ export function handlePaymentError(error) { if (error.cancelled) { // 用户主动取消,提示取消 showPaymentToast(false, '已取消支付'); } else { // 其他错误 const message = error.message || '支付失败'; showPaymentToast(false, message); } }