import MainButton from "@/components/MainButton"; import Title from "@/components/Title"; import routes from "@/routes"; import { actions } from "@/store"; import { PaymentElement, useElements, useStripe, } from "@stripe/react-stripe-js"; import { useState } from "react"; import { useDispatch } from "react-redux"; import { useNavigate } from "react-router-dom"; import styles from "./styles.module.css"; export type TConfirmType = "payment" | "setup"; interface ICheckoutFormProps { children?: JSX.Element | null; subscriptionReceiptId?: string; returnUrl?: string; confirmType?: TConfirmType; isHide?: boolean; } export default function CheckoutForm({ children, subscriptionReceiptId, returnUrl, confirmType = "payment", isHide = false, }: ICheckoutFormProps) { const stripe = useStripe(); const elements = useElements(); const dispatch = useDispatch(); const navigate = useNavigate(); const [message, setMessage] = useState(""); const [isProcessing, setIsProcessing] = useState(false); const [formReady, setFormReady] = useState(false); const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); if (!stripe || !elements) { return; } setIsProcessing(true); try { const { error } = await stripe[ confirmType === "payment" ? "confirmPayment" : "confirmSetup" ]({ elements, confirmParams: { return_url: returnUrl ? returnUrl : `https://${window.location.host}/payment/result/${subscriptionReceiptId}/`, }, }); if (error) { setMessage(error?.message || "Oops! Something went wrong."); } else { dispatch(actions.status.update("subscribed")); navigate(routes.client.paymentSuccess()); } } catch (error) { console.log("error -> ", error); setMessage("Oops! Something went wrong."); } finally { setIsProcessing(false); } }; return (
{children ? children : null} setFormReady(true)} /> Secure {isProcessing ? "Processing..." : "Start"} {!!message.length && ( {message} )} ); }