Credit Card Modal
CreditCardModal Component Documentation
Overview
The CreditCardModal
is a comprehensive component designed for securely handling credit card transactions within the application. It’s specifically tailored to interact with First Atlantic Commerce’s API to facilitate 3D Secure transactions, ensuring an added layer of security.
Key Functionalities
-
Initiating Payment: When users submit their credit card details, the component triggers the
checkoutPayment
function. This is the heart of the payment initiation process, where card data, billing details, and the amount are sent to the backend. Here’s a snippet illustrating this interaction:const handleSubmit = async () => {let cardErrors = validateCardDetails(cardData);if (cardErrors.length > 0) {// Display errors...return;}setIsLoading(true);const response = await checkoutPayment(cardData,billingDetails,amount,user._id);// Further actions based on response...};This function communicates with the backend and expects to receive
redirectData
andbillingId
, as a response, crucial for the transaction’s next steps.if (response.RedirectData) {setIframeContent(response.RedirectData);setBillingId(response.billingDetailsId);} -
Handling Redirects with an Iframe: Upon receiving
redirectData
, the component renders an iframe where this data is used to perform a secure redirect. This step is crucial, especially for transactions requiring additional authentication steps by the user’s bank (known as the challenge flow). The iframe serves as a secure environment for these interactions, separating them from the main application context.<><div className="c-modal-header"><h5>Processing</h5><button onClick={onClose} className="close-button">×</button></div><iframetitle="pt"srcDoc={iframeContent}style={{ width: "100%", height: "300px", border: "none" }}></iframe><SmallLoadingSpinner /></> -
Listening for Payment Status: A
useEffect
hook is employed to listen for messages from the iframe, signifying the transaction’s outcome. The message includes details about the transaction’s success or failure and, most importantly, a transaction ID when successful. The component then proceeds to update the payment’s status accordingly. Here’s how the message handling is set up:useEffect(() => {const extractTransactionId = (eventData) => {const regex = /TransactionID- (\S+)/;const match = eventData.match(regex);const transactionId = match ? match[1] : "unknown";return transactionId;};const handleMessage = async (event) => {if (event.origin === "http://localhost:5500") {// Ensure the message is from a trusted source and check its contentif (event.data.includes("Payment Complete")) {const transactionId = extractTransactionId(event.data);try {const paymentObj = await updatePaymentAfterCheckout(user._id,user.token,paymentId,transactionId,billingId);if (paymentObj.message === "Payment updated") {successfulToast(`Payment Complete. Transaction ID: ${transactionId}`);navigate(`/invoice/${paymentObj.data._id}`);} else {errorToast(paymentObj.message || "Something went wrong");}} catch (error) {errorToast(error.message);}} else if (event.data.includes("Payment Failed")) {const transactionId = extractTransactionId(event.data);errorToast(`Payment Failed. Transaction ID: ${transactionId}`);}setIsLoading(false);}};window.addEventListener("message", handleMessage);return () => {window.removeEventListener("message", handleMessage);};}, [navigate, paymentId, user._id, user.token, billingId]);
User Interaction
Users interact with a form to input their card details. Before submission, the data goes through a series of validations:
- Card Number: Ensured to be 16 digits and numeric.
- Expiry Date: Checked for the correct format (YYMM) and future validity.
- CVV: Verified to be 3 digits and numeric.
Here’s a sample validation function for the expiry date:
const validateExpiryDate = (date) => { // Ensure date format is YYMM and exactly 4 digits if (!/^\d{4}$/.test(date)) { return false; } // Further validation logic... return month >= 1 && month <= 12;};
Improvements
While the CreditCardModal
is functional and secure, the following improvements can enhance its performance and user experience:
- Enhanced Error Handling: Providing more detailed and user-friendly error messages, possibly derived directly from the payment gateway’s responses, would guide users more effectively through resolving issues.
- Improved Loading UI: Instead of a simple spinner, a more descriptive loading indicator could inform users of the current process stage, especially during the critical payment phase.
- Secure Input Enhancements: For increased security, consider implementing more robust input fields specifically designed for sensitive information like credit card numbers and CVVs.
- User Experience Enhancements: Implementing a smoother transition and feedback mechanism for the challenge flow presented in the iframe can significantly enhance user trust and comprehension of the payment process.
Conclusion
CreditCardModal
stands as a critical component in the application’s payment handling process. Its interaction with the First Atlantic Commerce’s API, combined with the secure handling of credit card information and user-friendly design, makes it an essential feature for any online transaction scenario. With continued improvements and updates, it will remain a robust and reliable solution for secure online transactions.