import axios from 'axios';
import React, { useState, useEffect, useRef } from 'react';
import DaumPostcode from "react-daum-postcode";
import { Container, Card, Row, Col, Button, Form, FormGroup } from 'react-bootstrap';
import { Redirect, Link } from 'react-router-dom';
import PaymentCard from '../Components/PaymentCard';
import { isAuthenticated } from '../utils/auth';
import catchErrors from '../utils/catchErrors';
function Payment({ match, location }) {
const [cart, setCart] = useState([])
const [order, setOrder] = useState({ products: [] })
const [userData, setUserData] = useState({})
const [error, setError] = useState()
const [paymentWay, setPaymentWay] = useState([])
// const [isAddress, setIsAddress] = useState("");
// const [isZoneCode, setIsZoneCode] = useState();
// const [isPostOpen, setIsPostOpen] = useState();
const [post, setPost] = useState([])
const [redirect, setRedirect] = useState(null)
const [address, setAddress] = useState("")
const [finalPrice, setFinalPrice] = useState(0)
const [num, setNum] = useState(0)
const user = isAuthenticated()
useEffect(() => {
getUser()
getCart()
}, [user])
useEffect(() => {
let price = 0
cart.map((el) => {
price = Number(el.count) * Number(el.productId.price) + price
})
setFinalPrice(price)
}, [cart])
async function getUser() {
const name = localStorage.getItem('name')
const tel = localStorage.getItem('tel')
// const email = localStorage.getItem('email')
setUserData({ name: name, tel: tel })
}
async function getCart() {
try {
const response = await axios.get(`/api/cart/showcart/${user}`)
console.log(response.data)
const preCart = response.data.filter((el) => el.checked === true)
setCart(preCart)
setOrder({ products: preCart })
} catch (error) {
catchErrors(error, setError)
}
}
function handleReceiverInfo(e) {
const { name, value } = e.target
console.log(name, value)
setOrder({ ...order, receiverInfo: { ...order.receiverInfo, [name]: value } })
}
function postClick() {
if (post.length !== 0) {
setPost([])
}
else {
setPost(
)
}
}
const handleComplete = (data) => {
let fullAddress = data.address;
let extraAddress = "";
console.log(data)
if (data.addressType === "R") {
if (data.bname !== "") {
extraAddress += data.bname;
console.log(extraAddress)
}
if (data.buildingName !== "") {
extraAddress +=
extraAddress !== "" ? `, ${data.buildingName}` : data.buildingName;
}
fullAddress += extraAddress !== "" ? ` (${extraAddress})` : "";
}
setAddress({ full: fullAddress, code: data.zonecode });
setOrder({ ...order, receiverInfo: { ...order.receiverInfo, address: fullAddress, postalCode: data.zonecode } })
console.log(fullAddress);
}
const postCodeStyle = {
// display: "block",
position: "absolute",
width: "400px",
height: "500px",
padding: "7px",
zIndex: "1000"
};
function handleClick() {
if (paymentWay.length !== 0) {
setPaymentWay([])
}
else {
const a = (
입금은행
입금자
입금예정일
)
setPaymentWay(a)
}
}
async function kakaopay() {
let itemNames = ""
if (cart.length > 1) {
itemNames = cart[0].productId.pro_name + ' 외 ' + String(cart.length - 1) + '개'
} else {
itemNames = cart[0].productId.pro_name
}
const response = await fetch('/api/kakaopay/test/single', {
method: "POST",
headers: {
'Content-type': 'application/json'
},
body: JSON.stringify({
cid: 'TC0ONETIME',
partner_order_id: 'partner_order_id',
partner_user_id: user,
item_name: itemNames,
quantity: cart.length,
total_amount: finalPrice + 2500,
vat_amount: 200,
tax_free_amount: 0,
approval_url: 'http://localhost:3000/payment',
fail_url: 'http://localhost:3000/payment',
cancel_url: 'http://localhost:3000/payment',
})
})
const data = await response.json()
console.log(data)
window.location.href = data.redirect_url
// setRedirect(data.redirect_url)
}
async function paymentCompleted() {
console.log(order)
const cartIds = []
order.products.map((el) => {
cartIds.push(el._id)
})
try {
const response = await axios.post(`/api/order/addorder`, {
userId: user,
...order,
total: finalPrice + 2500
})
const response2 = await axios.post(`/api/cart/deletecart2`, {
userId: user,
cartId: cartIds
})
const response3 = await axios.post(`/api/product/pluspurchase`, {
products: order.products
})
console.log(response.data)
alert("주문이 완료되었습니다.")
return
} catch (error) {
catchErrors(error, setError)
alert("주문에 실패하셨습니다. 다시 확인해주세요.")
}
}
if (redirect) {
console.log(redirect)
return
}
return (
{/* {console.log(order)} */}
주문/결제
주문자 정보
이름
휴대전화
이메일
받는사람 정보
이름
휴대전화
주소
{post}
상세 주소를 입력하세요.
-
총 상품금액
{finalPrice}원
-
배송비
2500원
결제금액{finalPrice + 2500}원
)
}
export default Payment