Payment.js 13.2 KB
Newer Older
Jiwon Yoon's avatar
Jiwon Yoon committed
1
import axios from 'axios';
Kim, Subin's avatar
Kim, Subin committed
2
import React, { useState, useEffect, useRef } from 'react';
Jiwon Yoon's avatar
Jiwon Yoon committed
3
import DaumPostcode from "react-daum-postcode";
Jiwon Yoon's avatar
Jiwon Yoon committed
4
import { Container, Card, Row, Col, Button, Form, FormGroup } from 'react-bootstrap';
Jiwon Yoon's avatar
Jiwon Yoon committed
5
import { Redirect, Link } from 'react-router-dom';
Jiwon Yoon's avatar
Jiwon Yoon committed
6
7
8
import PaymentCard from '../Components/PaymentCard';
import { isAuthenticated } from '../utils/auth';
import catchErrors from '../utils/catchErrors';
Kim, Subin's avatar
Kim, Subin committed
9

Jiwon Yoon's avatar
Jiwon Yoon committed
10
function Payment({ match, location }) {
Kim, Subin's avatar
Kim, Subin committed
11

Jiwon Yoon's avatar
Jiwon Yoon committed
12
    const [cart, setCart] = useState([])
13
    const [order, setOrder] = useState({ products: [] })
Jiwon Yoon's avatar
Jiwon Yoon committed
14
15
    const [userData, setUserData] = useState({})
    const [error, setError] = useState()
16
    const [paymentWay, setPaymentWay] = useState([])
Jiwon Yoon's avatar
Jiwon Yoon committed
17
    const [post, setPost] = useState([])
Jiwon Yoon's avatar
Jiwon Yoon committed
18
19
    const [redirect, setRedirect] = useState(null)
    const [address, setAddress] = useState("")
Jiwon Yoon's avatar
Jiwon Yoon committed
20
    const [finalPrice, setFinalPrice] = useState(0)
Jiwon Yoon's avatar
Jiwon Yoon committed
21
    const [completeState, setCompleteState] = useState(false)
Jiwon Yoon's avatar
Jiwon Yoon committed
22
    const user = isAuthenticated()
Jiwon Yoon's avatar
?    
Jiwon Yoon committed
23
    const preCart = []
Jiwon Yoon's avatar
Jiwon Yoon committed
24
25
26

    useEffect(() => {
        getUser()
Jiwon Yoon's avatar
Jiwon Yoon committed
27
28
29
30
        getCart()
    }, [user])

    useEffect(() => {
Jiwon Yoon's avatar
Jiwon Yoon committed
31
32
33
34
35
        let price = 0
        cart.map((el) => {
            price = Number(el.count) * Number(el.productId.price) + price
        })
        setFinalPrice(price)
Jiwon Yoon's avatar
Jiwon Yoon committed
36
    }, [cart])
Jiwon Yoon's avatar
Jiwon Yoon committed
37
38

    async function getUser() {
39
40
        const name = localStorage.getItem('name')
        const tel = localStorage.getItem('tel')
Jiwon Yoon's avatar
Jiwon Yoon committed
41
42
        const email = localStorage.getItem('email')
        setUserData({ name: name, tel: tel, email:email })
Jiwon Yoon's avatar
Jiwon Yoon committed
43
44
    }

Jiwon Yoon's avatar
Jiwon Yoon committed
45
46
47
48
    async function getCart() {
        try {
            const response = await axios.get(`/api/cart/showcart/${user}`)
            console.log(response.data)
Jiwon Yoon's avatar
?    
Jiwon Yoon committed
49
50
51
52
53
54
            if(response.data[0].checked){
                const preCart = response.data.filter((el) => el.checked === true)
                setCart(preCart)
            } else {
                setCart(response.data)
            }
55
            setOrder({ products: preCart })
Jiwon Yoon's avatar
Jiwon Yoon committed
56
57
58
59
60
        } catch (error) {
            catchErrors(error, setError)
        }
    }

Jiwon Yoon's avatar
Jiwon Yoon committed
61
62
    function handleReceiverInfo(e) {
        const { name, value } = e.target
Jiwon Yoon's avatar
Jiwon Yoon committed
63
64
        console.log(name, value)
        setOrder({ ...order, receiverInfo: { ...order.receiverInfo, [name]: value } })
Jiwon Yoon's avatar
Jiwon Yoon committed
65
    }
Jiwon Yoon's avatar
Jiwon Yoon committed
66
67
68
69
70
71
72
73

    function postClick() {
        if (post.length !== 0) {
            setPost([])
        }
        else {
            setPost(
                <div>
Jiwon Yoon's avatar
Jiwon Yoon committed
74
                    <DaumPostcode style={postCodeStyle} onComplete={handleComplete} autoClose={true} />
Jiwon Yoon's avatar
Jiwon Yoon committed
75
76
77
78
79
80
81
82
                </div>
            )
        }

    }
    const handleComplete = (data) => {
        let fullAddress = data.address;
        let extraAddress = "";
Jiwon Yoon's avatar
Jiwon Yoon committed
83
        console.log(data)
Jiwon Yoon's avatar
Jiwon Yoon committed
84
85
86
        if (data.addressType === "R") {
            if (data.bname !== "") {
                extraAddress += data.bname;
Jiwon Yoon's avatar
Jiwon Yoon committed
87
                console.log(extraAddress)
Jiwon Yoon's avatar
Jiwon Yoon committed
88
89
90
91
92
93
94
            }
            if (data.buildingName !== "") {
                extraAddress +=
                    extraAddress !== "" ? `, ${data.buildingName}` : data.buildingName;
            }
            fullAddress += extraAddress !== "" ? ` (${extraAddress})` : "";
        }
Jiwon Yoon's avatar
Jiwon Yoon committed
95
        setAddress({ full: fullAddress, code: data.zonecode });
Jiwon Yoon's avatar
Jiwon Yoon committed
96
        setOrder({ ...order, receiverInfo: { ...order.receiverInfo, address: fullAddress, postalCode: data.zonecode } })
Jiwon Yoon's avatar
Jiwon Yoon committed
97
98
99
        console.log(fullAddress);
    }

Jiwon Yoon's avatar
Jiwon Yoon committed
100
    const postCodeStyle = {
Jiwon Yoon's avatar
Jiwon Yoon committed
101
        // display: "block",
Jiwon Yoon's avatar
Jiwon Yoon committed
102
103
104
105
        position: "absolute",
        width: "400px",
        height: "500px",
        padding: "7px",
Jiwon Yoon's avatar
Jiwon Yoon committed
106
        zIndex: "1000"
Jiwon Yoon's avatar
Jiwon Yoon committed
107
    };
108
109
110

    function handleClick() {
        if (paymentWay.length !== 0) {
Jiwon Yoon's avatar
Jiwon Yoon committed
111
            setCompleteState(false)
112
113
114
115
            setPaymentWay([])
        }
        else {
            const a = (
116
117
                <Row className="justify-content-md-center">
                    <Col md={6} className="border m-5 p-5">
Jiwon Yoon's avatar
Jiwon Yoon committed
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
                        <Form>
                            <Form.Group controlId="exampleForm.ControlSelect1">
                                <Form.Label>입금은행</Form.Label>
                                <Form.Control as="select" placeholder="입금은행을 선택하세요.">
                                    <option>농협 / 352-0559-2528-83 / 김수빈</option>
                                    <option>우리은행 / 0000-000-000000 / 이재연</option>
                                    <option>국민은행 / 111111-11-111111 / 윤대기</option>
                                </Form.Control>
                            </Form.Group>
                            <Form.Group controlId="formName">
                                <Form.Label>입금자</Form.Label>
                                <Form.Control type="email" placeholder="윤지원" />
                            </Form.Group>
                            <Form.Group controlId="formDay">
                                <Form.Label>입금예정일</Form.Label>
                                <Form.Control type="date" />
                            </Form.Group>
                        </Form>
136
                    </Col>
Jiwon Yoon's avatar
Jiwon Yoon committed
137

138
                </Row>)
139
            setPaymentWay(a)
Jiwon Yoon's avatar
Jiwon Yoon committed
140
            setCompleteState(true)
141
142
143
        }
    }

Jiwon Yoon's avatar
Jiwon Yoon committed
144
    async function kakaopay() {
Jiwon Yoon's avatar
Jiwon Yoon committed
145
        let itemNames = ""
146
147
        if (cart.length > 1) {
            itemNames = cart[0].productId.pro_name + '' + String(cart.length - 1) + ''
Jiwon Yoon's avatar
Jiwon Yoon committed
148
149
150
        } else {
            itemNames = cart[0].productId.pro_name
        }
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
        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',
Jiwon Yoon's avatar
Jiwon Yoon committed
168
            })
