wechatPay.js
1.78 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
/*
* @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'
/**
* @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 = '支付未完成'
if (errMsg.includes('cancel')) {
friendlyMsg = '您已取消支付'
} else if (errMsg.includes('fail')) {
friendlyMsg = '支付失败,请稍后重试'
}
return { code: 0, data: pay_result?.err || null, msg: friendlyMsg }
}