Payment.js 12.1 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
5
import { Container, Card, Row, Col, Button, Form, FormGroup } from 'react-bootstrap';
import { Redirect } 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
13
14
15
    const [cart, setCart] = useState(location.state)
    const [order, setOrder] = useState({products: location.state})
    const [userData, setUserData] = useState({})
    const [error, setError] = useState()
16
    const [paymentWay, setPaymentWay] = useState([])
Jiwon Yoon's avatar
Jiwon Yoon committed
17
18
19
    // const [isAddress, setIsAddress] = useState("");
    // const [isZoneCode, setIsZoneCode] = useState();
    // const [isPostOpen, setIsPostOpen] = useState();
Jiwon Yoon's avatar
Jiwon Yoon committed
20
    const [post, setPost] = useState([])
Jiwon Yoon's avatar
Jiwon Yoon committed
21
22
    const [redirect, setRedirect] = useState(null)
    const [address, setAddress] = useState("")
Jiwon Yoon's avatar
Jiwon Yoon committed
23
    const [finalPrice, setFinalPrice] = useState(0)
Jiwon Yoon's avatar
Jiwon Yoon committed
24
    const [num, setNum] = useState(0)
Jiwon Yoon's avatar
Jiwon Yoon committed
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
    const user = isAuthenticated()

    useEffect(() => {
        getUser()
        let price = 0
        cart.map((el) => {
            price = Number(el.count) * Number(el.productId.price) + price
        })
        setFinalPrice(price)
    }, [user])

    async function getUser() {
        try {
            const response = await axios.get(`/api/users/getuser/${user}`)
            console.log(response.data)
            setUserData(response.data)
        } catch (error) {
            catchErrors(error, setError)
        }
    }

    function handleReceiverInfo(e) {
        const { name, value } = e.target
        console.log(name,value)
        setOrder({ ...order, receiverInfo: {...order.receiverInfo, [name]: value } })
    }
Jiwon Yoon's avatar
Jiwon Yoon committed
51
52
53
54
55
56
57
58

    function postClick() {
        if (post.length !== 0) {
            setPost([])
        }
        else {
            setPost(
                <div>
Jiwon Yoon's avatar
Jiwon Yoon committed
59
                    <DaumPostcode style={postCodeStyle} onComplete={handleComplete} autoClose={true} />
Jiwon Yoon's avatar
Jiwon Yoon committed
60
61
62
63
64
65
66
67
                </div>
            )
        }

    }
    const handleComplete = (data) => {
        let fullAddress = data.address;
        let extraAddress = "";
Jiwon Yoon's avatar
Jiwon Yoon committed
68
        console.log(data)
Jiwon Yoon's avatar
Jiwon Yoon committed
69
70
71
        if (data.addressType === "R") {
            if (data.bname !== "") {
                extraAddress += data.bname;
Jiwon Yoon's avatar
Jiwon Yoon committed
72
                console.log(extraAddress)
Jiwon Yoon's avatar
Jiwon Yoon committed
73
74
75
76
77
78
79
            }
            if (data.buildingName !== "") {
                extraAddress +=
                    extraAddress !== "" ? `, ${data.buildingName}` : data.buildingName;
            }
            fullAddress += extraAddress !== "" ? ` (${extraAddress})` : "";
        }
Jiwon Yoon's avatar
Jiwon Yoon committed
80
81
        setAddress({ full: fullAddress, code: data.zonecode });
        setOrder({ ...order, receiverInfo: {...order.receiverInfo, address: fullAddress, postalCode: data.zonecode  } })
Jiwon Yoon's avatar
Jiwon Yoon committed
82
83
84
        console.log(fullAddress);
    }

Jiwon Yoon's avatar
Jiwon Yoon committed
85
    const postCodeStyle = {
Jiwon Yoon's avatar
Jiwon Yoon committed
86
        // display: "block",
Jiwon Yoon's avatar
Jiwon Yoon committed
87
88
89
90
        position: "absolute",
        width: "400px",
        height: "500px",
        padding: "7px",
Jiwon Yoon's avatar
Jiwon Yoon committed
91
        zIndex: "1000"
Jiwon Yoon's avatar
Jiwon Yoon committed
92
    };
93
94
95
96
97
98
99

    function handleClick() {
        if (paymentWay.length !== 0) {
            setPaymentWay([])
        }
        else {
            const a = (
100
101
                <Row className="justify-content-md-center">
                    <Col md={6} className="border m-5 p-5">
Jiwon Yoon's avatar
Jiwon Yoon committed
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
                        <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>
120
                    </Col>
Jiwon Yoon's avatar
Jiwon Yoon committed
121

122
                </Row>)
123
124
125
126
            setPaymentWay(a)
        }
    }

Jiwon Yoon's avatar
Jiwon Yoon committed
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
    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,
142
143
144
                approval_url: 'http://localhost:3000/account',
                fail_url: 'http://localhost:3000/shoppingcart',
                cancel_url: 'http://localhost:3000/kakaopay/payment',
Jiwon Yoon's avatar
Jiwon Yoon committed
145
146
147
148
149
150
151
            })
        })
        const data = await response.json()
        console.log(data)
        window.location.href = data.redirect_url
        // setRedirect(data.redirect_url)
    }