169
        })
Jiwon Yoon's avatar
Jiwon Yoon committed
170
        const data = await response.json()
Jiwon Yoon's avatar
Jiwon Yoon committed
171
172
173
        if(data) {
            setCompleteState(true)
        }
Jiwon Yoon's avatar
Jiwon Yoon committed
174
175
176
        window.location.href = data.redirect_url
        // setRedirect(data.redirect_url)
    }
177

Jiwon Yoon's avatar
Jiwon Yoon committed
178
    async function paymentCompleted() {
Jiwon Yoon's avatar
Jiwon Yoon committed
179
        console.log(order)
180
181
182
183
        const cartIds = []
        order.products.map((el) => {
            cartIds.push(el._id)
        })
Jiwon Yoon's avatar
Jiwon Yoon committed
184
185
        try {
            const response = await axios.post(`/api/order/addorder`, {
Jiwon Yoon's avatar
Jiwon Yoon committed
186
                userId: user,
Jiwon Yoon's avatar
Jiwon Yoon committed
187
                ...order,
Jiwon Yoon's avatar
Jiwon Yoon committed
188
                total: finalPrice + 2500
Jiwon Yoon's avatar
Jiwon Yoon committed
189
            })
190
191
192
193
194
195
196
            const response2 = await axios.post(`/api/cart/deletecart2`, {
                userId: user,
                cartId: cartIds
            })
            const response3 = await axios.post(`/api/product/pluspurchase`, {
                products: order.products
            })
Jiwon Yoon's avatar
Jiwon Yoon committed
197
            console.log(response.data)
198
            alert("주문이 완료되었습니다.")
Jiwon Yoon's avatar
Jiwon Yoon committed
199
200
        } catch (error) {
            catchErrors(error, setError)
201
            alert("주문에 실패하셨습니다. 다시 확인해주세요.")
202
203
        }
    }
