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

@@ -4,7 +4,7 @@ import { ResLogin } from './response/user';
import { EmailTypeEnum } from '@/constants/common';
import { UserType, UserUpdateParams } from '@/types/user';
import type { PagingData, RequestPaging } from '@/types';
import { BillSchema } from '@/types/mongoSchema';
import { BillSchema, PaySchema } from '@/types/mongoSchema';
import { adaptBill } from '@/utils/adapt';
export const sendCodeToEmail = ({ email, type }: { email: string; type: `${EmailTypeEnum}` }) =>
@@ -56,11 +56,12 @@ export const getUserBills = (data: RequestPaging) =>
data: res.data.map((bill) => adaptBill(bill))
}));
export const getPayOrders = () => GET<PaySchema[]>(`/user/getPayOrders`);
export const getPayCode = (amount: number) =>
GET<{
codeUrl: string;
orderId: string;
payId: string;
}>(`/user/getPayCode?amount=${amount}`);
export const checkPayResult = (orderId: string) =>
GET<number>(`/user/checkPayResult?orderId=${orderId}`);
export const checkPayResult = (payId: string) => GET<number>(`/user/checkPayResult?payId=${payId}`);

View File

@@ -0,0 +1,49 @@
import React from 'react';
import {
Box,
Button,
Modal,
ModalOverlay,
ModalContent,
ModalHeader,
ModalFooter,
ModalBody,
ModalCloseButton,
useColorModeValue
} from '@chakra-ui/react';
import Image from 'next/image';
const WxConcat = ({ onClose }: { onClose: () => void }) => {
return (
<Modal isOpen={true} onClose={onClose}>
<ModalOverlay />
<ModalContent color={useColorModeValue('blackAlpha.700', 'white')}>
<ModalHeader>wx交流群</ModalHeader>
<ModalCloseButton />
<ModalBody textAlign={'center'}>
<Image
style={{ margin: 'auto' }}
src={'/imgs/wxcode.jpg'}
width={200}
height={200}
alt=""
/>
<Box mt={2}>
:{' '}
<Box as={'span'} userSelect={'all'}>
YNyiqi
</Box>
</Box>
</ModalBody>
<ModalFooter>
<Button variant={'outline'} onClick={onClose}>
</Button>
</ModalFooter>
</ModalContent>
</Modal>
);
};
export default WxConcat;

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
});
}
}

View File

