Commit 28a4a95f authored by Jiwon Yoon's avatar Jiwon Yoon
Browse files

payment 수정

parent 4ae42d2f
...@@ -2,15 +2,15 @@ import axios from 'axios'; ...@@ -2,15 +2,15 @@ import axios from 'axios';
import React, { useState, useEffect, useRef } from 'react'; import React, { useState, useEffect, useRef } from 'react';
import DaumPostcode from "react-daum-postcode"; import DaumPostcode from "react-daum-postcode";
import { Container, Card, Row, Col, Button, Form, FormGroup } from 'react-bootstrap'; import { Container, Card, Row, Col, Button, Form, FormGroup } from 'react-bootstrap';
import { Redirect } from 'react-router-dom'; import { Redirect, Link } from 'react-router-dom';
import PaymentCard from '../Components/PaymentCard'; import PaymentCard from '../Components/PaymentCard';
import { isAuthenticated } from '../utils/auth'; import { isAuthenticated } from '../utils/auth';
import catchErrors from '../utils/catchErrors'; import catchErrors from '../utils/catchErrors';
function Payment({ match, location }) { function Payment({ match, location }) {
const [cart, setCart] = useState(location.state) const [cart, setCart] = useState([])
const [order, setOrder] = useState({products: location.state}) const [order, setOrder] = useState({ products: location.state })
const [userData, setUserData] = useState({}) const [userData, setUserData] = useState({})
const [error, setError] = useState() const [error, setError] = useState()
const [paymentWay, setPaymentWay] = useState([]) const [paymentWay, setPaymentWay] = useState([])
...@@ -26,27 +26,42 @@ function Payment({ match, location }) { ...@@ -26,27 +26,42 @@ function Payment({ match, location }) {
useEffect(() => { useEffect(() => {
getUser() getUser()
getCart()
}, [user])
useEffect(() => {
let price = 0 let price = 0
cart.map((el) => { cart.map((el) => {
price = Number(el.count) * Number(el.productId.price) + price price = Number(el.count) * Number(el.productId.price) + price
}) })
setFinalPrice(price) setFinalPrice(price)
}, [user]) }, [cart])
async function getUser() { async function getUser() {
try { try {
const response = await axios.get(`/api/users/getuser/${user}`) const response = await axios.get(`/api/users/getuser/${user}`)
console.log(response.data) // console.log(response.data)
setUserData(response.data) setUserData(response.data)
} catch (error) { } catch (error) {
catchErrors(error, setError) catchErrors(error, setError)
} }
} }
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)
} catch (error) {
catchErrors(error, setError)
}
}
function handleReceiverInfo(e) { function handleReceiverInfo(e) {
const { name, value } = e.target const { name, value } = e.target
console.log(name,value) console.log(name, value)
setOrder({ ...order, receiverInfo: {...order.receiverInfo, [name]: value } }) setOrder({ ...order, receiverInfo: { ...order.receiverInfo, [name]: value } })
} }
function postClick() { function postClick() {
...@@ -78,7 +93,7 @@ function Payment({ match, location }) { ...@@ -78,7 +93,7 @@ function Payment({ match, location }) {
fullAddress += extraAddress !== "" ? ` (${extraAddress})` : ""; fullAddress += extraAddress !== "" ? ` (${extraAddress})` : "";
} }
setAddress({ full: fullAddress, code: data.zonecode }); setAddress({ full: fullAddress, code: data.zonecode });
setOrder({ ...order, receiverInfo: {...order.receiverInfo, address: fullAddress, postalCode: data.zonecode } }) setOrder({ ...order, receiverInfo: { ...order.receiverInfo, address: fullAddress, postalCode: data.zonecode } })
console.log(fullAddress); console.log(fullAddress);
} }
...@@ -125,6 +140,12 @@ function Payment({ match, location }) { ...@@ -125,6 +140,12 @@ function Payment({ match, location }) {
} }
async function kakaopay() { 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', { const response = await fetch('/api/kakaopay/test/single', {
method: "POST", method: "POST",
headers: { headers: {
...@@ -133,15 +154,15 @@ function Payment({ match, location }) { ...@@ -133,15 +154,15 @@ function Payment({ match, location }) {
body: JSON.stringify({ body: JSON.stringify({
cid: 'TC0ONETIME', cid: 'TC0ONETIME',
partner_order_id: 'partner_order_id', partner_order_id: 'partner_order_id',
partner_user_id: 'partner_user_id', partner_user_id: user,
item_name: '앙고라 반목 폴라 베이직 모헤어 니트 (T)', item_name: itemNames,
quantity: 1, quantity: cart.length,
total_amount: 22000, total_amount: finalPrice+2500,
vat_amount: 200, vat_amount: 200,
tax_free_amount: 0, tax_free_amount: 0,
approval_url: 'http://localhost:3000/account', approval_url: 'http://localhost:3000/payment',
fail_url: 'http://localhost:3000/shoppingcart', fail_url: 'http://localhost:3000/payment',
cancel_url: 'http://localhost:3000/kakaopay/payment', cancel_url: 'http://localhost:3000/payment',
}) })
}) })
const data = await response.json() const data = await response.json()
...@@ -150,20 +171,21 @@ function Payment({ match, location }) { ...@@ -150,20 +171,21 @@ function Payment({ match, location }) {
// setRedirect(data.redirect_url) // setRedirect(data.redirect_url)
} }
async function paymentCompleted(){ async function paymentCompleted() {
console.log(user) console.log(user)
console.log(order) console.log(order)
console.log(finalPrice) console.log(finalPrice)
try { try {
const response = await axios.post(`/api/order/addorder`, { const response = await axios.post(`/api/order/addorder`, {
userId : user, userId: user,
...order, ...order,
total : finalPrice+2500 total: finalPrice + 2500
}) })
console.log(response.data) console.log(response.data)
} catch (error) { } catch (error) {
catchErrors(error, setError) catchErrors(error, setError)
} }
alert("주문이 완료되었습니다.")
} }
if (redirect) { if (redirect) {
...@@ -265,7 +287,7 @@ function Payment({ match, location }) { ...@@ -265,7 +287,7 @@ function Payment({ match, location }) {
{paymentWay} {paymentWay}
</div> </div>
<div className="text-center"> <div className="text-center">
<Button className="px-5" style={{ background: "#91877F", borderColor: '#91877F' }} onClick={paymentCompleted} block>결제완료</Button> <Button href="/account" className="px-5" style={{ background: "#91877F", borderColor: '#91877F' }} onClick={paymentCompleted} block>결제완료</Button>
</div> </div>
</Container> </Container>
</div> </div>
......
...@@ -75,6 +75,7 @@ function ShoppingCart() { ...@@ -75,6 +75,7 @@ function ShoppingCart() {
async function getCart() { async function getCart() {
try { try {
setError('')
const response = await axios.get(`/api/cart/showcart/${user}`) const response = await axios.get(`/api/cart/showcart/${user}`)
const addChecked = response.data.map((el) => { const addChecked = response.data.map((el) => {
return { ...el, checked: false } return { ...el, checked: false }
...@@ -86,8 +87,22 @@ function ShoppingCart() { ...@@ -86,8 +87,22 @@ function ShoppingCart() {
} }
} }
function putCheckedCart(){
try {
setError('')
const response = axios.post(`/api/cart/changecart`, {
userId:user,
products: cart
})
console.log(response.data)
} catch (error) {
catchErrors(error, setError)
}
}
return ( return (
<div> <div>
{console.log(cart)}
<Container className="justify-content-center"> <Container className="justify-content-center">
<h1 className="my-5 font-weight-bold text-center">장바구니</h1> <h1 className="my-5 font-weight-bold text-center">장바구니</h1>
<div> <div>
...@@ -116,7 +131,7 @@ function ShoppingCart() { ...@@ -116,7 +131,7 @@ function ShoppingCart() {
<Button as={Link} to={{ <Button as={Link} to={{
pathname: `/payment`, pathname: `/payment`,
state: finalCart state: finalCart
}} className="px-5" style={{ background: "#91877F", borderColor: '#91877F' }} block>결제하기</Button> }} className="px-5" style={{ background: "#91877F", borderColor: '#91877F' }} onClick={putCheckedCart} block>결제하기</Button>
</div> </div>
</Container> </Container>
......
import Cart from "../schemas/Cart.js"; import Cart from "../schemas/Cart.js";
const addcart = async (req, res) => { const addCart = async (req, res) => {
const { userId, products} = req.body const { userId, products } = req.body
try { try {
const cart = await Cart.findOne({ userId: userId }) const cart = await Cart.findOne({ userId: userId })
await Cart.updateOne( await Cart.updateOne(
{ _id: cart._id }, { _id: cart._id },
{$push: {products: products}} { $push: { products: products } }
) )
res.status(200).send('카트에 저장되었습니다.') res.status(200).send('카트에 저장되었습니다.')
} catch (error) { } catch (error) {
...@@ -15,7 +15,22 @@ const addcart = async (req, res) => { ...@@ -15,7 +15,22 @@ const addcart = async (req, res) => {
} }
} }
const showcart = async (req, res) => { const changeCart = async (req, res) => {
const { userId, products } = req.body
console.log(products)
try {
const cart = await Cart.findOne({ userId: userId })
await Cart.updateOne(
{ _id: cart._id },
{ $set: { products: products } }
)
res.send("카트에 체크가 활성화되었습니다")
} catch (error) {
res.send("카트 체인지 실패")
}
}
const showCart = async (req, res) => {
try { try {
const cart = await Cart.findOne({ userId: req.id }).populate({ const cart = await Cart.findOne({ userId: req.id }).populate({
path: 'products.productId', path: 'products.productId',
...@@ -28,13 +43,14 @@ const showcart = async (req, res) => { ...@@ -28,13 +43,14 @@ const showcart = async (req, res) => {
} }
} }
const deletecart = async (req, res) => {
const deleteCart = async (req, res) => {
console.log(req.body) console.log(req.body)
const { userId,cartId } = req.body const { userId, cartId } = req.body
try { try {
const cart = await Cart.findOneAndUpdate( const cart = await Cart.findOneAndUpdate(
{ userId: userId }, { userId: userId },
{ $pull: { products: {_id:cartId} } }, { $pull: { products: { _id: cartId } } },
{ new: true } { new: true }
).populate({ ).populate({
path: 'products.productId', path: 'products.productId',
...@@ -63,4 +79,4 @@ const userById = async (req, res, next, id) => { ...@@ -63,4 +79,4 @@ const userById = async (req, res, next, id) => {
} }
export default { addcart, showcart, deletecart, userById } export default { addCart, changeCart, showCart, deleteCart, userById }
\ No newline at end of file \ No newline at end of file
...@@ -5,15 +5,18 @@ import cartCtrl from '../controllers/cart.controller.js'; ...@@ -5,15 +5,18 @@ import cartCtrl from '../controllers/cart.controller.js';
const router = express.Router() const router = express.Router()
router.route('/addcart') router.route('/addcart')
.put(cartCtrl.addcart) .put(cartCtrl.addCart)
// .get() // .get()
router.route('/showcart/:userId') router.route('/showcart/:userId')
.get(cartCtrl.showcart) .get(cartCtrl.showCart)
router.param('userId', cartCtrl.userById)
router.route('/changecart')
.post(cartCtrl.changeCart)
router.route('/deletecart') router.route('/deletecart')
.post(cartCtrl.deletecart) .post(cartCtrl.deleteCart)
router.param('userId', cartCtrl.userById)
export default router export default router
\ No newline at end of file
...@@ -22,6 +22,9 @@ const CartSchema = new mongoose.Schema({ ...@@ -22,6 +22,9 @@ const CartSchema = new mongoose.Schema({
}, },
color: { color: {
type: String type: String
},
checked: {
type: Boolean
} }
} }
] ]
......
...@@ -24,22 +24,25 @@ const OrderSchema = new mongoose.Schema({ ...@@ -24,22 +24,25 @@ const OrderSchema = new mongoose.Schema({
color: { color: {
type: String, type: String,
required: true required: true
},
checked: {
type: Boolean
} }
} }
], ],
receiverInfo: receiverInfo:
{ {
name: { name: {
type:String, type: String,
required:true required: true
}, },
tel: { tel: {
type: String, type: String,
required:true required: true
}, },
postalCode:{ postalCode: {
type:String, type: String,
required:true required: true
}, },
address: { address: {
type: String, type: String,
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment