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

payment 수정

parent 4ae42d2f
......@@ -2,15 +2,15 @@ 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 } from 'react-router-dom';
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(location.state)
const [order, setOrder] = useState({products: location.state})
const [cart, setCart] = useState([])
const [order, setOrder] = useState({ products: location.state })
const [userData, setUserData] = useState({})
const [error, setError] = useState()
const [paymentWay, setPaymentWay] = useState([])
......@@ -26,27 +26,42 @@ function Payment({ match, location }) {
useEffect(() => {
getUser()
getCart()
}, [user])
useEffect(() => {
let price = 0
cart.map((el) => {
price = Number(el.count) * Number(el.productId.price) + price
})
setFinalPrice(price)
}, [user])
}, [cart])
async function getUser() {
try {
const response = await axios.get(`/api/users/getuser/${user}`)
console.log(response.data)
// console.log(response.data)
setUserData(response.data)
} catch (error) {
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) {
const { name, value } = e.target
console.log(name,value)
setOrder({ ...order, receiverInfo: {...order.receiverInfo, [name]: value } })
console.log(name, value)
setOrder({ ...order, receiverInfo: { ...order.receiverInfo, [name]: value } })
}
function postClick() {
......@@ -78,7 +93,7 @@ function Payment({ match, location }) {
fullAddress += extraAddress !== "" ? ` (${extraAddress})` : "";
}
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);
}
......@@ -125,45 +140,52 @@ function Payment({ match, location }) {
}
async function kakaopay() {
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: 'partner_user_id',
item_name: '앙고라 반목 폴라 베이직 모헤어 니트 (T)',
quantity: 1,
total_amount: 22000,
vat_amount: 200,
tax_free_amount: 0,
approval_url: 'http://localhost:3000/account',
fail_url: 'http://localhost:3000/shoppingcart',
cancel_url: 'http://localhost:3000/kakaopay/payment',
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(){
async function paymentCompleted() {
console.log(user)
console.log(order)
console.log(finalPrice)
try {
const response = await axios.post(`/api/order/addorder`, {
userId : user,
userId: user,
...order,
total : finalPrice+2500
total: finalPrice + 2500
})
console.log(response.data)
} catch (error) {
catchErrors(error, setError)
}
alert("주문이 완료되었습니다.")
}
if (redirect) {
......@@ -265,7 +287,7 @@ function Payment({ match, location }) {
{paymentWay}
</div>
<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>
</Container>
</div>
......
......@@ -75,6 +75,7 @@ function ShoppingCart() {
async function getCart() {
try {
setError('')
const response = await axios.get(`/api/cart/showcart/${user}`)
const addChecked = response.data.map((el) => {
return { ...el, checked: false }
......@@ -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 (
<div>
{console.log(cart)}
<Container className="justify-content-center">
<h1 className="my-5 font-weight-bold text-center">장바구니</h1>
<div>
......@@ -116,7 +131,7 @@ function ShoppingCart() {
<Button as={Link} to={{
pathname: `/payment`,
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>
</Container>
......
import Cart from "../schemas/Cart.js";
const addcart = async (req, res) => {
const { userId, products} = req.body
const addCart = async (req, res) => {
const { userId, products } = req.body
try {
const cart = await Cart.findOne({ userId: userId })
await Cart.updateOne(
{ _id: cart._id },
{$push: {products: products}}
{ $push: { products: products } }
)
res.status(200).send('카트에 저장되었습니다.')
} catch (error) {
......@@ -15,11 +15,26 @@ 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 {
const cart = await Cart.findOne({ userId: req.id }).populate({
path: 'products.productId',
model: 'Product'
model: 'Product'
})
res.status(200).json(cart.products)
} catch (error) {
......@@ -28,18 +43,19 @@ const showcart = async (req, res) => {
}
}
const deletecart = async (req, res) => {
const deleteCart = async (req, res) => {
console.log(req.body)
const { userId,cartId } = req.body
const { userId, cartId } = req.body
try {
const cart = await Cart.findOneAndUpdate(
{ userId: userId },
{ $pull: { products: {_id:cartId} } },
{ $pull: { products: { _id: cartId } } },
{ new: true }
).populate({
).populate({
path: 'products.productId',
model: 'Product'
})
})
// res.send("삭제완료")
res.json(cart)
} catch (error) {
......@@ -63,4 +79,4 @@ const userById = async (req, res, next, id) => {
}
export default { addcart, showcart, deletecart, userById }
\ No newline at end of file
export default { addCart, changeCart, showCart, deleteCart, userById }
\ No newline at end of file
......@@ -5,15 +5,18 @@ import cartCtrl from '../controllers/cart.controller.js';
const router = express.Router()
router.route('/addcart')
.put(cartCtrl.addcart)
.put(cartCtrl.addCart)
// .get()
router.route('/showcart/:userId')
.get(cartCtrl.showcart)
router.param('userId', cartCtrl.userById)
.get(cartCtrl.showCart)
router.route('/changecart')
.post(cartCtrl.changeCart)
router.route('/deletecart')
.post(cartCtrl.deletecart)
.post(cartCtrl.deleteCart)
router.param('userId', cartCtrl.userById)
export default router
\ No newline at end of file
......@@ -22,6 +22,9 @@ const CartSchema = new mongoose.Schema({
},
color: {
type: String
},
checked: {
type: Boolean
}
}
]
......
......@@ -24,32 +24,35 @@ const OrderSchema = new mongoose.Schema({
color: {
type: String,
required: true
},
checked: {
type: Boolean
}
}
],
receiverInfo:
{
name: {
type:String,
required:true
},
tel: {
type: String,
required:true
},
postalCode:{
type:String,
required:true
},
address: {
type: String,
required: true
},
address2: {
type: String,
required: true
}
receiverInfo:
{
name: {
type: String,
required: true
},
tel: {
type: String,
required: true
},
postalCode: {
type: String,
required: true
},
address: {
type: String,
required: true
},
address2: {
type: String,
required: true
}
}
,
total: {
type: Number,
......
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