This commit is contained in:
2025-02-24 19:35:16 +03:00
parent ba8763232b
commit 9b16274400

View File

@@ -11,22 +11,6 @@ import { Textarea } from "@/components/ui/textarea"
import { CheckCircle2, ExternalLink } from "lucide-react"
import Cookies from "js-cookie"
// Mock function for generating YooMoney payment link
const generateYooMoneyPaymentLink = async (amount: number): Promise<string> => {
// Simulate API call to generate payment link
await new Promise((resolve) => setTimeout(resolve, 1000))
// In a real application, this would be an actual API call to YooMoney
return `https://yoomoney.ru/checkout/payments/v2/contract?orderId=${Date.now()}&amount=${amount}`
}
// Mock function for verifying YooMoney payment
const verifyYooMoneyPayment = async (): Promise<boolean> => {
// Simulate API call to verify payment
await new Promise((resolve) => setTimeout(resolve, 2000))
// In a real application, this would check the actual payment status
return true
}
const setTotalPriceCookie = (totalPrice: number) => {
Cookies.set("totalPrice", totalPrice.toString(), { expires: 1 }) // Expires in 1 day
}
@@ -37,6 +21,7 @@ export function CheckoutForm() {
const [isOrderPlaced, setIsOrderPlaced] = useState(false)
const [step, setStep] = useState(0)
const [paymentLink, setPaymentLink] = useState("")
const [error, setError] = useState<string | null>(null)
const router = useRouter()
const { items, clearCart, getTotalItems } = useCart()
@@ -52,33 +37,59 @@ export function CheckoutForm() {
const handleInitiatePayment = async () => {
setIsProcessing(true)
setError(null)
try {
setTotalPriceCookie(totalPrice)
const link = await generateYooMoneyPaymentLink(totalPrice)
setPaymentLink(link)
const response = await fetch("http://localhost:8081/api/pay", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
amount: totalPrice,
address: address,
items: items.map((item) => ({
id: item.id,
title: item.title,
price: item.price,
quantity: item.quantity,
})),
}),
})
if (!response.ok) {
throw new Error("Ошибка при создании платежа")
}
const data = await response.json()
if (!data.paymentUrl) {
throw new Error("Не получена ссылка на оплату")
}
setPaymentLink(data.paymentUrl)
setStep(2)
} catch (error) {
console.error("Error generating payment link:", error)
alert("Не удалось создать ссылку для оплаты. Пожалуйста, попробуйте еще раз.")
setError("Не удалось создать ссылку для оплаты. Пожалуйста, попробуйте еще раз.")
} finally {
setIsProcessing(false)
}
setIsProcessing(false)
}
const handlePaymentConfirmation = async () => {
setIsProcessing(true)
setError(null)
try {
const paymentSuccess = await verifyYooMoneyPayment()
if (paymentSuccess) {
clearCart() // Clear the cart after successful payment
setIsOrderPlaced(true)
} else {
alert("Оплата не подтверждена. Пожалуйста, убедитесь, что вы завершили оплату.")
}
// Here you would typically check the payment status with your backend
clearCart()
setIsOrderPlaced(true)
} catch (error) {
console.error("Error verifying payment:", error)
alert("Не удалось проверить статус оплаты. Пожалуйста, попробуйте еще раз.")
setError("Не удалось проверить статус оплаты. Пожалуйста, попробуйте еще раз.")
} finally {
setIsProcessing(false)
}
setIsProcessing(false)
}
if (getTotalItems() === 0) {
@@ -105,6 +116,8 @@ export function CheckoutForm() {
return (
<div className="space-y-8">
{error && <div className="bg-red-50 border border-red-200 text-red-600 px-4 py-3 rounded">{error}</div>}
{step === 0 && (
<form onSubmit={handleAddressSubmit} className="space-y-4">
<h2 className="text-xl font-bold mb-4">Адрес доставки</h2>
@@ -132,7 +145,7 @@ export function CheckoutForm() {
<p className="text-2xl font-bold">{totalPrice} </p>
</div>
<Button onClick={handleInitiatePayment} disabled={isProcessing} className="w-full">
{isProcessing ? "Создание ссылки..." : "Оплатить через ЮMoney"}
{isProcessing ? "Создание ссылки..." : "Перейти к оплате"}
</Button>
</div>
)}