| 1 |
import { |
| 2 |
useCallback, |
| 3 |
useEffect, |
| 4 |
useMemo, |
| 5 |
useRef, |
| 6 |
useState, |
| 7 |
} from '@wordpress/element' |
| 8 |
import apiFetch from '@wordpress/api-fetch' |
| 9 |
import PaymentRedirect from '../components/PaymentRedirectPage/PaymentRedirect' |
| 10 |
import PaymentCancelled |
| 11 |
from '../components/PaymentRedirectPage/PaymentCancelled' |
| 12 |
import PaymentError from '../components/PaymentRedirectPage/PaymentError' |
| 13 |
|
| 14 |
export default function PaymentRedirectPage () { |
| 15 |
const { logo, continueShoppingUrl } = window.VippsMobilePaySettings |
| 16 |
const searchParams = new URLSearchParams(window.location.search) |
| 17 |
|
| 18 |
const [response, setResponse] = useState(null) |
| 19 |
const [error, setError] = useState(false) |
| 20 |
const [errorCounter, setErrorCounter] = useState(0) |
| 21 |
const intervalHandlerRef = useRef(null) |
| 22 |
|
| 23 |
const checkStatus = useCallback(() => { |
| 24 |
apiFetch({ |
| 25 |
path: `/vipps-mobilepay-recurring/v1/orders/status/${searchParams.get( |
| 26 |
'order_id')}?key=${searchParams.get('key')}`, method: 'GET', |
| 27 |
}).then(response => { |
| 28 |
setResponse(response) |
| 29 |
setErrorCounter(0) |
| 30 |
}).catch(() => { |
| 31 |
setErrorCounter((value) => value + 1) |
| 32 |
}) |
| 33 |
}, []) |
| 34 |
|
| 35 |
useEffect(() => { |
| 36 |
checkStatus(); |
| 37 |
intervalHandlerRef.current = setInterval(checkStatus, 10_000) |
| 38 |
|
| 39 |
return () => clearInterval(intervalHandlerRef.current) |
| 40 |
}, []) |
| 41 |
|
| 42 |
useEffect(() => { |
| 43 |
setError(errorCounter >= 4) |
| 44 |
}, [errorCounter]) |
| 45 |
|
| 46 |
useEffect(() => { |
| 47 |
if (error) { |
| 48 |
clearInterval(intervalHandlerRef.current) |
| 49 |
|
| 50 |
return |
| 51 |
} |
| 52 |
|
| 53 |
if (!response || response.status === 'PENDING' || cancelled) { |
| 54 |
return |
| 55 |
} |
| 56 |
|
| 57 |
clearInterval(intervalHandlerRef.current) |
| 58 |
|
| 59 |
if (response.redirect_url) { |
| 60 |
window.location.href = response.redirect_url |
| 61 |
} |
| 62 |
}, [response, error]) |
| 63 |
|
| 64 |
const cancelled = useMemo(() => { |
| 65 |
if (!response) { |
| 66 |
return false |
| 67 |
} |
| 68 |
|
| 69 |
return ['EXPIRED', 'STOPPED'].includes(response.status) |
| 70 |
}, [response]) |
| 71 |
|
| 72 |
return <> |
| 73 |
{!error && <> |
| 74 |
{!cancelled |
| 75 |
? <PaymentRedirect logo={logo}/> |
| 76 |
: <PaymentCancelled logo={logo} |
| 77 |
continueShoppingUrl={continueShoppingUrl}/>} |
| 78 |
</>} |
| 79 |
|
| 80 |
{error && <PaymentError logo={logo} |
| 81 |
continueShoppingUrl={continueShoppingUrl}/>} |
| 82 |
</> |
| 83 |
} |
| 84 |
|