152

Jiwon Yoon's avatar
Jiwon Yoon committed
153
154
155
156
157
158
159
160
161
162
163
164
165
    async function paymentCompleted(){
        console.log(user)
        console.log(order)
        console.log(finalPrice)
        try {
            const response = await axios.post(`/api/order/addorder`, {
                userId : user,
                ...order,
                total : finalPrice+2500
            })
            console.log(response.data)
        } catch (error) {
            catchErrors(error, setError)
166
167
        }
    }
Jiwon Yoon's avatar
Jiwon Yoon committed
168
169
170
171
172
173

    if (redirect) {
        console.log(redirect)
        return <Redirect to={'/kakao'} />
    }

Kim, Subin's avatar
Kim, Subin committed
174
175
    return (
        <div>
Jiwon Yoon's avatar
Jiwon Yoon committed
176
            {/* {console.log(order)} */}
177
            <Container>
Jiwon Yoon's avatar
Jiwon Yoon committed
178
                <h3 className="my-5 font-weight-bold text-center">주문/결제</h3>
179
                <div>
Jiwon Yoon's avatar
Jiwon Yoon committed
180
                    <h5 className="font-weight-bold py-3 border-top border-bottom text-center" style={{ background: '#F7F3F3' }}>주문자 정보</h5>
181
182
183
184
185
                    <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
186
                                    <Form.Control type="text" value={userData.name} readOnly />
187
188
189
                                </Form.Group>
                                <Form.Group controlId="formBasicTel">
                                    <Form.Label>휴대전화</Form.Label>
Jiwon Yoon's avatar
Jiwon Yoon committed
190
191
192
193
194
                                    <Form.Control type="tel" value={userData.tel} readOnly />
                                </Form.Group>
                                <Form.Group controlId="formBasicEmail">
                                    <Form.Label>이메일</Form.Label>
                                    <Form.Control type="email" placeholder="이메일 주소를 입력해주세요" />
195
196
197
198
                                </Form.Group>
                            </Form>
                        </Col>
                    </Row>
199
200
201
                </div>

                <div>
Jiwon Yoon's avatar
Jiwon Yoon committed
202
203
204
205
206
207
                    <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
208
209
210
211
212
                                    <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
213
214
215
216
217
                                </Form.Group>
                                <Form.Group controlId="formBasicAdd">
                                    <Form.Label>주소</Form.Label>
                                    <Form.Row>
                                        <Col xs={4} sm={4}>
Jiwon Yoon's avatar
Jiwon Yoon committed
218
                                            <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
219
220
221
222
223
224
225
226
                                        </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
227
228
                                            <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
229
230
231
232
233
                                            <Form.Control.Feedback type="invalid" > 상세 주소를 입력하세요. </Form.Control.Feedback>
                                        </Col>
                                    </Form.Row>
                                </Form.Group>
                            </Form>
Jiwon Yoon's avatar
Jiwon Yoon committed
234
235
                        </Col>
                    </Row>
236
237
238
                </div>

                <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>
Jiwon Yoon's avatar
Jiwon Yoon committed
240
                    <PaymentCard cart={cart} />
241
242
                </div>

Jiwon Yoon's avatar
Jiwon Yoon committed
243
                <div className="p-5 m-3" style={{ background: '#F7F3F3' }}>
244
245
246
                    <ul className="pl-0" style={{ listStyle: 'none' }}>
                        <li>
                            <span className="text-secondary"> 상품금액</span>
Jiwon Yoon's avatar
Jiwon Yoon committed
247
                            <span className="text-secondary float-right">{finalPrice}</span>
248
249
250
                        </li>
                        <li>
                            <span className="text-secondary">배송비</span>
Jiwon Yoon's avatar
Jiwon Yoon committed
251
                            <span className="text-secondary float-right">2500</span>
252
253
254
                        </li>
                    </ul>
                    <div className="my-1 pt-2 border-top font-weight-bold">
Jiwon Yoon's avatar
Jiwon Yoon committed
255
                        결제금액<span className="float-right">{finalPrice + 2500}</span>
256
257
258
259
                    </div>
                </div>

                <div>
Jiwon Yoon's avatar
Jiwon Yoon committed
260
                    <h5 className="font-weight-bold py-3 border-top border-bottom text-center" style={{ background: '#F7F3F3' }}>결제수단</h5>
261
                    <div className="text-center mt-5">
Jiwon Yoon's avatar
Jiwon Yoon committed
262
                        <Button variant="success" className="align-top" onClick={handleClick} >무통장입금</Button>
263
                        <input type="image" alt="카카오페이결제" src="icon/payment_icon_yellow_small.png" onClick={kakaopay} />
264
265
                    </div>
                    {paymentWay}
Jiwon Yoon's avatar
Jiwon Yoon committed
266
267
                </div>
                <div className="text-center">
Jiwon Yoon's avatar
Jiwon Yoon committed
268
                    <Button className="px-5" style={{ background: "#91877F", borderColor: '#91877F' }} onClick={paymentCompleted} block>결제완료</Button>
269
270
                </div>
            </Container>
Kim, Subin's avatar
Kim, Subin committed
271
272
273
274
275
        </div>
    )
}

export default Payment