wechatPay.js
2.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
/*
* @Date: 2026-01-16 19:41:09
* @LastEditors: hookehuyr hookehuyr@gmail.com
* @LastEditTime: 2026-01-20 11:40:46
* @FilePath: /xyxBooking-weapp/src/utils/wechatPay.js
* @Description: 微信支付工具函数
*/
import Taro from '@tarojs/taro'
import { wxPayAPI } from '@/api/wx/pay'
import { billCancelUnpaidAPI } from '@/api/index'
import { ENABLE_REPAY_FEATURE } from '@/utils/config'
/**
* @description 微信支付
* @param {*} pay_id 订单号
* @returns {*} 支付结果
*/
export const wechat_pay = async ({ pay_id }) => {
const normalized_pay_id = String(pay_id || '')
if (!normalized_pay_id) {
return { code: 0, data: null, msg: '缺少订单号' }
}
Taro.showLoading({ title: '支付准备中...' })
let pay_params_res = null
try {
pay_params_res = await wxPayAPI({ pay_id: normalized_pay_id })
} finally {
Taro.hideLoading()
}
if (!pay_params_res || pay_params_res.code !== 1) {
return { code: 0, data: null, msg: pay_params_res?.msg || '获取支付信息失败,请稍后再试' }
}
const pay_params = pay_params_res?.data || {}
const pay_result = await new Promise(resolve => {
Taro.requestPayment({
timeStamp: pay_params.timeStamp,
nonceStr: pay_params.nonceStr,
package: pay_params.package,
signType: pay_params.signType,
paySign: pay_params.paySign,
success: res => resolve({ ok: true, res }),
fail: err => resolve({ ok: false, err })
})
})
if (pay_result?.ok) {
return { code: 1, data: pay_result.res || null, msg: '支付成功' }
}
// 优化错误提示文案
const errMsg = pay_result?.err?.errMsg || ''
let friendlyMsg = '支付未完成'
let showConfirmAndBack = false
if (errMsg.includes('cancel')) {
friendlyMsg = '您已取消支付'
showConfirmAndBack = true
} else if (errMsg.includes('fail')) {
friendlyMsg = '支付失败'
showConfirmAndBack = true
}
// 如果重新支付功能关闭,直接提示并返回上一页
if (!ENABLE_REPAY_FEATURE && showConfirmAndBack) {
// 自动取消订单
Taro.showLoading({ title: '取消订单中...' })
try {
const { code } = await billCancelUnpaidAPI({ pay_id: normalized_pay_id })
Taro.hideLoading()
if (code) {
// 取消成功,更新提示文案
friendlyMsg = `${friendlyMsg},订单已自动取消`
}
} catch (e) {
Taro.hideLoading()
console.error('取消订单失败:', e)
}
await Taro.showModal({
title: friendlyMsg,
content: '订单未完成支付,如有需要请重新预约',
showCancel: false,
confirmText: '我知道了'
})
// 返回上一页
const pages = Taro.getCurrentPages()
if (pages.length > 1) {
Taro.navigateBack()
}
}
return { code: 0, data: pay_result?.err || null, msg: friendlyMsg }
}