Skip to content

Commit

Permalink
feat checkout wechat
Browse files Browse the repository at this point in the history
Signed-off-by: jingyang <3161362058@qq.com>
  • Loading branch information
zjy365 committed Oct 30, 2023
1 parent 290f36f commit be8ab21
Show file tree
Hide file tree
Showing 10 changed files with 193 additions and 104 deletions.
11 changes: 9 additions & 2 deletions service/license/src/api/payment.ts
@@ -1,10 +1,17 @@
import { GET, POST } from '@/services/request';
import { PaymentData, PaymentParams, PaymentResult, PaymentResultParams } from '@/types';
import {
CheckWeChatType,
PaymentData,
PaymentParams,
PaymentResult,
PaymentResultParams
} from '@/types';

export const createPayment = (payload: PaymentParams) =>
POST<PaymentData>('/api/payment/create', payload);

export const handlePaymentResult = (payload: PaymentResultParams) =>
POST<PaymentResult>('/api/payment/result', payload);

export const checkWechatPay = () => GET<PaymentResult>('/api/payment/checkWechat');
export const checkWechatPay = (type: CheckWeChatType) =>
GET<PaymentResult>('/api/payment/checkWechat', { type });
2 changes: 1 addition & 1 deletion service/license/src/components/Pagination/index.tsx
Expand Up @@ -3,7 +3,7 @@ import { useState } from 'react';
type PaginationProps = {
totalItems: number;
itemsPerPage: number;
onPageChange: any;
onPageChange: (page: number) => void;
};

export default function Pagination({ totalItems, itemsPerPage, onPageChange }: PaginationProps) {
Expand Down
53 changes: 45 additions & 8 deletions service/license/src/pages/api/payment/checkWechat.ts
@@ -1,12 +1,21 @@
import { authSession } from '@/services/backend/auth';
import { findRecentNopayOrder, updatePaymentStatus } from '@/services/backend/db/payment';
import { createClusterAndLicense } from '@/services/backend/db/cluster';
import { generateLicenseToken } from '@/services/backend/db/license';
import { findRecentNopayOrder, updatePaymentAndIssueLicense } from '@/services/backend/db/payment';
import { jsonRes } from '@/services/backend/response';
import { getSealosPay } from '@/services/pay';
import { PaymentResult, PaymentStatus } from '@/types';
import {
CheckWeChatType,
ClusterType,
LicenseRecordPayload,
PaymentResult,
PaymentStatus
} from '@/types';
import type { NextApiRequest, NextApiResponse } from 'next';

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
try {
const { type } = req.query as { type: CheckWeChatType };
const userInfo = await authSession(req.headers);
if (!userInfo) {
return jsonRes(res, { code: 401, message: 'token verify error' });
Expand Down Expand Up @@ -40,14 +49,42 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
})
}).then((res) => res.json());

const updateStatusResult = await updatePaymentStatus({
orderID: payment?.orderID,
status: result.status,
uid: userInfo.uid
});
if (type === 'license' && result.status === PaymentStatus.PaymentSuccess) {
await updatePaymentAndIssueLicense({
uid: userInfo.uid,
status: result.status,
amount: payment.amount,
quota: payment.amount,
orderID: payment.orderID,
payMethod: payment.payMethod,
type: 'Account'
});
}

if (type === 'cluster' && result.status === PaymentStatus.PaymentSuccess) {
const _token = generateLicenseToken({ type: 'Account', data: { amount: payment.amount } });
const record: LicenseRecordPayload = {
uid: userInfo.uid,
amount: payment.amount,
token: _token,
orderID: payment.orderID,
quota: payment.amount,
payMethod: payment.payMethod,
type: 'Account'
};
await createClusterAndLicense({
licensePayload: record,
clusterPayload: {
uid: userInfo.uid,
orderID: payment.orderID,
type: ClusterType.Enterprise
}
});
}

