fix: 修复支付可能存在的缺陷

This commit is contained in:
archer
2023-03-22 12:20:27 +08:00
parent 984baf60f0
commit 5ec303610c
12 changed files with 266 additions and 93 deletions

View File

@@ -3,56 +3,68 @@ import { jsonRes } from '@/service/response';
import axios from 'axios';
import { connectToDatabase, User, Pay } from '@/service/mongo';
import { authToken } from '@/service/utils/tools';
import { formatPrice } from '@/utils/user';
import { PaySchema } from '@/types/mongoSchema';
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
try {
const { authorization } = req.headers;
let { orderId } = req.query as { orderId: string };
let { payId } = req.query as { payId: string };
const userId = await authToken(authorization);
await connectToDatabase();
// 查找订单记录校验
const payOrder = await Pay.findById<PaySchema>(payId);
if (!payOrder) {
throw new Error('订单不存在');
}
if (payOrder.status !== 'NOTPAY') {
throw new Error('订单已结算');
}
const { data } = await axios.get(
`https://sif268.laf.dev/wechat-order-query?order_number=${orderId}&api_key=${process.env.WXPAYCODE}`
`https://sif268.laf.dev/wechat-order-query?order_number=${payOrder.orderId}&api_key=${process.env.WXPAYCODE}`
);
if (data.trade_state === 'SUCCESS') {
await connectToDatabase();
// 重复记录校验
const count = await Pay.count({
orderId
});
if (count > 0) {
throw new Error('订单重复,请刷新');
}
// 计算实际充值。把分转成数据库的值
const price = data.amount.total * 0.01 * 100000;
let payId;
// 订单已支付
try {
// 充值记录 +1
const payRecord = await Pay.create({
userId,
price,
orderId
});
payId = payRecord._id;
// 充钱
await User.findByIdAndUpdate(userId, {
$inc: { balance: price }
});
// 更新订单状态
const updateRes = await Pay.updateOne(
{
_id: payId,
status: 'NOTPAY'
},
{
status: 'SUCCESS'
}
);
if (updateRes.modifiedCount === 1) {
// 给用户账号充钱
await User.findByIdAndUpdate(userId, {
$inc: { balance: payOrder.price }
});
jsonRes(res, {
data: 'success'
});
}
} catch (error) {
payId && Pay.findByIdAndDelete(payId);
await Pay.findByIdAndUpdate(payId, {
status: 'NOTPAY'
});
console.log(error);
}
jsonRes(res, {
data: 'success'
} else if (data.trade_state === 'CLOSED') {
// 订单已关闭
await Pay.findByIdAndUpdate(payId, {
status: 'CLOSED'
});
} else {
throw new Error(data.trade_state_desc);
}
throw new Error('订单已过期');
} catch (err) {
console.log(err);
jsonRes(res, {

View File

@@ -25,7 +25,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
const bills = await Bill.find<BillSchema>({
userId
})
.sort({ createdAt: -1 }) // 按照创建时间倒序排列
.sort({ time: -1 }) // 按照创建时间倒序排列
.skip((pageNum - 1) * pageSize)
.limit(pageSize);

View File

@@ -4,6 +4,8 @@ import { jsonRes } from '@/service/response';
import axios from 'axios';
import { authToken } from '@/service/utils/tools';
import { customAlphabet } from 'nanoid';
import { connectToDatabase, Pay } from '@/service/mongo';
const nanoid = customAlphabet('abcdefghijklmnopqrstuvwxyz1234567890', 20);
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
@@ -15,9 +17,10 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
if (!authorization) {
throw new Error('缺少登录凭证');
}
await authToken(authorization);
const userId = await authToken(authorization);
const id = nanoid();
await connectToDatabase();
const response = await axios({
url: 'https://sif268.laf.dev/wechat-pay',
@@ -29,9 +32,16 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
}
});
// 充值记录 + 1
const payOrder = await Pay.create({
userId,
price: amount * 100000,
orderId: id
});
jsonRes(res, {
data: {
orderId: id,
payId: payOrder._id,
codeUrl: response.data?.code_url
}
});

View File

@@ -0,0 +1,31 @@
import type { NextApiRequest, NextApiResponse } from 'next';
import { jsonRes } from '@/service/response';
import { authToken } from '@/service/utils/tools';
import { connectToDatabase, Pay } from '@/service/mongo';
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
try {
const { authorization } = req.headers;
if (!authorization) {
throw new Error('缺少登录凭证');
}
const userId = await authToken(authorization);
await connectToDatabase();
const records = await Pay.find({
userId
}).sort({ createTime: -1 });
jsonRes(res, {
data: records
});
} catch (err) {
console.log(err);
jsonRes(res, {
code: 500,
error: err
});
}
}