-
Notifications
You must be signed in to change notification settings - Fork 44
/
Payment.js
85 lines (67 loc) · 2.19 KB
/
Payment.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import React, { useEffect, useRef } from "react";
import { useDispatch, useSelector } from "react-redux";
import { useParams, useNavigate } from "react-router-dom";
import AdyenCheckout from "@adyen/adyen-web";
import "@adyen/adyen-web/dist/adyen.css";
import { initiateCheckout } from "../../app/paymentSlice";
import { getRedirectUrl } from "../../util/redirect";
export const PaymentContainer = () => {
const { type } = useParams();
return (
<div id="payment-page">
<div className="container">
<Checkout type={type} />
</div>
</div>
);
}
const Checkout = () => {
const dispatch = useDispatch();
const payment = useSelector(state => state.payment);
const navigate = useNavigate();
const paymentContainer = useRef(null);
const { type } = useParams();
useEffect(() => {
dispatch(initiateCheckout(type));
}, [dispatch, type])
useEffect(() => {
const { error } = payment;
if (error) {
navigate(`/status/error?reason=${error}`, { replace: true });
}
}, [payment, navigate])
useEffect(() => {
const { config, session } = payment;
let ignore = false;
if (!session || !paymentContainer.current) {
// initiateCheckout is not finished yet.
return;
}
const createCheckout = async () => {
const checkout = await AdyenCheckout({
...config,
session,
onPaymentCompleted: (response, _component) =>
navigate(getRedirectUrl(response.resultCode), { replace: true }),
onError: (error, _component) => {
console.error(error);
navigate(`/status/error?reason=${error.message}`, { replace: true });
},
});
// The 'ignore' flag is used to avoid double re-rendering caused by React 18 StrictMode
// More about it here: https://beta.reactjs.org/learn/synchronizing-with-effects#fetching-data
if (paymentContainer.current && !ignore) {
checkout.create(type).mount(paymentContainer.current);
}
}
createCheckout();
return () => {
ignore = true;
}
}, [payment, type, navigate])
return (
<div className="payment-container">
<div ref={paymentContainer} className="payment"></div>
</div>
);
}