console.log('Handle wechat shutdown situation');
return jsonRes(res, {
data: updateStatusResult
data: result
});
} catch (error) {
console.error(error, '===payment error===\n');
Expand Down
8 changes: 7 additions & 1 deletion service/license/src/pages/cluster/components/Record.tsx
Expand Up @@ -104,7 +104,13 @@ export default function ClusterRecord({ changeClusterId, clusterId }: TClusterRe
</Flex>
)}
<Flex ml="auto" mt={'auto'} pr="20px">
<Pagination totalItems={data?.total || 0} itemsPerPage={pageSize} onPageChange={() => {}} />
<Pagination
totalItems={data?.total || 0}
itemsPerPage={pageSize}
onPageChange={(page) => {
setPage(page);
}}
/>
</Flex>
</Flex>
);
Expand Down
38 changes: 21 additions & 17 deletions service/license/src/pages/license/components/Recharge.tsx
Expand Up @@ -43,7 +43,7 @@ export default function RechargeComponent() {
const [wechatPaymentData, setWechatPaymentData] = useState<WechatPaymentData>();
const { data: platformEnv } = useQuery(['getPlatformEnv'], getSystemEnv);
// 用于避免微信支付,窗口关闭后感知不到的问题
// const { paymentData, setPaymentData, deletePaymentData } = usePaymentDataStore();
const { paymentData, setPaymentData, deletePaymentData, isExpired } = usePaymentDataStore();

const onClosePayment = useCallback(() => {
setOrderID('');
Expand Down Expand Up @@ -94,6 +94,7 @@ export default function RechargeComponent() {
setOrderID(data.orderID);
setWechatPaymentData({ tradeNO: data?.tradeNO, codeURL: data?.codeURL });
setComplete(2);
setPaymentData(data.orderID);
}
},
onError(err: any) {
Expand Down Expand Up @@ -121,6 +122,7 @@ export default function RechargeComponent() {
position: 'top'
});
queryClient.invalidateQueries(['getLicenseActive']);
deletePaymentData();
},
onError(err: any) {
toast({
Expand Down Expand Up @@ -156,22 +158,24 @@ export default function RechargeComponent() {
}
});

// checkWechatPay
// useQuery(['checkWechatPay'], () => checkWechatPay(), {
// enabled: !!paymentData?.orderId,
// onSuccess(data) {
// console.log(data, '------');
// if (data.status === PaymentStatus.PaymentSuccess) {
// toast({
// status: 'success',
// title: t('Payment Successful'), // 这里改为license 签发成功
// isClosable: true,
// duration: 9000,
// position: 'top'
// });
// }
// }
// });
// checkWechatPay;
useQuery(['checkWechatPay'], () => checkWechatPay('license'), {
enabled: !isExpired() && !!paymentData?.orderId,
onSuccess(data) {
console.log(data, 'Handle wechat shutdown situation');
if (data.status === PaymentStatus.PaymentSuccess) {
toast({
status: 'success',
title: t('Payment Successful'), // 这里改为license 签发成功
isClosable: true,
duration: 9000,
position: 'top'
});
queryClient.invalidateQueries(['getLicenseActive']);
deletePaymentData();
}
}
});

useEffect(() => {
const { stripeState, orderID } = router.query;
Expand Down
6 changes: 5 additions & 1 deletion service/license/src/pages/license/components/Record.tsx
Expand Up @@ -98,7 +98,11 @@ export default function History() {
</Flex>
)}
<Flex ml="auto" mt={'auto'} pr="20px">
<Pagination totalItems={data?.total || 0} itemsPerPage={pageSize} onPageChange={() => {}} />
<Pagination
totalItems={data?.total || 0}
itemsPerPage={pageSize}
onPageChange={(page) => setPage(page)}
/>
</Flex>
</Flex>
);
Expand Down
40 changes: 25 additions & 15 deletions service/license/src/pages/pricing/components/Product.tsx
Expand Up @@ -30,6 +30,7 @@ import { useCallback, useEffect, useState } from 'react';
import ServicePackage from './ServicePackage';
import useRouteParamsStore from '@/stores/routeParams';
import useSessionStore from '@/stores/session';
import usePaymentDataStore from '@/stores/payment';

export default function Product() {
const { t } = useTranslation();
Expand All @@ -48,6 +49,7 @@ export default function Product() {
const [remainingSeconds, setRemainingSeconds] = useState(2); // 初始值为2秒
const { data: routeParams, setRouteParams, clearRouteParams } = useRouteParamsStore();
const { isUserLogin } = useSessionStore();
const { paymentData, setPaymentData, deletePaymentData, isExpired } = usePaymentDataStore();

const onClosePayment = useCallback(() => {
setOrderID('');
Expand All @@ -58,7 +60,7 @@ export default function Product() {
const openPayModal = () => {
setComplete(1);
setPayType('wechat');
paymentMutation.mutate((599 * 100).toString());
paymentMutation.mutate((1 * 100).toString());
onOpen();
};

Expand Down Expand Up @@ -105,6 +107,7 @@ export default function Product() {
setOrderID(data.orderID);
setWechatData({ tradeNO: data?.tradeNO, codeURL: data?.codeURL });
setComplete(2);
setPaymentData(data.orderID);
}
},
onError(err: any) {
Expand All @@ -126,7 +129,7 @@ export default function Product() {
console.log(data, 'clusterMutation');
setComplete(3);
queryClient.invalidateQueries(['getClusterRecord']);
// onClosePayment();
deletePaymentData();
},
onError(err: any) {
toast({
Expand All @@ -148,6 +151,7 @@ export default function Product() {
console.log(data, 'clusterAndLicenseMutation');
setComplete(3);
queryClient.invalidateQueries(['getClusterRecord']);
deletePaymentData();
},
onError(err: any) {
toast({
Expand Down Expand Up @@ -184,19 +188,24 @@ export default function Product() {
});

// checkWechatPay
// useQuery(['checkWechatPay'], () => checkWechatPay(), {
// onSuccess(data) {
// if (data.status === PaymentStatus.PaymentSuccess) {
// toast({
// status: 'success',
// title: t('License issued successfully'), // 这里改为license 签发成功
// isClosable: true,
// duration: 9000,
// position: 'top'
// });
// }
// }
// });
useQuery(['checkWechatPay'], () => checkWechatPay('cluster'), {
enabled: !isExpired() && !!paymentData?.orderId,
onSuccess(data) {
console.log(data, 'Handle wechat shutdown situation');
if (data.status === PaymentStatus.PaymentSuccess) {
toast({
status: 'success',
title: t('Payment Successful'), // 这里改为license 签发成功
isClosable: true,
duration: 9000,
position: 'top'
});
deletePaymentData();
queryClient.invalidateQueries(['getClusterRecord']);
setComplete(3);
}
}
});

// handle stripe
useEffect(() => {
Expand Down Expand Up @@ -273,6 +282,7 @@ export default function Product() {
<Box flex={1} overflow={'scroll'} backgroundColor="#f2f5f7">
<Flex
minW={'1280px'}
// flexWrap={'wrap'}
h="100%"
pt="30px"
pb="15px"
Expand Down

0 comments on commit be8ab21

Please sign in to comment.