From c6672b346dbf61e7f0c63fc6c9b8cc4ef4e62fe5 Mon Sep 17 00:00:00 2001 From: Ted Date: Wed, 4 Dec 2024 15:14:56 +0800 Subject: [PATCH] feat: support cache token --- src/hooks/payment.ts | 36 ++++++++++++++++++++++++++++++++++++ src/pages/PaymentPage.tsx | 17 ++++++++++++++++- 2 files changed, 52 insertions(+), 1 deletion(-) create mode 100644 src/hooks/payment.ts diff --git a/src/hooks/payment.ts b/src/hooks/payment.ts new file mode 100644 index 000000000..5f380422a --- /dev/null +++ b/src/hooks/payment.ts @@ -0,0 +1,36 @@ +import axios from 'axios' +import { useEffect, useState } from 'react' + +export const useFetchPayFormToken = (paymentNo?: string, cacheToken?: string | null | undefined) => { + const [result, setResult] = useState(null) + const [loading, setLoading] = useState(false) + const [error, setError] = useState(null) + + useEffect(() => { + if (!paymentNo || !cacheToken) return + + const fetchPayFormToken = async () => { + setLoading(true) + try { + const response = await axios.get( + `${process.env.REACT_APP_API_BASE_ROOT}/payment/${paymentNo}/pay-form-token/${cacheToken}`, + ) + if (response.data.code === 'SUCCESS') { + setResult({ + token: response.data.result.payFormToken.toString(), + }) + } else { + setError(new Error(response.data.message)) + } + } catch (err) { + setError(err as Error) + } finally { + setLoading(false) + } + } + + fetchPayFormToken() + }, [paymentNo, cacheToken]) + + return { result, loading, error } +} diff --git a/src/pages/PaymentPage.tsx b/src/pages/PaymentPage.tsx index 8e9065eba..77e52c4c9 100644 --- a/src/pages/PaymentPage.tsx +++ b/src/pages/PaymentPage.tsx @@ -14,6 +14,8 @@ import AdminCard from '../components/common/AdminCard' import DefaultLayout from '../components/layout/DefaultLayout' import hasura from '../hasura' import { commonMessages } from '../helpers/translation' +import { useFetchPayFormToken } from '../hooks/payment' +import LoadingPage from './LoadingPage' const messages = defineMessages({ bankCodeMessage: { @@ -56,6 +58,7 @@ const PaymentPage: React.VFC = () => { const tracking = useTracking() const { paymentNo } = useParams<{ paymentNo: string }>() const [payToken] = useQueryParam('token', StringParam) + const [cacheToken] = useQueryParam('cacheToken', StringParam) const [method] = useQueryParam('method', StringParam) const { data: payment, loading } = useQuery( gql` @@ -70,7 +73,19 @@ const PaymentPage: React.VFC = () => { ) const [bankCode, setBankCode] = useState('') - const decodedToken = payToken && jwt.decode(payToken) + let decodedToken = payToken && jwt.decode(payToken) + + const { result: payFormResult, loading: payFormLoading } = useFetchPayFormToken(paymentNo, cacheToken || '') + + if (cacheToken) { + if (payFormLoading) { + return + } + + if (payFormResult?.token) { + decodedToken = jwt.decode(payFormResult.token) + } + } if (decodedToken) { const payload = decodedToken as { gateway: string; method: string; payForm: { html?: string; url?: string } }