Payment.js 14.6 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';
5
import { Redirect, Link, useHistory } 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 }) {
Jiwon Yoon's avatar
Jiwon Yoon committed
11
    const [cart, setCart] = useState([])
12
    const [order, setOrder] = useState({products: []})
Jiwon Yoon's avatar
Jiwon Yoon committed
13
14
    const [userData, setUserData] = useState({})
    const [error, setError] = useState()
Jiwon Yoon's avatar
Jiwon Yoon committed
15
    const [post, setPost] = useState([])
Jiwon Yoon's avatar
Jiwon Yoon committed
16
17
    const [redirect, setRedirect] = useState(null)
    const [address, setAddress] = useState("")
Jiwon Yoon's avatar
Jiwon Yoon committed
18
    const [finalPrice, setFinalPrice] = useState(0)
Jiwon Yoon's avatar
Jiwon Yoon committed
19
    const [paymentWay, setPaymentWay] = useState([])
Jiwon Yoon's avatar
Jiwon Yoon committed
20
    const [completeState, setCompleteState] = useState(false)
Jiwon Yoon's avatar
Jiwon Yoon committed
21
    const user = isAuthenticated()
22
    let history = useHistory();
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
        const email = localStorage.getItem('email')
42
        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
    async function getCart() {
        try {
47
            setError('')
Jiwon Yoon's avatar
Jiwon Yoon committed
48
49
            const response = await axios.get(`/api/cart/showcart/${user}`)
            console.log(response.data)
50
51
            const preCart = response.data.filter((el) => el.checked === true)
            if (preCart.length) {
Jiwon Yoon's avatar
?    
Jiwon Yoon committed
52
                setCart(preCart)
53
                setOrder({ products: preCart })
Jiwon Yoon's avatar
?    
Jiwon Yoon committed
54
            } else {
55
56
                alert("주문하실 상품이 없습니다.")
                history.push("/home")
Jiwon Yoon's avatar
?    
Jiwon Yoon committed
57
            }
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
        } 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
            })
            console.log(response.data)
            const preCart = response.data.products.filter((el) => el.checked === true)
            setCart(preCart)
73
            setOrder({ products: preCart })
Jiwon Yoon's avatar
Jiwon Yoon committed
74
75
76
77
78
        } catch (error) {
            catchErrors(error, setError)
        }
    }

Jiwon Yoon's avatar
Jiwon Yoon committed
79
80
    function handleReceiverInfo(e) {
        const { name, value } = e.target
Jiwon Yoon's avatar
Jiwon Yoon committed
81
82
        console.log(name, value)
        setOrder({ ...order, receiverInfo: { ...order.receiverInfo, [name]: value } })
Jiwon Yoon's avatar
Jiwon Yoon committed
83
    }
Jiwon Yoon's avatar
Jiwon Yoon committed
84
85
86
87
88
89
90
91

    function postClick() {
        if (post.length !== 0) {
            setPost([])
        }
        else {
            setPost(
                <div>
Jiwon Yoon's avatar
Jiwon Yoon committed
92
                    <DaumPostcode style={postCodeStyle} onComplete={handleComplete} autoClose={true} />
Jiwon Yoon's avatar
Jiwon Yoon committed
93
94
95
96
97
98
99
100
                </div>
            )
        }

    }
    const handleComplete = (data) => {
        let fullAddress = data.address;
        let extraAddress = "";
Jiwon Yoon's avatar
Jiwon Yoon committed
101
        console.log(data)
Jiwon Yoon's avatar
Jiwon Yoon committed
102
103
104
        if (data.addressType === "R") {
            if (data.bname !== "") {
                extraAddress += data.bname;
Jiwon Yoon's avatar
Jiwon Yoon committed
105
                console.log(extraAddress)
Jiwon Yoon's avatar
Jiwon Yoon committed
106
107
108
109
110
111
112
            }
            if (data.buildingName !== "") {
                extraAddress +=
                    extraAddress !== "" ? `, ${data.buildingName}` : data.buildingName;
            }
            fullAddress += extraAddress !== "" ? ` (${extraAddress})` : "";
        }
Jiwon Yoon's avatar
Jiwon Yoon committed
113
        setAddress({ full: fullAddress, code: data.zonecode });
Jiwon Yoon's avatar
Jiwon Yoon committed
114
        setOrder({ ...order, receiverInfo: { ...order.receiverInfo, address: fullAddress, postalCode: data.zonecode } })
Jiwon Yoon's avatar
Jiwon Yoon committed
115
116
117
        console.log(fullAddress);
    }