Jiwon Yoon's avatar
Jiwon Yoon committed
204

Kim, Subin's avatar
Kim, Subin committed
205
206
    return (
        <div>
Jiwon Yoon's avatar
Jiwon Yoon committed
207
            {console.log(completeState)}
208
            <Container>
Jiwon Yoon's avatar
Jiwon Yoon committed
209
                <h3 className="my-5 font-weight-bold text-center">주문/결제</h3>
210
                <div>
Jiwon Yoon's avatar
Jiwon Yoon committed
211
                    <h5 className="font-weight-bold py-3 border-top border-bottom text-center" style={{ background: '#F7F3F3' }}>주문자 정보</h5>
212
213
214
215
216
                    <Row className="justify-content-md-center">
                        <Col md={4}>
                            <Form>
                                <Form.Group controlId="formBasicName">
                                    <Form.Label>이름</Form.Label>
Jiwon Yoon's avatar
Jiwon Yoon committed
217
                                    <Form.Control type="text" value={userData.name} readOnly />
218
219
220
                                </Form.Group>
                                <Form.Group controlId="formBasicTel">
                                    <Form.Label>휴대전화</Form.Label>
Jiwon Yoon's avatar
Jiwon Yoon committed
221
222
223
224
                                    <Form.Control type="tel" value={userData.tel} readOnly />
                                </Form.Group>
                                <Form.Group controlId="formBasicEmail">
                                    <Form.Label>이메일</Form.Label>
Jiwon Yoon's avatar
Jiwon Yoon committed
225
                                    <Form.Control type="email" value={userData.email} readOnly />
226
227
228
229
                                </Form.Group>
                            </Form>
                        </Col>
                    </Row>
230
231
232
                </div>

                <div>
Jiwon Yoon's avatar
Jiwon Yoon committed
233
234
235
236
237
238
                    <h5 className="font-weight-bold py-3 border-top border-bottom text-center" style={{ background: '#F7F3F3' }}>받는사람 정보</h5>
                    <Row className="justify-content-center">
                        <Col md={8}>
                            <Form>
                                <Form.Group>
                                    <Form.Label>이름</Form.Label>
Jiwon Yoon's avatar
Jiwon Yoon committed
239
240
241
242
243
                                    <Form.Control type="text" name="name" onChange={handleReceiverInfo}></Form.Control>
                                </Form.Group>
                                <Form.Group>
                                    <Form.Label>휴대전화</Form.Label>
                                    <Form.Control type="text" name="tel" onChange={handleReceiverInfo}></Form.Control>
Jiwon Yoon's avatar
Jiwon Yoon committed
244
245
246
247
248
                                </Form.Group>
                                <Form.Group controlId="formBasicAdd">
                                    <Form.Label>주소</Form.Label>
                                    <Form.Row>
                                        <Col xs={4} sm={4}>
Jiwon Yoon's avatar
Jiwon Yoon committed
249
                                            <Form.Control type="text" name="postalCode" id="add" onChange={handleReceiverInfo} value={address.code} disabled={(address.code == null) ? false : true} placeholder="우편번호" required ></Form.Control>
Jiwon Yoon's avatar
Jiwon Yoon committed
250
251
252
253
254
255
256
257
                                        </Col>
                                        <Col >
                                            <Button style={{ background: '#91877F', borderColor: '#91877F' }} className="mx-1" onClick={postClick}>우편번호</Button>
                                            {post}
                                        </Col>
                                    </Form.Row>
                                    <Form.Row>
                                        <Col>
Jiwon Yoon's avatar
Jiwon Yoon committed
258
259
                                            <Form.Control type="text" name="address" id="add1" onChange={handleReceiverInfo} value={address.full} disabled={(address.code == null) ? false : true} placeholder="주소" required></Form.Control>
                                            <Form.Control type="text" name="address2" id="add2" onChange={handleReceiverInfo} placeholder="상세주소" required></Form.Control>
Jiwon Yoon's avatar
Jiwon Yoon committed
260
261
262
263
264
                                            <Form.Control.Feedback type="invalid" > 상세 주소를 입력하세요. </Form.Control.Feedback>
                                        </Col>
                                    </Form.Row>
                                </Form.Group>
                            </Form>
Jiwon Yoon's avatar
Jiwon Yoon committed
265
266
                        </Col>
                    </Row>
267
268
269
                </div>

                <div>
Jiwon Yoon's avatar
Jiwon Yoon committed
270
                    <h5 className="font-weight-bold py-3 border-top border-bottom text-center" style={{ background: '#F7F3F3' }}>주문상품정보</h5>
Jiwon Yoon's avatar
Jiwon Yoon committed
271
                    <PaymentCard cart={cart} />
272
273
                </div>

Jiwon Yoon's avatar
Jiwon Yoon committed
274
                <div className="p-5 m-3" style={{ background: '#F7F3F3' }}>
275
276
277
                    <ul className="pl-0" style={{ listStyle: 'none' }}>
                        <li>
                            <span className="text-secondary"> 상품금액</span>
Jiwon Yoon's avatar
Jiwon Yoon committed
278
                            <span className="text-secondary float-right">{finalPrice}</span>
279
280
281
                        </li>
                        <li>
                            <span className="text-secondary">배송비</span>
Jiwon Yoon's avatar
Jiwon Yoon committed
282
                            <span className="text-secondary float-right">2500</span>
283
284
285
                        </li>
                    </ul>
                    <div className="my-1 pt-2 border-top font-weight-bold">
Jiwon Yoon's avatar
Jiwon Yoon committed
286
                        결제금액<span className="float-right">{finalPrice + 2500}</span>
287
288
289
290
                    </div>
                </div>

                <div>
Jiwon Yoon's avatar
Jiwon Yoon committed
291
                    <h5 className="font-weight-bold py-3 border-top border-bottom text-center" style={{ background: '#F7F3F3' }}>결제수단</h5>
292
                    <div className="text-center m-3">
Jiwon Yoon's avatar
Jiwon Yoon committed
293
                        <Button variant="success" className="align-top" onClick={handleClick} >무통장입금</Button>
294
                        <input type="image" alt="카카오페이결제" src="icon/payment_icon_yellow_small.png" onClick={kakaopay} />
295
296
                    </div>
                    {paymentWay}
Jiwon Yoon's avatar
Jiwon Yoon committed
297
298
                </div>
                <div className="text-center">
Jiwon Yoon's avatar
Jiwon Yoon committed
299
                    <Button type="button" onClick={paymentCompleted} disabled={!completeState}  className="px-5" style={{ background: "#91877F", borderColor: '#91877F' }}  block>결제완료</Button>
300
301
                </div>
            </Container>
Kim, Subin's avatar
Kim, Subin committed
302
303
304
305
306
        </div>
    )
}

export default Payment