checkout form

This commit is contained in:
User
2025-02-16 14:55:04 +03:00
parent fa53707210
commit 1e803b4beb

View File

@@ -1,61 +1,91 @@
"use client" "use client"
import type React from "react"
import { useState } from "react" import { useState } from "react"
import { useRouter } from "next/navigation" import { useRouter } from "next/navigation"
import { useCart } from "@/contexts/cart-context" import { useCart } from "@/contexts/cart-context"
import { Button } from "@/components/ui/button" import { Button } from "@/components/ui/button"
import { Label } from "@/components/ui/label" import { Label } from "@/components/ui/label"
import { Textarea } from "@/components/ui/textarea" import { Textarea } from "@/components/ui/textarea"
import { CheckCircle2 } from "lucide-react" import { CheckCircle2, ExternalLink } from "lucide-react"
// Mock function for YooMoney payment // Mock function for generating YooMoney payment link
const processYooMoneyPayment = async (amount: number): Promise<boolean> => { const generateYooMoneyPaymentLink = async (amount: number): Promise<string> => {
// Simulate API call // 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)) await new Promise((resolve) => setTimeout(resolve, 2000))
// Simulate successful payment (in real app, this would be the actual API response) // In a real application, this would check the actual payment status
return true return true
} }
export function CheckoutForm() { export function CheckoutForm() {
const [step, setStep] = useState(1)
const [address, setAddress] = useState("") const [address, setAddress] = useState("")
const [isProcessing, setIsProcessing] = useState(false) const [isProcessing, setIsProcessing] = useState(false)
const [isOrderPlaced, setIsOrderPlaced] = useState(false) const [isOrderPlaced, setIsOrderPlaced] = useState(false)
const [step, setStep] = useState(0)
const [paymentLink, setPaymentLink] = useState("")
const { items, clearCart } = useCart()
const router = useRouter() const router = useRouter()
const { items, clearCart, getTotalItems } = useCart()
// Log the cart items to make sure they are correct const totalPrice = items.reduce((sum, item) => sum + item.price * item.quantity, 0)
console.log("Cart items:", items)
// Define the getTotalPrice function inside the component
const getTotalPrice = () => {
return items.reduce((total, item) => total + item.price * item.quantity, 0).toFixed(2)
}
const handleAddressSubmit = (e: React.FormEvent) => { const handleAddressSubmit = (e: React.FormEvent) => {
e.preventDefault() e.preventDefault()
if (address.trim()) { if (address.trim()) {
setStep(2) setStep(1)
} }
} }
const handlePayment = async () => { const handleInitiatePayment = async () => {
setIsProcessing(true) setIsProcessing(true)
const totalPrice = getTotalPrice() // Calculate total price here try {
console.log("Total Price:", totalPrice) // Log the total price to check const link = await generateYooMoneyPaymentLink(totalPrice)
setPaymentLink(link)
const paymentSuccess = await processYooMoneyPayment(Number(totalPrice)) setStep(2)
} catch (error) {
if (paymentSuccess) { console.error("Error generating payment link:", error)
setIsOrderPlaced(true) alert("Не удалось создать ссылку для оплаты. Пожалуйста, попробуйте еще раз.")
clearCart()
} else {
alert("Оплата не прошла. Пожалуйста, попробуйте еще раз.")
} }
setIsProcessing(false) setIsProcessing(false)
} }
const handlePaymentConfirmation = async () => {
setIsProcessing(true)
try {
const paymentSuccess = await verifyYooMoneyPayment()
if (paymentSuccess) {
clearCart() // Clear the cart after successful payment
setIsOrderPlaced(true)
} else {
alert("Оплата не подтверждена. Пожалуйста, убедитесь, что вы завершили оплату.")
}
} catch (error) {
console.error("Error verifying payment:", error)
alert("Не удалось проверить статус оплаты. Пожалуйста, попробуйте еще раз.")
}
setIsProcessing(false)
}
if (getTotalItems() === 0) {
return (
<div className="text-center py-10">
<p className="text-xl">Ваша корзина пуста. Добавьте товары перед оформлением заказа.</p>
<Button onClick={() => router.push("/")} className="mt-4">
Вернуться к покупкам
</Button>
</div>
)
}
if (isOrderPlaced) { if (isOrderPlaced) {
return ( return (
<div className="text-center py-10"> <div className="text-center py-10">
@@ -68,10 +98,10 @@ export function CheckoutForm() {
} }
return ( return (
<div className="max-w-md mx-auto"> <div className="space-y-8">
{step === 1 && ( {step === 0 && (
<form onSubmit={handleAddressSubmit} className="space-y-4"> <form onSubmit={handleAddressSubmit} className="space-y-4">
<h2 className="text-xl font-bold mb-4">Шаг 1: Адрес доставки</h2> <h2 className="text-xl font-bold mb-4">Адрес доставки</h2>
<div> <div>
<Label htmlFor="address">Адрес</Label> <Label htmlFor="address">Адрес</Label>
<Textarea <Textarea
@@ -82,22 +112,43 @@ export function CheckoutForm() {
required required
/> />
</div> </div>
<Button type="submit">Продолжить</Button> <Button type="submit" className="w-full">
Продолжить
</Button>
</form> </form>
)} )}
{step === 1 && (
<div className="space-y-4">
<h2 className="text-xl font-bold mb-4">Оплата</h2>
<div className="bg-gray-100 p-4 rounded-md">
<h3 className="font-semibold mb-2">Итого к оплате:</h3>
<p className="text-2xl font-bold">{totalPrice} </p>
</div>
<Button onClick={handleInitiatePayment} disabled={isProcessing} className="w-full">
{isProcessing ? "Создание ссылки..." : "Оплатить через ЮMoney"}
</Button>
</div>
)}
{step === 2 && ( {step === 2 && (
<div className="space-y-4"> <div className="space-y-4">
<h2 className="text-xl font-bold mb-4">Шаг 2: Оплата</h2> <h2 className="text-xl font-bold mb-4">Завершение оплаты</h2>
<div className="bg-gray-100 p-4 rounded-md"> <p>Пожалуйста, перейдите по ссылке ниже для оплаты:</p>
<h3 className="font-semibold mb-2">Итого к оплате:</h3> <a
<p className="text-2xl font-bold">{getTotalPrice()} </p> href={paymentLink}
</div> target="_blank"
<Button onClick={handlePayment} disabled={isProcessing} className="w-full"> rel="noopener noreferrer"
{isProcessing ? "Обработка..." : "Оплатить через ЮMoney"} className="text-blue-600 hover:underline flex items-center"
>
Оплатить заказ <ExternalLink className="ml-1 w-4 h-4" />
</a>
<Button onClick={handlePaymentConfirmation} disabled={isProcessing} className="w-full">
{isProcessing ? "Проверка оплаты..." : "Я оплатил"}
</Button> </Button>
</div> </div>
)} )}
</div> </div>
) )
} }