Jiwon Yoon's avatar
Jiwon Yoon committed
118
    const postCodeStyle = {
Jiwon Yoon's avatar
Jiwon Yoon committed
119
        // display: "block",
Jiwon Yoon's avatar
Jiwon Yoon committed
120
121
122
123
        position: "absolute",
        width: "400px",
        height: "500px",
        padding: "7px",
Jiwon Yoon's avatar
Jiwon Yoon committed
124
        zIndex: "1000"
Jiwon Yoon's avatar
Jiwon Yoon committed
125
    };
126
127
128

    function handleClick() {
        if (paymentWay.length !== 0) {
Jiwon Yoon's avatar
Jiwon Yoon committed
129
            setCompleteState(false)
130
            setPaymentWay([])
Jiwon Yoon's avatar
Jiwon Yoon committed
131
        } else {
132
            const a = (
133
134
                <Row className="justify-content-md-center">
                    <Col md={6} className="border m-5 p-5">
Jiwon Yoon's avatar
Jiwon Yoon committed
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
                        <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>
153
                    </Col>
Jiwon Yoon's avatar
Jiwon Yoon committed
154

155
                </Row>)
156
157
158
159
            setPaymentWay(a)
        }
    }

Jiwon Yoon's avatar
Jiwon Yoon committed
160
    async function kakaopay() {
Jiwon Yoon's avatar
Jiwon Yoon committed
161
162
163
164
165
166
167
168
169

        setCompleteState("kakaopay")
        setPaymentWay(
            <div className="text-center">
                <p className=" font-weight-bold" style={{ display: 'inline' }}>'카카오페이'</p><p style={{ display: 'inline' }}>를 선택하셨습니다. </p>
                <p>주문하기를 눌러 결제를 이어가주세요.</p>
            </div>
        )
        // window.location.href = data.redirect_url
Jiwon Yoon's avatar
Jiwon Yoon committed
170
171
        // setRedirect(data.redirect_url)
    }
172

Jiwon Yoon's avatar
Jiwon Yoon committed
173
    async function paymentCompleted() {
Jiwon Yoon's avatar
Jiwon Yoon committed
174
        console.log(order)
175
176
177
178
        const cartIds = []
        order.products.map((el) => {
            cartIds.push(el._id)
        })
Jiwon Yoon's avatar
Jiwon Yoon committed
179
        try {
180
            setError('')
Jiwon Yoon's avatar
Jiwon Yoon committed
181
            const response = await axios.post(`/api/order/addorder`, {
Jiwon Yoon's avatar
Jiwon Yoon committed
182
                userId: user,
Jiwon Yoon's avatar
Jiwon Yoon committed
183
                ...order,
Jiwon Yoon's avatar
Jiwon Yoon committed
184
                total: finalPrice + 2500
Jiwon Yoon's avatar
Jiwon Yoon committed
185
            })
186
187
188
189
190
191
192
            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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
            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
                }
                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()
            } else {
                console.log(response.data)
                console.log(response2.data)
                console.log(response3.data)
                alert("주문이 완료되었습니다.")
                history.push('/paymentcompleted')
            }
Jiwon Yoon's avatar
Jiwon Yoon committed
227
228
        } catch (error) {
            catchErrors(error, setError)
229
            alert("주문에 실패하셨습니다. 다시 확인해주세요.")
230
231
        }
    }
Jiwon Yoon's avatar
Jiwon Yoon committed
232