@@ -32,7 +32,7 @@ import { useCopyData } from '@/utils/tools';
import Markdown from '@/components/Markdown';
import { shareHint } from '@/constants/common';
import { getChatSiteId } from '@/api/chat';
import Image from 'next/image';
import WxConcat from '@/components/WxConcat';
const SlideBar = ({
name,
@@ -305,34 +305,7 @@ const SlideBar = ({
</ModalContent>
</Modal>
{/* wx 联系 */}
<Modal isOpen={isOpenWx} onClose={onCloseWx}>
<ModalOverlay />
<ModalContent color={useColorModeValue('blackAlpha.700', 'white')}>
<ModalHeader>wx交流群</ModalHeader>
<ModalCloseButton />
<ModalBody textAlign={'center'}>
<Image
style={{ margin: 'auto' }}
src={'/imgs/wxcode.jpg'}
width={200}
height={200}
alt=""
/>
<Box mt={2}>
:{' '}
<Box as={'span'} userSelect={'all'}>
YNyiqi
</Box>
</Box>
</ModalBody>
<ModalFooter>
<Button variant={'outline'} onClick={onCloseWx}>
</Button>
</ModalFooter>
</ModalContent>
</Modal>
{isOpenWx && <WxConcat onClose={onCloseWx} />}
</Flex>
);
};

View File

@@ -15,14 +15,14 @@ import {
import { getPayCode, checkPayResult } from '@/api/user';
import { useToast } from '@/hooks/useToast';
import { useQuery } from '@tanstack/react-query';
import { useUserStore } from '@/store/user';
import { useRouter } from 'next/router';
const PayModal = ({ onClose }: { onClose: () => void }) => {
const router = useRouter();
const { toast } = useToast();
const { initUserInfo } = useUserStore();
const [inputVal, setInputVal] = useState<number | ''>('');
const [loading, setLoading] = useState(false);
const [orderId, setOrderId] = useState('');
const [payId, setPayId] = useState('');
const handleClickPay = useCallback(async () => {
if (!inputVal || inputVal <= 0 || isNaN(+inputVal)) return;
@@ -38,7 +38,7 @@ const PayModal = ({ onClose }: { onClose: () => void }) => {
colorLight: '#ffffff',
correctLevel: QRCode.CorrectLevel.H
});
setOrderId(res.orderId);
setPayId(res.payId);
} catch (error) {
toast({
title: '出现了一些意外...',
@@ -50,21 +50,20 @@ const PayModal = ({ onClose }: { onClose: () => void }) => {
}, [inputVal, toast]);
useQuery(
[orderId],
[payId],
() => {
if (!orderId) return null;
return checkPayResult(orderId);
if (!payId) return null;
return checkPayResult(payId);
},
{
refetchInterval: 2000,
onSuccess(res) {
if (!res) return;
onClose();
initUserInfo();
toast({
title: '充值成功',
status: 'success'
});
router.reload();
}
}
);
@@ -74,17 +73,17 @@ const PayModal = ({ onClose }: { onClose: () => void }) => {
<Modal
isOpen={true}
onClose={() => {
if (orderId) return;
if (payId) return;
onClose();
}}
>
<ModalOverlay />
<ModalContent>
<ModalHeader></ModalHeader>
{!orderId && <ModalCloseButton />}
{!payId && <ModalCloseButton />}
<ModalBody>
{!orderId && (
{!payId && (
<>
<Grid gridTemplateColumns={'repeat(4,1fr)'} gridGap={5} mb={4}>
{[5, 10, 20, 50].map((item) => (
@@ -112,18 +111,23 @@ const PayModal = ({ onClose }: { onClose: () => void }) => {
)}
{/* 付费二维码 */}
<Box textAlign={'center'}>
{orderId && <Box mb={3}>: {inputVal}</Box>}
{payId && <Box mb={3}>: {inputVal}</Box>}
<Box id={'payQRCode'} display={'inline-block'}></Box>
</Box>
</ModalBody>
<ModalFooter>
{!orderId && (
{!payId && (
<>
<Button colorScheme={'gray'} onClick={onClose}>
</Button>
<Button ml={3} isLoading={loading} onClick={handleClickPay}>
<Button
ml={3}
isLoading={loading}
isDisabled={!inputVal || inputVal === 0}
onClick={handleClickPay}
>
</Button>
</>

View File

@@ -13,12 +13,13 @@ import {
TableContainer,
Select,
Input,
IconButton
IconButton,
useDisclosure
} from '@chakra-ui/react';
import { DeleteIcon } from '@chakra-ui/icons';
import { useForm, useFieldArray } from 'react-hook-form';
import { UserUpdateParams } from '@/types/user';
import { putUserInfo, getUserBills } from '@/api/user';
import { putUserInfo, getUserBills, getPayOrders, checkPayResult } from '@/api/user';
import { useToast } from '@/hooks/useToast';
import { useGlobalStore } from '@/store/global';
import { useUserStore } from '@/store/user';
@@ -27,6 +28,10 @@ import { usePaging } from '@/hooks/usePaging';
import type { UserBillType } from '@/types/user';
import { useQuery } from '@tanstack/react-query';
import dynamic from 'next/dynamic';
import { PaySchema } from '@/types/mongoSchema';
import dayjs from 'dayjs';
import { formatPrice } from '@/utils/user';
import WxConcat from '@/components/WxConcat';
const PayModal = dynamic(() => import('./components/PayModal'));
@@ -37,6 +42,7 @@ const NumberSetting = () => {
defaultValues: userInfo as UserType
});
const [showPay, setShowPay] = useState(false);
const { isOpen: isOpenWx, onOpen: onOpenWx, onClose: onCloseWx } = useDisclosure();
const { toast } = useToast();
const {
fields: accounts,
@@ -50,6 +56,7 @@ const NumberSetting = () => {
api: getUserBills,
pageSize: 30
});
const [payOrders, setPayOrders] = useState<PaySchema[]>([]);
const onclickSave = useCallback(
async (data: UserUpdateParams) => {
@@ -69,6 +76,31 @@ const NumberSetting = () => {
useQuery(['init'], initUserInfo);
useQuery(['initPayOrder'], getPayOrders, {
onSuccess(res) {
setPayOrders(res);
}
});
const handleRefreshPayOrder = useCallback(
async (payId: string) => {
try {
setLoading(true);
await checkPayResult(payId);
const res = await getPayOrders();
setPayOrders(res);
} catch (error: any) {
toast({
title: error?.message,
status: 'warning'
});
console.log(error);
}
setLoading(false);
},
[setLoading, toast]
);
return (
<>
<Card px={6} py={4}>
@@ -161,11 +193,55 @@ const NumberSetting = () => {
</Table>
</TableContainer>
</Card>
<Card mt={6} px={6} py={4}>
<Flex alignItems={'flex-end'}>
<Box fontSize={'xl'} fontWeight={'bold'}>
</Box>
<Button onClick={onOpenWx} size={'xs'} ml={4} variant={'outline'}>
wx联系
</Button>
</Flex>
<TableContainer maxH={'400px'} overflowY={'auto'}>
<Table>
<Thead>
<Tr>
<Th></Th>
<Th></Th>
<Th></Th>
<Th></Th>
<Th></Th>
</Tr>
</Thead>
<Tbody fontSize={'sm'}>
{payOrders.map((item) => (
<Tr key={item._id}>
<Td>{item.orderId}</Td>
<Td>
{item.createTime ? dayjs(item.createTime).format('YYYY/MM/DD HH:mm:ss') : '-'}
</Td>
<Td whiteSpace="pre-wrap" wordBreak={'break-all'}>
{formatPrice(item.price)}
</Td>
<Td>{item.status}</Td>
<Td>
{item.status === 'NOTPAY' && (
<Button onClick={() => handleRefreshPayOrder(item._id)} size={'sm'}>
</Button>
)}
</Td>
</Tr>
))}
</Tbody>
</Table>
</TableContainer>
</Card>
<Card mt={6} px={6} py={4}>
<Box fontSize={'xl'} fontWeight={'bold'}>
使
使(30)
</Box>
<TableContainer>
<TableContainer maxH={'400px'} overflowY={'auto'}>
<Table>
<Thead>
<Tr>
@@ -177,8 +253,8 @@ const NumberSetting = () => {
<Tbody fontSize={'sm'}>
{bills.map((item) => (
<Tr key={item.id}>
<Td minW={'200px'}>{item.time}</Td>
<Td minW={'200px'} whiteSpace="pre-wrap" wordBreak={'break-all'}>
<Td>{item.time}</Td>
<Td whiteSpace="pre-wrap" wordBreak={'break-all'}>
{item.textLen}
</Td>
<Td>{item.price}</Td>
@@ -189,6 +265,8 @@ const NumberSetting = () => {
</TableContainer>
</Card>
{showPay && <PayModal onClose={() => setShowPay(false)} />}
{/* wx 联系 */}
{isOpenWx && <WxConcat onClose={onCloseWx} />}
</>
);
};

View File

@@ -6,9 +6,9 @@ const PaySchema = new Schema({
ref: 'user',
required: true
},
time: {
type: Number,
default: () => Date.now()
createTime: {
type: Date,
default: () => new Date()
},
price: {
type: Number,
@@ -17,6 +17,12 @@ const PaySchema = new Schema({
orderId: {
type: String,
required: true
},
status: {
// 支付的状态
type: String,
default: 'NOTPAY',
enum: ['SUCCESS', 'REFUND', 'NOTPAY', 'CLOSED']
}
});

View File

@@ -16,7 +16,7 @@ const UserSchema = new Schema({
},
balance: {
type: Number,
default: 0.5
default: 0.5 * 100000
},
accounts: [
{

View File

@@ -85,3 +85,12 @@ export interface BillSchema {
textLen: number;
price: number;
}
export interface PaySchema {
_id: string;
userId: string;
createTime: Date;
price: number;
orderId: string;
status: 'SUCCESS' | 'REFUND' | 'NOTPAY' | 'CLOSED';
}