PaymentPage.js 17.6 KB
Newer Older
Jiwon Yoon's avatar
Jiwon Yoon committed
1
2
import axios from 'axios'
import { useEffect, useState } from 'react'
Jiwon Yoon's avatar
Jiwon Yoon committed
3
import authApi from '../../apis/auth.api'
4
import kakaopayApi from '../../apis/kakaopay.api'
한규민's avatar
한규민 committed
5
import reservationApi from '../../apis/reservation.api'
Jiwon Yoon's avatar
Jiwon Yoon committed
6
7
8
9
10
import { useAuth } from '../../context/auth_context'
import catchErrors from '../../utils/catchErrors'
import styles from './PaymentPage.module.scss'

const Payment = ({ location }) => {
11
    const { user } = useAuth()
한규민's avatar
한규민 committed
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
    const [guestInfo, setGuestInfo] = useState({
        name: "",
        email: "",
        birth: "",
        phoneNumber: "",
        password: "",
        rePassword: ""
    })
    const [errorMsg, setErrorMsg] = useState({
        errorName: false,
        errorEmail: false,
        errorBirthday: false,
        errorMbnum: false,
        errorPassword: false,
    })

28
    const [guestID, setGuestID] = useState()
29
30
31
32
33
34
    const [userInfo, setUserInfo] = useState({
        nickname: "",
        email: "",
        birth: "",
        phoneNumber: ""
    })
35
36
37
    const [ticketInfo, setTicketInfo] = useState({ ...location.state })
    const [element, setElement] = useState()
    const [error, setError] = useState("")
Jiwon Yoon's avatar
Jiwon Yoon committed
38

한규민's avatar
한규민 committed
39
40
41
42
43
44
    const [startTime, setStartTime] = useState("");
    const [number, setNumber] = useState(null);
    const [loading, setLoading] = useState(false);
    const [mbError, setMbError] = useState(false);
    const [confirmMb, setConfirmMb] = useState(false);

Jiwon Yoon's avatar
Jiwon Yoon committed
45
    useEffect(() => {
46
        if (user.role === "member") {
Jiwon Yoon's avatar
Jiwon Yoon committed
47
48
49
50
            getUserInfo()
        }
    }, [])

한규민's avatar
한규민 committed
51
    const getUserInfo = async () => {
Jiwon Yoon's avatar
Jiwon Yoon committed
52
        try {
Kim, Subin's avatar
Kim, Subin committed
53
            setError("")
Jiwon Yoon's avatar
Jiwon Yoon committed
54
55
56
57
58
59
60
61
62
            const response = await axios.post(`/api/auth/getuserinfo`, {
                id: user.id
            })
            setUserInfo(response.data)
        } catch (error) {
            catchErrors(error, setError)
        }
    }

한규민's avatar
한규민 committed
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
    const handleChangeGuest = (e) => {
        setGuestInfo({
            ...guestInfo,
            [e.target.name]: String(e.target.value)
        })
        if (e.target.name === "birth" || e.target.name === "phoneNumber") {
            setGuestInfo({
                ...guestInfo,
                [e.target.name]: String(e.target.value)
            })
        }
    }
    //인증번호
    const handleOnClickMbnum = async (e) => {
        e.preventDefault();
        try {
            setStartTime("");
            setError("");
            setLoading(true)
            const phone = guestInfo.phoneNumber;
            const message = await authApi.confirmMbnum(phone);
            if (message.isSuccess) {
                setMbError("보냄");
                setStartTime(message.startTime);
            }
        } catch (error) {
            catchErrors(error, setError);
        } finally {
            setLoading(false);
        }
    }

    const handleOnChangeMb = (e) => {
        setNumber(String(e.target.value));
Jiwon Yoon's avatar
Jiwon Yoon committed
97
98
    }

한규민's avatar
한규민 committed
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
    const handleOnClickMbConfirm = async (e) => {
        e.preventDefault();
        try {
            setError("");
            setLoading(true);
            const confirmNum = { userMbnum: guestInfo.phoneNumber, number: number, startTime: startTime };
            const message = await authApi.confirmNum(confirmNum);
            setMbError(message);
            if (message === "성공") {
                setConfirmMb(true);
            }
        } catch (error) {
            catchErrors(error, setError);
        } finally {
            setLoading(false);
        }
    }
    //비밀번호 확인
    const validationPw = () => {
        if (guestInfo.password !== guestInfo.rePassword) return false;
        else return true;
    }

    const handleClickGuest = async () => {
Jiwon Yoon's avatar
Jiwon Yoon committed
123
        try {
Kim, Subin's avatar
Kim, Subin committed
124
            setError("")
한규민's avatar
한규민 committed
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
            setLoading(true);
            let validPw = validationPw();
            if (confirmMb) {
                if (validPw) {
                    const response = await authApi.saveGuestInfo(guestInfo);
                    if (response.id) {
                        setGuestID(response.id)
                        alert("비회원 정보가 저장되었습니다.")
                    }
                    else {
                        setErrorMsg(response);
                        alert("형식에 맞게 다시 작성해주세요");
                    }
                } else throw new Error("비밀번호가 일치하지 않습니다.");
            } else throw new Error("핸드폰 번호를 인증해주세요.");
Jiwon Yoon's avatar
Jiwon Yoon committed
140
141
142
143
144
        } catch (error) {
            catchErrors(error, setError)
        }
    }

한규민's avatar
한규민 committed
145
    const kakaoBtnClick = () => {
146
147
148
149
150
151
152
153
154
        setElement(
            <div className="text-center">
                <p className=" font-weight-bold" style={{ display: 'inline', color: "#FEDC00" }}>'카카오페이'</p><p style={{ display: 'inline' }}>를 선택하셨습니다. </p>
                <p>결제하기를 눌러 결제를 이어가주세요.</p>
            </div>
        )
        setTicketInfo({ ...ticketInfo, payment: "카카오페이" })
    }

한규민's avatar
한규민 committed
155
    const reservationComplete = async () => {
Jiwon Yoon's avatar
Jiwon Yoon committed
156
        try {
Kim, Subin's avatar
Kim, Subin committed
157
            setError("")
158
            if (user.role === "member") {
한규민's avatar
한규민 committed
159
                const response = await reservationApi.save({
Jiwon Yoon's avatar
Jiwon Yoon committed
160
161
162
163
                    userType: "member",
                    user: userInfo.id,
                    ...ticketInfo,
                })
164
                const responsekakao = await kakaopayApi.approveReq({
165
                    cid: 'TC0ONETIME',
Jiwon Yoon's avatar
Jiwon Yoon committed
166
                    partner_order_id: 'butter_studio',
167
                    partner_user_id: '000000' + guestID,
168
                    item_name: ticketInfo.title,
169
                    item_code: ticketInfo.movieId,
170
171
172
173
174
                    quantity: ticketInfo.adult + ticketInfo.youth + ticketInfo.senior,
                    total_amount: ticketInfo.totalFee,
                    vat_amount: 0,
                    tax_free_amount: 0,
                    approval_url: 'http://localhost:3000/paymentcomplete',
175
176
                    fail_url: 'http://localhost:3000/paymentfail',
                    cancel_url: 'http://localhost:3000/paymentfail',
177
178
                })
                if (response && responsekakao) {
179
180
                    localStorage.setItem('tid', responsekakao.tid)
                    window.location.href = responsekakao.redirect_url
181
                }
Jiwon Yoon's avatar
Jiwon Yoon committed
182
183
            } else {
                if (guestID) {
한규민's avatar
한규민 committed
184
                    const response = await reservationApi.save({
Jiwon Yoon's avatar
Jiwon Yoon committed
185
186
187
188
                        userType: "guest",
                        user: guestID,
                        ...ticketInfo,
                    })
189
                    const responsekakao = await kakaopayApi.approveReq({
190
                        cid: 'TC0ONETIME',
Jiwon Yoon's avatar
Jiwon Yoon committed
191
                        partner_order_id: 'butter_studio',
192
                        partner_user_id: '000000' + guestID,
193
                        item_name: ticketInfo.title,
Jiwon Yoon's avatar
Jiwon Yoon committed
194
                        item_code: ticketInfo.movieId,
195
196
197
198
199
                        quantity: ticketInfo.adult + ticketInfo.youth + ticketInfo.senior,
                        total_amount: ticketInfo.totalFee,
                        vat_amount: 0,
                        tax_free_amount: 0,
                        approval_url: 'http://localhost:3000/paymentcomplete',
200
201
                        fail_url: 'http://localhost:3000/paymentfail',
                        cancel_url: 'http://localhost:3000/paymentfail',
202
                    })
203
204
205
                    if (response && responsekakao) {
                        localStorage.setItem('tid', responsekakao.tid)
                        window.location.href = responsekakao.redirect_url
206
                    }
Jiwon Yoon's avatar
Jiwon Yoon committed
207
                } else {
208
                    alert("비회원 정보를 모두 입력 후 비회원 정보 저장 버튼을 눌러주세요.")
Jiwon Yoon's avatar
Jiwon Yoon committed
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
                }
            }
        } catch (error) {
            catchErrors(error, setError)
        }
    }

    return (
        <div className="container" style={{ color: "white" }}>
            <div className="row justify-content-center my-5">
                <div className="col-sm-4 ">
                    <h3 className="py-2 text-white text-center" style={{ border: "3px solid #000000", borderBottom: "3px solid #FEDC00" }}>결제하기</h3>
                </div>
            </div>
            <div className="row justify-content-center">
                <div className="col-sm-8 text-center">
225
                    {user.role === "member"
Jiwon Yoon's avatar
Jiwon Yoon committed
226
227
                        ?
                        <div>
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
                            <h5 className="mb-4 p-2" style={{ backgroundColor: "white", color: "black" }}>회원정보</h5>
                            <div className="my-1">
                                <label className={styles.labelStyle}>이름</label>
                                <input type="text" name="name" placeholder="이름" value={userInfo.nickname} />
                            </div>
                            <div className="my-1">
                                <label className={styles.labelStyle}>이메일</label>
                                <input type="email" name="email" placeholder="이메일" value={userInfo.email} />
                            </div>
                            <div className="my-1">
                                <label className={styles.labelStyle}>생년월일</label>
                                <input type="number" name="birth" placeholder="생년월일" maxLength="6" value={userInfo.birth} />
                            </div>
                            <div className="my-1">
                                <label className={styles.labelStyle}>휴대폰 번호</label>
                                <input type="number" name="phoneNumber" placeholder="휴대폰 번호" maxLength="11" value={userInfo.phoneNumber} />
                            </div>
                            <div className="m-2">
                                <p className={`text-muted ${styles.warningText}`}>
                                     회원정보 변경은 마이페이지에서 가능합니다.
                                </p>
                            </div>
Jiwon Yoon's avatar
Jiwon Yoon committed
250
251
252
253
                        </div>
                        :
                        <div>
                            <h5 className="mb-4 p-2" style={{ backgroundColor: "white", color: "black" }}>비회원예매 정보입력</h5>
한규민's avatar
한규민 committed
254
255
256
257
258
259
                            <div className="d-flex flex-column">
                                <div className="my-1">
                                    <label className={styles.labelStyle}>이름</label>
                                    <input type="text" name="name" placeholder="이름" onChange={handleChangeGuest} />
                                </div>
                                {errorMsg.errorName && <p className={styles.errorMsg}>이름을 입력해주세요</p>}
Jiwon Yoon's avatar
Jiwon Yoon committed
260
                            </div>
한규민's avatar
한규민 committed
261
262
263
264
265
266
                            <div className="d-flex flex-column">
                                <div className="my-1">
                                    <label className={styles.labelStyle}>이메일</label>
                                    <input type="email" name="email" placeholder="이메일" onChange={handleChangeGuest} />
                                </div>
                                {errorMsg.errorEmail && <p className={styles.errorMsg}>이메일을 입력해주세요</p>}
Jiwon Yoon's avatar
Jiwon Yoon committed
267
                            </div>
한규민's avatar
한규민 committed
268
269
270
271
272
273
                            <div className="d-flex flex-column">
                                <div className="my-1">
                                    <label className={styles.labelStyle}>생년월일</label>
                                    <input type="number" name="birth" placeholder="생년월일" onChange={handleChangeGuest} maxLength="6" />
                                </div>
                                {errorMsg.errorBirthday && <p className={styles.errorMsg}>숫자 6자리를 입력해주세요.</p>}
Jiwon Yoon's avatar
Jiwon Yoon committed
274
                            </div>
한규민's avatar
한규민 committed
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
                                <div className="d-flex flex-column">
                                <div className="my-1">
                                    <label className={styles.labelStyle}>휴대폰 번호</label>
                                    <input type="number" name="phoneNumber" placeholder="휴대폰 번호" onChange={handleChangeGuest} maxLength="11" />
                                    <button type="button" disabled={loading} className={`rounded-2 mt-2 ${styles.butterYellowAndBtn} ${styles.btnHover}`} data-bs-toggle="collapse" data-bs-target="#collapseExample" aria-expanded="false" aria-controls="collapseExample" onClick={handleOnClickMbnum}>인증번호받기</button>
                                </div>
                                {errorMsg.errorMbnum && <p className={styles.errorMsg}>-없이 숫자 11자리를 입력해주세요.</p>}
                                <div className="collapse" id="collapseExample">
                                    <div className="d-flex justify-content-center align-items-center mt-3">
                                        <label className={styles.labelStyle}>인증하기</label>
                                        <div>
                                            <input className={`${styles.input} ${styles.input2}`} type="number" placeholder="인증번호를 입력" onChange={handleOnChangeMb} />
                                            <button type="button" className={`rounded-2 py-2 ${styles.butterYellowAndBtn} ${styles.btnHover}`} onClick={handleOnClickMbConfirm}>확인</button>
                                            <button type="button" className={`rounded-2 py-2 ${styles.butterYellowAndBtn} ${styles.btnHover}`} onClick={handleOnClickMbnum}>재전송</button>
                                        </div>
                                    </div>
                                    {(mbError === "재전송") && <p className={styles.errorMsg}>유효시간이 만료되었습니다. 재전송해주세요.</p>}
                                    {(mbError === "보냄") && <p className={styles.errorMsg}>5분이내에 입력해주세요.</p>}
                                    {(mbError === "성공") && <p className={styles.errorMsg}>인증되었습니다.</p>}
                                    {(mbError === "실패") && <p className={styles.errorMsg}>인증번호를 다시 입력해주세요.</p>}
                                </div>
Jiwon Yoon's avatar
Jiwon Yoon committed
296
                            </div>
한규민's avatar
한규민 committed
297
298
299
300
301
302
                            <div className="d-flex flex-column">
                                <div className="my-1">
                                    <label className={styles.labelStyle}>비밀번호</label>
                                    <input type="password" name="password" placeholder="비밀번호" onChange={handleChangeGuest} style={{ width: "178px" }} />
                                </div>
                                {errorMsg.errorPassword && <p className={styles.errorMsg}>8~11자리 사이로 입력해주세요.</p>}
Jiwon Yoon's avatar
Jiwon Yoon committed
303
                            </div>
한규민's avatar
한규민 committed
304
305
306
307
308
309
310
                            <div className="d-flex flex-column">
                                <div className="my-1">
                                    <label className={styles.labelStyle}>비밀번호 확인</label>
                                    <input type="password" name="rePassword" placeholder="비밀번호 확인" onChange={handleChangeGuest} style={{ width: "178px" }} />
                                </div>
                            </div>

Jiwon Yoon's avatar
Jiwon Yoon committed
311
312
313
314
315
316
317
318
319
                            <div className="m-2">
                                <p className={`text-muted ${styles.warningText}`}>
                                     비회원 정보 오기입  예매 내역 확인/취소  티켓 발권이 어려울  있으니 다시 한번 확인해 주시기 바랍니다.
                                </p>
                            </div>
                            <button className="btn btn-warning mb-3" type="button" style={{ width: "100%" }} onClick={handleClickGuest}>비회원 정보 저장</button>
                        </div>
                    }
                    <h5 className="my-4 p-2" style={{ backgroundColor: "white", color: "black" }}>결제방법</h5>
320
321
322
323
324
                    <img src="/images/naverpay_button.png" style={{ width: "150px" }} />
                    <button onClick={kakaoBtnClick} style={{ backgroundColor: "black", border: '0' }}>
                        <img src="/images/payment_icon_yellow_medium.png" style={{ width: "130px" }} />
                    </button>
                    {element}
Jiwon Yoon's avatar
Jiwon Yoon committed
325
                    <div className="my-5">
326
                        <button className="btn btn-warning" type="button" style={{ width: "100%" }} onClick={reservationComplete}>결제하기</button>
Jiwon Yoon's avatar
Jiwon Yoon committed
327
328
329
330
331
332
333
334
335
                    </div>
                </div>

                <div className="col-sm-4">
                    <div className="text-center rounded-3 p-3" style={{ backgroundColor: "#252525" }}>
                        <img style={{ maxHeight: "10rem" }} src={`https://image.tmdb.org/t/p/original${ticketInfo.poster_path}`} alt="영화포스터" />
                        <h5 className="my-3">{ticketInfo.title}</h5>
                        <div>{ticketInfo.cinema}</div>
                        <div>{ticketInfo.time}</div>
Jiwon Yoon's avatar
Jiwon Yoon committed
336
                        <div className="mb-3">{ticketInfo.selectedTheater} {ticketInfo.selectedSeats.map(el => String.fromCharCode(parseInt(el.split('-')[0]) + 64) + el.split('-')[1]) + ' '}</div>
Jiwon Yoon's avatar
Jiwon Yoon committed
337
338
                        <div className="rounded-3 p-3" style={{ backgroundColor: '#404040' }}>
                            <div>성인: {ticketInfo.adult}</div>
339
340
341
                            <div>청소년: {ticketInfo.youth}</div>
                            <div>경로우대: {ticketInfo.senior}</div>
                            <div className="mt-2"> 결제금액: {ticketInfo.totalFee}</div>
Jiwon Yoon's avatar
Jiwon Yoon committed
342
343
344
345
346
347
348
349
350
351
                        </div>
                    </div>
                </div>
            </div>

        </div>
    )
}

export default Payment