109 lines
3.3 KiB
TypeScript
109 lines
3.3 KiB
TypeScript
import { useApi } from "@/api";
|
|
import { ResponsePost } from "@/api/resources/Payment";
|
|
import { EPlacementKeys, IPaywallProduct } from "@/api/resources/Paywall";
|
|
import { usePaywall } from "@/hooks/paywall/usePaywall";
|
|
import { selectors } from "@/store";
|
|
import { useEffect, useMemo, useState } from "react"
|
|
import { useSelector } from "react-redux";
|
|
|
|
interface IUsePaymentProps {
|
|
placementKey: EPlacementKeys;
|
|
activeProduct: IPaywallProduct;
|
|
}
|
|
|
|
export const usePayment = ({ placementKey, activeProduct }: IUsePaymentProps) => {
|
|
const api = useApi();
|
|
const token = useSelector(selectors.selectToken);
|
|
const [isSubmitting, setIsSubmitting] = useState(false);
|
|
const [paymentResponse, setPaymentResponse] = useState<ResponsePost>();
|
|
const [error, setError] = useState<string | null>(null);
|
|
const [isPaymentSuccess, setIsPaymentSuccess] = useState(false);
|
|
const formPrice = String((activeProduct?.trialPrice || 99) / 100);
|
|
|
|
const isLoading = useMemo(() => {
|
|
return isSubmitting
|
|
}, [isSubmitting]);
|
|
|
|
const { products, placementId, paywallId } = usePaywall({
|
|
placementKey,
|
|
});
|
|
|
|
useEffect(() => {
|
|
const product = products.find((product) => product._id === activeProduct._id);
|
|
if (!product) {
|
|
setError("Product not found");
|
|
} else {
|
|
setError(null);
|
|
}
|
|
}, [products]);
|
|
|
|
useEffect(() => {
|
|
window.CollectJS.configure({
|
|
variant: 'lightbox',
|
|
// styleSniffer: true,
|
|
callback: (token: any) => {
|
|
finishSubmit(token);
|
|
},
|
|
primaryColor: '#066fde',
|
|
theme: "material",
|
|
fields: {
|
|
ccnumber: {
|
|
placeholder: '1234 1234 1234 1234',
|
|
selector: '#ccnumber'
|
|
},
|
|
ccexp: {
|
|
placeholder: 'MM/YY',
|
|
selector: '#ccexp'
|
|
},
|
|
cvv: {
|
|
placeholder: 'CVC',
|
|
selector: '#cvv'
|
|
}
|
|
},
|
|
price: formPrice,
|
|
// country: "US",
|
|
// currency: "USD",
|
|
});
|
|
}, [placementId, paywallId]);
|
|
|
|
const finishSubmit = async (response: any) => {
|
|
try {
|
|
console.log("response: ", response);
|
|
setIsSubmitting(true);
|
|
const res = await api.makePayment({
|
|
token,
|
|
productId: activeProduct?._id || "",
|
|
placementId,
|
|
paywallId,
|
|
paymentToken: response.token
|
|
});
|
|
setPaymentResponse(res);
|
|
setIsPaymentSuccess(res.status === "paid");
|
|
} catch (error: any) {
|
|
console.error('Payment error:', error);
|
|
setError(error?.message);
|
|
} finally {
|
|
setIsSubmitting(false);
|
|
}
|
|
};
|
|
|
|
const showCreditCardForm = () => {
|
|
window.CollectJS.startPaymentRequest({
|
|
amount: formPrice,
|
|
});
|
|
};
|
|
|
|
return useMemo(() => ({
|
|
isLoading,
|
|
paymentResponse,
|
|
error,
|
|
isPaymentSuccess,
|
|
showCreditCardForm
|
|
}), [
|
|
isLoading,
|
|
paymentResponse,
|
|
error,
|
|
isPaymentSuccess,
|
|
showCreditCardForm
|
|
])
|
|
} |