Kim, Subin's avatar
Kim, Subin committed
233
234
    return (
        <div>
235
            {/* {console.log(completeState)} */}
236
            <Container>
Jiwon Yoon's avatar
Jiwon Yoon committed
237
                <h3 className="my-5 font-weight-bold text-center">주문/결제</h3>
238
                <div>
Jiwon Yoon's avatar
Jiwon Yoon committed
239
                    <h5 className="font-weight-bold py-3 border-top border-bottom text-center" style={{ background: '#F7F3F3' }}>주문자 정보</h5>
240
241
242
243
244
                    <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
245
                                    <Form.Control type="text" value={userData.name} readOnly />
246
247
248
                                </Form.Group>
                                <Form.Group controlId="formBasicTel">
                                    <Form.Label>휴대전화</Form.Label>
Jiwon Yoon's avatar
Jiwon Yoon committed
249
250
251
252
                                    <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
253
                                    <Form.Control type="email" value={userData.email} readOnly />
254
255
256
257
                                </Form.Group>
                            </Form>
                        </Col>
                    </Row>
258
259
260
                </div>

                <div>
Jiwon Yoon's avatar
Jiwon Yoon committed
261
262
263
264
265
266
                    <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
267
268
269
270
271
                                    <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
272
273
274
275
276
                                </Form.Group>
                                <Form.Group controlId="formBasicAdd">
                                    <Form.Label>주소</Form.Label>
                                    <Form.Row>
                                        <Col xs={4} sm={4}>
Jiwon Yoon's avatar
Jiwon Yoon committed
277
                                            <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
278
279
280
281
282
283
284
285
                                        </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
286
287
                                            <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
288
289
290
291
292
                                            <Form.Control.Feedback type="invalid" > 상세 주소를 입력하세요. </Form.Control.Feedback>
                                        </Col>
                                    </Form.Row>
                                </Form.Group>
                            </Form>
Jiwon Yoon's avatar
Jiwon Yoon committed
293
294
                        </Col>
                    </Row>
295
296
                </div>
                <div>
Jiwon Yoon's avatar
Jiwon Yoon committed
297
                    <h5 className="font-weight-bold py-3 border-top border-bottom text-center" style={{ background: '#F7F3F3' }}>주문상품정보</h5>
298
                    <PaymentCard cart={cart} deleteOrder={deleteOrder} />
299
300
                </div>

Jiwon Yoon's avatar
Jiwon Yoon committed
301
                <div className="p-5 m-3" style={{ background: '#F7F3F3' }}>
302
303
304
                    <ul className="pl-0" style={{ listStyle: 'none' }}>
                        <li>
                            <span className="text-secondary"> 상품금액</span>
Jiwon Yoon's avatar
Jiwon Yoon committed
305
                            <span className="text-secondary float-right">{finalPrice}</span>
306
307
308
                        </li>
                        <li>
                            <span className="text-secondary">배송비</span>
Jiwon Yoon's avatar
Jiwon Yoon committed
309
                            <span className="text-secondary float-right">2500</span>
310
311
312
                        </li>
                    </ul>
                    <div className="my-1 pt-2 border-top font-weight-bold">
Jiwon Yoon's avatar
Jiwon Yoon committed
313
                        결제금액<span className="float-right">{finalPrice + 2500}</span>
314
315
316
                    </div>
                </div>
                <div>
Jiwon Yoon's avatar
Jiwon Yoon committed
317
                    <h5 className="font-weight-bold py-3 border-top border-bottom text-center" style={{ background: '#F7F3F3' }}>결제수단</h5>
318
                    <div className="text-center m-3">
Jiwon Yoon's avatar
Jiwon Yoon committed
319
320
                        <Button className="align-top m-1" variant="success" onClick={handleClick} style={{ height: '42px' }}>무통장입금</Button>
                        <Button className="align-top m-1 p-0" style={{ borderColor: "#ffeb00" }} type="button" onClick={kakaopay} alt="카카오페이"><img src="icon/payment_icon_yellow_small2.png" /></Button>
321
322
                    </div>
                    {paymentWay}
Jiwon Yoon's avatar
Jiwon Yoon committed
323
324
                </div>
                <div className="text-center">
Jiwon Yoon's avatar
Jiwon Yoon committed
325
                    <Button type="button" onClick={paymentCompleted} className="px-5" style={{ background: "#91877F", borderColor: '#91877F' }} block>결제완료</Button>
326
327
                </div>
            </Container>
Kim, Subin's avatar
Kim, Subin committed
328
329
330
331
332
        </div>
    )
}

export default Payment