API 报错
This commit is contained in:
+77
-1
@@ -361,8 +361,84 @@ async function refundPayment(ctx) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询支付结果
|
||||
* 调用微信支付订单查询API,确认支付状态
|
||||
*/
|
||||
async function queryPayment(ctx) {
|
||||
const { orderId } = ctx.params
|
||||
|
||||
if (!orderId) {
|
||||
ctx.body = { code: 400, message: '订单ID不能为空' }
|
||||
return
|
||||
}
|
||||
|
||||
// 查询本地订单
|
||||
const orders = await query('SELECT * FROM orders WHERE id = ?', [orderId])
|
||||
if (orders.length === 0) {
|
||||
ctx.body = { code: 404, message: '订单不存在' }
|
||||
return
|
||||
}
|
||||
|
||||
const order = orders[0]
|
||||
|
||||
// 如果本地已标记为已支付,直接返回
|
||||
if (order.status === 'paid') {
|
||||
ctx.body = { code: 200, data: { orderId: order.id, status: 'paid', transactionId: order.transaction_id } }
|
||||
return
|
||||
}
|
||||
|
||||
// 检查支付配置
|
||||
if (!APPID || !MCH_ID || !API_KEY) {
|
||||
ctx.body = { code: 200, data: { orderId: order.id, status: order.status } }
|
||||
return
|
||||
}
|
||||
|
||||
// 调用微信订单查询API
|
||||
const params = {
|
||||
appid: APPID,
|
||||
mch_id: MCH_ID,
|
||||
out_trade_no: orderId,
|
||||
nonce_str: generateNonceStr()
|
||||
}
|
||||
params.sign = generateSign(params)
|
||||
|
||||
try {
|
||||
const xmlData = buildXML(params)
|
||||
const response = await fetch(ORDER_QUERY_URL, {
|
||||
method: 'POST',
|
||||
body: xmlData,
|
||||
headers: { 'Content-Type': 'application/xml' }
|
||||
})
|
||||
|
||||
const resultXml = await response.text()
|
||||
const result = await parseXML(resultXml)
|
||||
|
||||
if (result.return_code !== 'SUCCESS') {
|
||||
ctx.body = { code: 500, message: '查询支付状态通信失败' }
|
||||
return
|
||||
}
|
||||
|
||||
if (result.trade_state === 'SUCCESS') {
|
||||
// 微信确认已支付,更新本地订单状态
|
||||
const transactionId = result.transaction_id || null
|
||||
await query(
|
||||
'UPDATE orders SET status = ?, transaction_id = ? WHERE id = ? AND status != ?',
|
||||
['paid', transactionId, orderId, 'paid']
|
||||
)
|
||||
ctx.body = { code: 200, data: { orderId: order.id, status: 'paid', transactionId } }
|
||||
} else {
|
||||
ctx.body = { code: 200, data: { orderId: order.id, status: order.status, tradeState: result.trade_state } }
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('查询支付状态失败:', error)
|
||||
ctx.body = { code: 200, data: { orderId: order.id, status: order.status } }
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
createPayment,
|
||||
paymentNotify,
|
||||
refundPayment
|
||||
refundPayment,
|
||||
queryPayment
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user