Payment.js 17.2 KB
Newer Older
Kim, Subin's avatar
최종    
Kim, Subin committed
1
2
import React, { useState, useEffect } from 'react';
import { useHistory } from 'react-router-dom';
kusang96's avatar
kusang96 committed
3
import DaumPostcode from "react-daum-postcode";
kusang96's avatar
card    
kusang96 committed
4
import ListCard from '../Components/ListCard';
kusang96's avatar
kusang96 committed
5
import axios from 'axios';
Jiwon Yoon's avatar
Jiwon Yoon committed
6
7
import { isAuthenticated } from '../utils/auth';
import catchErrors from '../utils/catchErrors';
kusang96's avatar
kusang96 committed
8
import { Container, Row, Col, Button, Form } from 'react-bootstrap';
Jiwon Yoon's avatar
Jiwon Yoon committed
9
const paymentInfo = {}
Kim, Subin's avatar
Kim, Subin committed
10

Kim, Subin's avatar
최종    
Kim, Subin committed
11
function Payment() {
Jiwon Yoon's avatar
Jiwon Yoon committed
12
    const [cart, setCart] = useState([])
kusang96's avatar
kusang96 committed
13
    const [order, setOrder] = useState({ products: [] })
Jiwon Yoon's avatar
Jiwon Yoon committed
14
15
    const [userData, setUserData] = useState({})
    const [error, setError] = useState()
Jiwon Yoon's avatar
Jiwon Yoon committed
16
    const [post, setPost] = useState([])
Jiwon Yoon's avatar
Jiwon Yoon committed
17
    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
24
25

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

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

    async function getUser() {
Jiwon Yoon's avatar
Jiwon Yoon committed
38
39
40
41
42
43
44
        try {
            const response = await axios.get(`/api/users/account/${user}`)
            const { name, tel, email } = response.data
            setUserData({ name: name, tel: tel, email: email })
        } catch (error) {
            catchErrors(error, setError)
        }
Jiwon Yoon's avatar
Jiwon Yoon committed
45
46
    }

Jiwon Yoon's avatar
Jiwon Yoon committed
47
48
    async function getCart() {
        try {
49
            setError('')
Jiwon Yoon's avatar
Jiwon Yoon committed
50
            const response = await axios.get(`/api/cart/showcart/${user}`)
51
52
            const preCart = response.data.filter((el) => el.checked === true)
            if (preCart.length) {
Jiwon Yoon's avatar
?    
Jiwon Yoon committed
53
                setCart(preCart)
54
                setOrder({ products: preCart })
Jiwon Yoon's avatar
?    
Jiwon Yoon committed
55
            } else {
56
57
                alert("주문하실 상품이 없습니다.")
                history.push("/home")
Jiwon Yoon's avatar
?    
Jiwon Yoon committed
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
            })
            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
Kim, Subin's avatar
최종    
Kim, Subin committed
81
        console.log(name, value)
Jiwon Yoon's avatar
Jiwon Yoon committed
82
        setOrder({ ...order, receiverInfo: { ...order.receiverInfo, [name]: value } })
Jiwon Yoon's avatar
Jiwon Yoon committed
83
    }
Jiwon Yoon's avatar
Jiwon Yoon committed
84

Jiwon Yoon's avatar
Jiwon Yoon committed
85
86
87
88
89
90
91
92
    function handlepaymentInfo(e) {
        const { name, value } = e.target
        // console.log(name, value)
        paymentInfo[name] = value
        console.log(paymentInfo)
        // setOrder({ ...order, paymentInfo: { ...order.paymentInfo, [name]: value } })
    }

Jiwon Yoon's avatar
Jiwon Yoon committed
93
94
95
96
97
98
99
    function postClick() {
        if (post.length !== 0) {
            setPost([])
        }
        else {
            setPost(
                <div>
Jiwon Yoon's avatar
Jiwon Yoon committed
100
                    <DaumPostcode style={postCodeStyle} onComplete={handleComplete} autoClose={true} />
Jiwon Yoon's avatar
Jiwon Yoon committed
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
                </div>
            )
        }

    }
    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})` : "";
        }
Jiwon Yoon's avatar
Jiwon Yoon committed
119
        setAddress({ full: fullAddress, code: data.zonecode });
Jiwon Yoon's avatar
Jiwon Yoon committed
120
        setOrder({ ...order, receiverInfo: { ...order.receiverInfo, address: fullAddress, postalCode: data.zonecode } })
Jiwon Yoon's avatar
Jiwon Yoon committed
121
122
    }

Jiwon Yoon's avatar
Jiwon Yoon committed
123
124
125
126
127
    const postCodeStyle = {
        position: "absolute",
        width: "400px",
        height: "500px",
        padding: "7px",
Jiwon Yoon's avatar
Jiwon Yoon committed
128
        zIndex: "1000"
Jiwon Yoon's avatar
Jiwon Yoon committed
129
    };
130
131

    function handleClick() {
Jiwon Yoon's avatar
Jiwon Yoon committed
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
        const bankList = (
            <Row className="justify-content-md-center">
                <Col md={6} className="border m-5 p-5">
                    <Form>
                        <Form.Group controlId="bank">
                            <Form.Label>입금은행</Form.Label>
                            <Form.Control as="select" name="bank" onChange={handlepaymentInfo}>
                                <option value=''>입금은행을 선택하세요.</option>
                                <option value="농협 / 352-0559-2528-83 / 김수빈">농협 / 352-0559-2528-83 / 김수빈</option>
                                <option value="우리은행 / 0000-000-000000 / 이재연">우리은행 / 0000-000-000000 / 이재연</option>
                                <option value="국민은행 / 111111-11-111111 / 윤대기">국민은행 / 111111-11-111111 / 윤대기</option>
                            </Form.Control>
                        </Form.Group>
                        <Form.Group controlId="depositor">
                            <Form.Label>입금자</Form.Label>
                            <Form.Control type="text" name="depositor" onChange={handlepaymentInfo} />
                        </Form.Group>
                        <Form.Group controlId="deadline">
                            <Form.Label>입금예정일</Form.Label>
                            <Form.Control type="date" name="deadline" onChange={handlepaymentInfo} />
                        </Form.Group>
                    </Form>
                </Col>
            </Row>)
        setCompleteState("Remittance")
        setPaymentWay(bankList)

159
160
    }

Jiwon Yoon's avatar
Jiwon Yoon committed
161
    async function kakaopay() {
Jiwon Yoon's avatar
Jiwon Yoon committed
162
163
164
165
166
167
168
        setCompleteState("kakaopay")
        setPaymentWay(
            <div className="text-center">
                <p className=" font-weight-bold" style={{ display: 'inline' }}>'카카오페이'</p><p style={{ display: 'inline' }}>를 선택하셨습니다. </p>
                <p>주문하기를 눌러 결제를 이어가주세요.</p>
            </div>
        )
Jiwon Yoon's avatar
Jiwon Yoon committed
169
        // setOrder({ ...order, paymentInfo: { bank: "kakaopay" }})
Jiwon Yoon's avatar
Jiwon Yoon committed
170
    }
171

Jiwon Yoon's avatar
Jiwon Yoon committed
172
    async function paymentCompleted() {
Jiwon Yoon's avatar
Jiwon Yoon committed
173
174
        console.log(paymentInfo)
        console.log(completeState)
175
176
177
178
        const cartIds = []
        order.products.map((el) => {
            cartIds.push(el._id)
        })
Kim, Subin's avatar
최종    
Kim, Subin committed
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
        try {
            setError('')
            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()
Jiwon Yoon's avatar
Jiwon Yoon committed
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
                const response1 = await axios.post(`/api/order/addorder`, {
                    userId: user,
                    ...order,
                    completeState,
                    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 (response1 && response2 && response3) {
                    window.location.href = data.redirect_url
                }
            } else if(completeState === "Remittance"){
                const response1 = await axios.post(`/api/order/addorder`, {
                    userId: user,
                    ...order,
                    paymentInfo,
                    completeState,
                    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 (response1 && response2 && response3) {
                    alert("주문이 완료되었습니다.")
                    history.push('/paymentcompleted')
                } else {
                    alert("주문에 실패하셨습니다. 다시 확인해주세요.")
                }
Kim, Subin's avatar
최종    
Kim, Subin committed
246
            } else {
Jiwon Yoon's avatar
Jiwon Yoon committed
247
                alert("completeState없음")
Kim, Subin's avatar
최종    
Kim, Subin committed
248
249
250
            }
        } catch (error) {
            catchErrors(error, setError)
Jiwon Yoon's avatar
Jiwon Yoon committed
251
            alert("주문에 실패하셨습니다. 정보가 모두 입력되었는지 다시 확인해주세요.")
Kim, Subin's avatar
최종    
Kim, Subin committed
252
253
            window.location.reload()
        }
254
    }
Jiwon Yoon's avatar
Jiwon Yoon committed
255

256
257
258
259
260
    if (error) {
        alert(`${error}`)
        setError('')
    }

Kim, Subin's avatar
Kim, Subin committed
261
    return (
Kim, Subin's avatar
margin    
Kim, Subin committed
262
        <Container className="mb-5">
Kim, Subin's avatar
최종    
Kim, Subin committed
263
            {console.log("order=", order)}
kusang96's avatar
kusang96 committed
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
            <h3 className="my-5 font-weight-bold text-center">주문/결제</h3>
            <div>
                <h5 className="font-weight-bold py-3 border-top border-bottom text-center" style={{ background: '#F7F3F3' }}>주문자 정보</h5>
                <Row className="justify-content-md-center">
                    <Col md={4}>
                        <Form>
                            <Form.Group controlId="formBasicName">
                                <Form.Label>이름</Form.Label>
                                <Form.Control type="text" value={userData.name} readOnly />
                            </Form.Group>
                            <Form.Group controlId="formBasicTel">
                                <Form.Label>휴대전화</Form.Label>
                                <Form.Control type="tel" value={userData.tel} readOnly />
                            </Form.Group>
                            <Form.Group controlId="formBasicEmail">
                                <Form.Label>이메일</Form.Label>
280
                                <Form.Control type="email" value={userData.email} readOnly />
kusang96's avatar
kusang96 committed
281
282
283
284
285
286
287
288
289
290
                            </Form.Group>
                        </Form>
                    </Col>
                </Row>
            </div>
            <div>
                <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>
291
                            <Form.Group controlId="recipientName">
kusang96's avatar
kusang96 committed
292
293
294
                                <Form.Label>이름</Form.Label>
                                <Form.Control type="text" name="name" onChange={handleReceiverInfo}></Form.Control>
                            </Form.Group>
295
                            <Form.Group controlId="recipientTel">
kusang96's avatar
kusang96 committed
296
297
298
                                <Form.Label>휴대전화</Form.Label>
                                <Form.Control type="text" name="tel" onChange={handleReceiverInfo}></Form.Control>
                            </Form.Group>
299
                            <Form.Group controlId="recipientAdd">
kusang96's avatar
kusang96 committed
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
                                <Form.Label>주소</Form.Label>
                                <Form.Row>
                                    <Col xs={4} sm={4}>
                                        <Form.Control type="text" name="postalCode" id="add" onChange={handleReceiverInfo} value={address.code} disabled={(address.code == null) ? false : true} placeholder="우편번호" required ></Form.Control>
                                    </Col>
                                    <Col >
                                        <Button style={{ background: '#91877F', borderColor: '#91877F' }} className="mx-1" onClick={postClick}>우편번호</Button>
                                        {post}
                                    </Col>
                                </Form.Row>
                                <Form.Row>
                                    <Col>
                                        <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>
                                        <Form.Control.Feedback type="invalid" > 상세 주소를 입력하세요. </Form.Control.Feedback>
                                    </Col>
                                </Form.Row>
                            </Form.Group>
                        </Form>
                    </Col>
                </Row>
            </div>
            <div>
                <h5 className="font-weight-bold py-3 border-top border-bottom text-center" style={{ background: '#F7F3F3' }}>주문상품정보</h5>
kusang96's avatar
card    
kusang96 committed
324
                <ListCard cart={cart} deleteOrder={deleteOrder} status={'payment'} />
kusang96's avatar
kusang96 committed
325
326
327
328
329
330
331
332
333
334
335
336
337
338
            </div>
            <div className="p-5 m-3" style={{ background: '#F7F3F3' }}>
                <ul className="pl-0" style={{ listStyle: 'none' }}>
                    <li>
                        <span className="text-secondary"> 상품금액</span>
                        <span className="text-secondary float-right">{finalPrice}</span>
                    </li>
                    <li>
                        <span className="text-secondary">배송비</span>
                        <span className="text-secondary float-right">2500</span>
                    </li>
                </ul>
                <div className="my-1 pt-2 border-top font-weight-bold">
                    결제금액<span className="float-right">{finalPrice + 2500}</span>
339
                </div>
Jiwon Yoon's avatar
Jiwon Yoon committed
340
            </div>
341
342
343
            <div>
                <h5 className="font-weight-bold py-3 border-top border-bottom text-center" style={{ background: '#F7F3F3' }}>결제수단</h5>
                <div className="text-center m-3">
Jiwon Yoon's avatar
Jiwon Yoon committed
344
                    <Button className="align-top m-1" variant="success" type="button" onClick={handleClick} style={{ height: '42px' }}>무통장입금</Button>
345
                    <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>
346
                </div>
Jiwon Yoon's avatar
Jiwon Yoon committed
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
                {/* <Row className="justify-content-md-center">
                    <Col md={6} className="border m-5 p-5">
                        <Form>
                            <Form.Group controlId="bank">
                                <Form.Label>입금은행</Form.Label>
                                <Form.Control as="select" name="bank" onChange={handlepaymentInfo}>
                                    <option value=''>입금은행을 선택하세요.</option>
                                    <option value="농협 / 352-0559-2528-83 / 김수빈">농협 / 352-0559-2528-83 / 김수빈</option>
                                    <option value="우리은행 / 0000-000-000000 / 이재연">우리은행 / 0000-000-000000 / 이재연</option>
                                    <option value="국민은행 / 111111-11-111111 / 윤대기">국민은행 / 111111-11-111111 / 윤대기</option>
                                </Form.Control>
                            </Form.Group>
                            <Form.Group controlId="depositor">
                                <Form.Label>입금자</Form.Label>
                                <Form.Control type="text" name="depositor" onChange={handlepaymentInfo} />
                            </Form.Group>
                            <Form.Group controlId="deadline">
                                <Form.Label>입금예정일</Form.Label>
                                <Form.Control type="date" name="deadline" onChange={handlepaymentInfo} />
                            </Form.Group>
                        </Form>
                    </Col>
                </Row> */}
370
371
372
                {paymentWay}
            </div>
            <div className="text-center">
Jiwon Yoon's avatar
Jiwon Yoon committed
373
                <Button type="button" onClick={paymentCompleted} className="px-5" style={{ background: "#91877F", borderColor: '#91877F' }} block>주문하기</Button>
kusang96's avatar
kusang96 committed
374
375
            </div>
        </Container>
Kim, Subin's avatar
Kim, Subin committed
376
377
378
379
    )
}

export default Payment