import React, { useState, useEffect, useRef } from 'react';
import { Redirect, Link, useHistory } from 'react-router-dom';
import DaumPostcode from "react-daum-postcode";
import ListCard from '../Components/ListCard';
import axios from 'axios';
import { isAuthenticated } from '../utils/auth';
import catchErrors from '../utils/catchErrors';
import { Container, Row, Col, Button, Form } from 'react-bootstrap';
function Payment({ match, location }) {
const [cart, setCart] = useState([])
const [order, setOrder] = useState({ products: [] })
const [userData, setUserData] = useState({})
const [error, setError] = useState()
const [post, setPost] = useState([])
const [redirect, setRedirect] = useState(null)
const [address, setAddress] = useState("")
const [finalPrice, setFinalPrice] = useState(0)
const [paymentWay, setPaymentWay] = useState([])
const [completeState, setCompleteState] = useState(false)
const user = isAuthenticated()
let history = useHistory();
const preCart = []
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, email: email })
}
async function getCart() {
try {
setError('')
const response = await axios.get(`/api/cart/showcart/${user}`)
const preCart = response.data.filter((el) => el.checked === true)
if (preCart.length) {
setCart(preCart)
setOrder({ products: preCart })
} else {
alert("주문하실 상품이 없습니다.")
history.push("/home")
}
} catch (error) {
catchErrors(error, setError)
}
}
async function deleteOrder(e) {
try {
setError('')
const response = await axios.post('/api/cart/deletecart', {
userId: user,
cartId: e.target.name
})
const preCart = response.data.products.filter((el) => el.checked === true)
setCart(preCart)
setOrder({ products: preCart })
} catch (error) {
catchErrors(error, setError)
}
}
function handleReceiverInfo(e) {
const { name, value } = e.target
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 = "";
if (data.addressType === "R") {
if (data.bname !== "") {
extraAddress += data.bname;
}
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) {
setCompleteState(false)
setPaymentWay([])
} else {
const bankList = (
입금은행
입금자
입금예정일
)
setPaymentWay(bankList)
}
}
async function kakaopay() {
setCompleteState("kakaopay")
setPaymentWay(
'카카오페이'
를 선택하셨습니다.
주문하기를 눌러 결제를 이어가주세요.
)
// 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 {
setError('')
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
})
if (completeState === "kakaopay") {
let itemNames = ""
if (cart.length > 1) {
itemNames = cart[0].productId.pro_name + ' 외 ' + String(cart.length - 1) + '개'
} else {
itemNames = cart[0].productId.pro_name
}
setError('')
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/paymentcompleted',
fail_url: 'http://localhost:3000/shoppingcart',
cancel_url: 'http://localhost:3000/shoppingcart',
})
})
const data = await response.json()
window.location.href = data.redirect_url
} else {
console.log(response.data)
console.log(response2.data)
console.log(response3.data)
alert("주문이 완료되었습니다.")
history.push('/paymentcompleted')
}
} catch (error) {
catchErrors(error, setError)
alert("주문에 실패하셨습니다. 다시 확인해주세요.")
}
}
return (
주문/결제
주문자 정보
이름
휴대전화
이메일
받는사람 정보
이름
휴대전화
주소
{post}
상세 주소를 입력하세요.
주문상품정보
-
총 상품금액
{finalPrice}원
-
배송비
2500원
결제금액{finalPrice + 2500}원
결제수단
{paymentWay}
)
}
export default Payment