PayOrder.js 19.9 KB
Newer Older
wangshuo committed
1
import React, { Component } from 'react';
zhanghaozhe committed
2 3
import { Flex, WingBlank, WhiteSpace, List, Radio, Toast } from 'antd-mobile';
import { http, getParam, is_weixin, browser } from '@/utils';
4
import { OrderItem, HeaderBar } from '@/common/index';
wangshuo committed
5
import { Link } from 'react-router-dom';
wangshuo committed
6
import './PayOrder.scss';
wangshuo committed
7
import { VList } from '@/common';
wangshuo committed
8

xuzhenghua committed
9

wangshuo committed
10 11 12 13
const Item = List.Item;
const Brief = Item.Brief;
const RadioItem = Radio.RadioItem;

xuzhenghua committed
14
let mockData = []
zhanghaozhe committed
15
if (browser.isWeixin) {
xuzhenghua committed
16
    mockData = [
zhanghaozhe committed
17
        {value: 1, label: '微信支付', icon: 'iconweixinzhifu'}
xuzhenghua committed
18 19 20
    ];
} else {
    mockData = [
zhanghaozhe committed
21
        {value: 1, label: '微信支付', icon: 'iconweixinzhifu'},
wangshuo committed
22
        {value: 0, label: '支付宝', icon: 'iconalipay'},
xuzhenghua committed
23 24 25 26 27
        // { value: 2, label: '花呗分期', icon: 'iconhuabei' },
    ];
}


wangshuo committed
28 29 30 31
export default class PayOrder extends Component {
    constructor(props) {
        super(props);
        this.state = {
wangshuo committed
32
            pay_amount: 0,
wangshuo committed
33
            payType: 1,
wangshuo committed
34
            stageNumber: 0,
35 36 37
            checkPeriod: false,
            singleMoney: 0,
            periodNumber: 0,
wangshuo committed
38 39 40
            orderId: getParam('oid'),
            huabei: false,
            fenqiList: [
zhanghaozhe committed
41 42 43
                {value: 'zhifubao', qishu: '3', lilv: '2.30%', everyMoney: 300, feiyong: 2.3},
                {value: 'weixin', qishu: '6', lilv: '4.50%', everyMoney: 150, feiyong: 4.5},
                {value: 'huabei', qishu: '9', lilv: '7.50%', everyMoney: 100, feiyong: 7.5},
wangshuo committed
44 45
            ],
            categoryList: [],
wangshuo committed
46 47
        }
    }
xuzhenghua committed
48 49 50 51 52 53 54

    // 支付成功后,判断并重定向
    redirectAfterPay = () => {
        // status:0成功,1失败
        const status = getParam('status');
        const type = getParam('type');
        const oid = getParam('oid');
zhanghaozhe committed
55 56 57
        const {history} = this.props;
        if (status || type) {
            if (parseInt(status, 10) === 0) {
xuzhenghua committed
58
                // type订单类型 0普通订单 1团购 2小团 3砍价 4单集购买 5定金课定金 6定金课尾款
zhanghaozhe committed
59
                if (parseInt(type, 10) === 2) {
xuzhenghua committed
60
                    history.push(`/togroup?id=${oid}`);
FE committed
61 62 63 64
                }else if(parseInt(type, 10) === 4) {
                courseId && window.localStorage.setItem('payCourse', courseId);
                    const courseId = window.localStorage.getItem('payCourse')
                    courseId && history.push(`/detail?id=${courseId}`,{oid});
zhanghaozhe committed
65
                } else {
xuzhenghua committed
66 67
                    history.push('/purchased');
                }
zhanghaozhe committed
68
            } else {
xuzhenghua committed
69 70 71 72 73
                Toast.info('支付异常', 2);
            }
        }
    }

wangshuo committed
74 75
    onChange = (value) => {
        this.setState({
wangshuo committed
76 77
            payType: value,
            checkPeriod: false,
wangshuo committed
78
        });
wangshuo committed
79 80 81 82 83
        if (value === 2) {
            this.setState({
                huabei: true,
            });
        }
wangshuo committed
84
    };
wangshuo committed
85
    checkStaging = (item) => {
86
        // console.log(item);
wangshuo committed
87 88 89 90 91 92 93 94
        this.setState({
            huabei: false,
            stageNumber: item.value,
            singleMoney: item.everyTotal,
            periodNumber: item.stage,
            checkPeriod: true,
        });
    }
wangshuo committed
95 96
    print = (...e) => {
        console.log(e);
wangshuo committed
97 98 99 100
    };
    // 确定购买
    pay = () => {
        const {payType, orderId} = this.state;
zhanghaozhe committed
101
        if (payType === 0) {
wangshuo committed
102
            this.alipayPay(orderId);
wangshuo committed
103 104
        } else if (payType === 1) {
            this.weixinPay(orderId)
xuzhenghua committed
105
        }
wangshuo committed
106 107 108 109 110 111 112 113
        // else { // 花呗分期暂时不做
        //     this.huabeiPay(orderId)
        // }
    }
    // 微信支付
    weixinPay = (orderId) => {
        // 微信内部-支付
        if (is_weixin()) {
wangshuo committed
114
            window.location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx23dac6775ac82877&redirect_uri=" + encodeURIComponent(window.location.href + "&aa=bb").toLowerCase() + "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
xuzhenghua committed
115 116 117 118 119 120 121 122 123
            // if(window.location.href.indexOf('aa=bb') === -1){
            //     localStorage.setItem('a', '第一次');
            //     window.location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx23dac6775ac82877&redirect_uri=" + encodeURIComponent(window.location.href + "&aa=bb").toLowerCase() + "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
            // }
            // if(window.location.href.indexOf('aa=bb') > 0) {
            //     localStorage.setItem('a', '多次');
            //     let newHref = window.location.href.slice(0, window.location.href.indexOf('aa=bb')-1);
            //     window.location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx23dac6775ac82877&redirect_uri=" + encodeURIComponent(newHref + "&aa=bb").toLowerCase() + "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
            // }
wangshuo committed
124 125
        } else {
            // 微信外部-支付
zhanghaozhe committed
126
            http.get(`${API['base-api']}/pay/wxpay/wap_charge/oid/${orderId}`).then((res) => {
127
                // console.log(res);
wangshuo committed
128
                if (res.data.errno === 0) {
wangshuo committed
129
                    window.location.href = res.data.data.url + "&redirect_url=" + encodeURIComponent(window.location.href + "&weixinpay=1").toLowerCase();
wangshuo committed
130
                } else {
wangshuo committed
131
                    Toast.info(res.data.msg, 2)
wangshuo committed
132 133 134 135 136 137
                }
            })
        }
    }
    // 微信内部支付
    isweixinPay = () => {
wangshuo committed
138 139
        let _this = this;
        let weixin_code = getParam('code');
wangshuo committed
140 141 142 143
        if (weixin_code) {
            if (getParam('oid') === undefined) {
                return
            } else {
zhanghaozhe committed
144
                http.get(`${API['base-api']}/pay/wxpay/pub_charge/oid/${getParam('oid')}/code/${weixin_code}`).then((res) => {
wangshuo committed
145
                    if (res.data.errno === 0) {
wangshuo committed
146
                        let data = res.data.data;
zhanghaozhe committed
147

wangshuo committed
148 149 150
                        function onBridgeReady() {
                            WeixinJSBridge.invoke(
                                'getBrandWCPayRequest', {
zhanghaozhe committed
151 152 153 154 155 156
                                    appId: data.appId,                //公众号名称,由商户传入
                                    timeStamp: data.timeStamp,        //时间戳,自1970年以来的秒数
                                    nonceStr: data.nonceStr,          //随机串
                                    package: data.package,
                                    signType: data.signType,          //微信签名方式:
                                    paySign: data.paySign             //微信签名
wangshuo committed
157 158 159 160
                                },
                                function (res) {
                                    if (res.err_msg == "get_brand_wcpay_request:ok") {
                                        Toast.info('支付成功', 2);
zhanghaozhe committed
161
                                        _this.intervalPayStatus = setInterval(function () {
wangshuo committed
162 163 164 165 166
                                            http.get(`${API['base-api']}/m/orderState/oid/${getParam('oid')}`).then(res => {
                                                if (res.data.errno === 401) {
                                                    clearInterval(_this.intervalPayStatus);
                                                    _this.intervalPayStatus = null;
                                                    // 获取课程类型
wangshuo committed
167
                                                    http.get(`${API['base-api']}/m/app_order/detail/${getParam('oid')}`).then(res => {
zhanghaozhe committed
168
                                                        if (Number(res.data.data.course_type) === 2) {
wangshuo committed
169
                                                            _this.props.history.replace(`/togroup?id=${getParam('oid')}`);
zhanghaozhe committed
170
                                                        } else {
wangshuo committed
171
                                                            // 跳转到已购课程  /purchased 不需要传递任何参数
wangshuo committed
172
                                                            _this.props.history.replace(`/purchased`);
wangshuo committed
173 174 175 176 177
                                                        }
                                                    });
                                                }
                                            })
                                        }, 1000)
wangshuo committed
178 179 180 181 182 183 184
                                    } else {
                                        alert('支付失败')
                                    }
                                }
                            )
                        }

wangshuo committed
185 186
                        if (typeof WeixinJSBridge == "undefined") {
                            if (document.addEventListener) {
wangshuo committed
187
                                document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false)
wangshuo committed
188
                            } else if (document.attachEvent) {
wangshuo committed
189 190
                                document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
                                document.attachEvent('onWeixinJSBridgeReady', onBridgeReady)
wangshuo committed
191 192
                            }
                        } else {
wangshuo committed
193
                            onBridgeReady();
wangshuo committed
194 195
                        }
                    } else {
wangshuo committed
196
                        Toast.info(res.data.msg, 2)
wangshuo committed
197 198 199 200 201 202 203
                    }
                })
            }
        }
    }
    // 支付完成之后获取状态
    payCallback = () => {
xuzhenghua committed
204 205 206
        const _this = this;
        // 支付回调
        // 定时器轮训获取订单状态
zhanghaozhe committed
207
        _this.intervalPayStatus = setInterval(function () {
wangshuo committed
208
            http.get(`${API['base-api']}/m/orderState/oid/${getParam('oid')}`).then(res => {
xuzhenghua committed
209 210 211 212
                if (res.data.errno === 401) {
                    clearInterval(_this.intervalPayStatus);
                    _this.intervalPayStatus = null;
                    // 获取课程类型
wangshuo committed
213
                    http.get(`${API['base-api']}/m/app_order/detail/${getParam('oid')}`).then(res => {
zhanghaozhe committed
214
                        if (Number(res.data.data.course_type) === 2) {
wangshuo committed
215
                            _this.props.history.replace(`/togroup?id=${getParam('oid')}`);
zhanghaozhe committed
216
                        } else {
xuzhenghua committed
217
                            // 跳转到已购课程  /purchased 不需要传递任何参数
wangshuo committed
218
                            _this.props.history.replace(`/purchased`);
xuzhenghua committed
219 220 221 222 223 224
                        }

                    });
                }
            })
        }, 1000)
wangshuo committed
225 226
    }

wangshuo committed
227
    onBridgeReady1 = (data) => {
wangshuo committed
228 229
        let _this = this;
        data = data || _this.BridgeData;
wangshuo committed
230

wangshuo committed
231 232
        WeixinJSBridge.invoke(
            'getBrandWCPayRequest', {
wangshuo committed
233
                "appId": "wx23dac6775ac82877",                //公众号名称,由商户传入
wangshuo committed
234 235 236 237 238 239 240 241
                "timeStamp": data.timeStamp,        //时间戳,自1970年以来的秒数
                "nonceStr": data.nonceStr,          //随机串
                "package": data.package,
                "signType": data.signType,          //微信签名方式:
                "paySign": data.paySign             //微信签名
            },
            function (res) {
                if (res.err_msg == "get_brand_wcpay_request:ok") {
wangshuo committed
242 243
                    Toast.info('支付成功', 2);
                    _this.payCallback();
wangshuo committed
244 245 246 247 248 249 250 251
                } else {
                    alert('支付失败')
                }
            }
        )
    }
    // 支付宝支付
    alipayPay = (orderId) => {
xuzhenghua committed
252
        http.get(`${API['base-api']}/pay/alipay/wap_charge_new/oid/${orderId}`).then((res) => {
wangshuo committed
253
            if (res.data.errno === 0) {
wangshuo committed
254
                this.payCallback();
wangshuo committed
255
                window.location = res.data.data.url;
wangshuo committed
256
            } else {
wangshuo committed
257
                Toast.info(res.data.msg, 2)
wangshuo committed
258 259 260 261 262 263
            }
        })
    }
    // 花呗分期 暂时不做
    huabeiPay = (orderId) => {
        const {singleMoney, periodNumber} = this.state;
xuzhenghua committed
264

265
        // console.log('花呗分期支付');
zhanghaozhe committed
266
        http.get(`/pay/alipay/wap_charge/oid/${orderId}/plat/{plat} /hb_num/${periodNumber}`).then(res => {
267
            // console.log(res);
wangshuo committed
268 269 270
            if (res.data.errno === 0) {
                window.location = res.data.data.url;
            } else {
wangshuo committed
271
                Toast.info(res.data.msg, 2)
wangshuo committed
272 273
            }
        });
wangshuo committed
274
    }
wangshuo committed
275 276

    componentDidMount() {
xuzhenghua committed
277
        this.redirectAfterPay()
xuzhenghua committed
278 279 280 281 282 283 284 285 286 287 288 289
        let data = {}
        if(this.props.location.state && this.props.location.state.group){
            data = {
                order_id: this.state.orderId,
                type: 2
            }
        } else {
            data = {
                order_id: this.state.orderId,
            }
        }
        http.post(`${API['base-api']}/m/order/detail`,data).then((res) => {
xuzhenghua committed
290
            if (res.data.errno !== 200) {
wangshuo committed
291
                Toast.info(res.data.msg, 2);
wangshuo committed
292
                return;
wangshuo committed
293
            }
zhanghaozhe committed
294
            const {course, pay_amount} = res.data.data;
wangshuo committed
295
            const fenqiList = [];
zhanghaozhe committed
296
            [1, 2, 3].map((item) => {
wangshuo committed
297 298
                let obj = {};
                obj.value = item;
zhanghaozhe committed
299
                if (item === 1) {
wangshuo committed
300 301 302
                    obj.stage = 3; //期数
                    obj.moneyRate = '2.30%'; // 分期费率展示
                    obj.rate = 0.023; // 分期费率计算
zhanghaozhe committed
303
                    obj.periodic = (pay_amount / 3).toFixed(2); // 每期本金
wangshuo committed
304 305 306 307
                } else if (item === 2) {
                    obj.stage = 6; //期数
                    obj.moneyRate = '4.50%'; // 分期费率展示
                    obj.rate = 0.045; // 分期费率计算
zhanghaozhe committed
308
                    obj.periodic = (pay_amount / 6).toFixed(2); // 每期本金
wangshuo committed
309 310 311 312
                } else {
                    obj.stage = 12; //期数
                    obj.moneyRate = '7.50%'; // 分期费率展示
                    obj.rate = 0.075; // 分期费率计算
zhanghaozhe committed
313
                    obj.periodic = (pay_amount / 9).toFixed(2); // 每期本金
wangshuo committed
314 315 316 317 318
                }
                obj.serviceFee = ((pay_amount * obj.rate) / obj.stage).toFixed(2); // 每期的手续费 = 总金额 * 费率 / 期数
                obj.everyTotal = (parseFloat(obj.periodic) + parseFloat(obj.serviceFee)).toFixed(2);// 每期总费用 = 每期本金 + 每期手续费
                fenqiList.push(obj);
            });
319
            // console.log(fenqiList);
wangshuo committed
320 321 322 323 324 325 326 327 328 329 330 331 332
            // { value: 'zhifubao',  qishu: '3', lilv: '2.30%', everyMoney: 300, feiyong: 2.3 },
            // { value: 'weixin',  qishu: '6', lilv: '4.50%', everyMoney: 150, feiyong: 4.5 },
            // { value: 'huabei',  qishu: '9', lilv: '7.50%', everyMoney: 100, feiyong: 7.5 },
            this.setState({
                pay_amount,
                categoryList: course,
                fenqiList,
            });
        });
        if (getParam('is_class') === 1 || getParam('weixinpay')) {
            this.payCallback()
        }
        if (is_weixin()) {
xuzhenghua committed
333 334 335
            this.setState({
                payType: 1
            })
wangshuo committed
336 337
            this.isweixinPay()
        }
wangshuo committed
338
    }
zhanghaozhe committed
339

wangshuo committed
340
    render() {
zhanghaozhe committed
341
        const {orderId, pay_amount, payType, checkPeriod, singleMoney, periodNumber, huabei, fenqiList, categoryList, stageNumber} = this.state;
wangshuo committed
342 343
        return (
            <div className='pay-order'>
344
                <HeaderBar title='确认支付' arrow={true}></HeaderBar>
wangshuo committed
345 346 347
                <WhiteSpace size='sm'></WhiteSpace>
                <div className='order-number'>
                    <WingBlank>
zhanghaozhe committed
348
                        <Flex justify='between' align='center' style={{height: '44px'}}>
wangshuo committed
349
                            <span>订单号</span>
wangshuo committed
350
                            <span className='number'>{orderId}</span>
wangshuo committed
351 352 353 354
                        </Flex>
                    </WingBlank>
                </div>
                <WhiteSpace size='md'></WhiteSpace>
355
                {
wangshuo committed
356
                    categoryList.map((item, index) => {
357 358 359 360 361 362 363 364 365 366 367 368 369
                        const Info = (
                            <div className="order-info">
                                <p className='order-title text-overflow-one'>
                                    <Link to={`/detail?id=${item.course_id}`}>{item.course_title}</Link>
                                </p>
                                <p className='order-content text-overflow-2'>{item.simpledescription}</p>
                                <p className='order-des'>
                                    <span className='order-newprice'>¥{item.price1}</span>
                                    <span className='order-price'>¥{item.price0}</span>
                                </p>
                            </div>
                        )
                        return (
wangshuo committed
370
                            <VList handleClick={this.print} key={index} img={item.image_name}
zhanghaozhe committed
371 372
                                   id={item.course_id}
                                   info={Info}></VList>
373 374 375 376
                        )
                    })
                }
                <WhiteSpace size='md'></WhiteSpace>
wangshuo committed
377 378
                <div className='order-number'>
                    <WingBlank>
zhanghaozhe committed
379
                        <Flex justify='between' align='center' style={{height: '44px'}}>
wangshuo committed
380
                            <span>支付金额</span>
wangshuo committed
381
                            <span className='money'>{`¥${pay_amount}`}</span>
wangshuo committed
382 383 384 385 386 387 388
                        </Flex>
                    </WingBlank>
                </div>

                <WhiteSpace size='md'></WhiteSpace>
                <List renderHeader={() => '支付方式'} className='pay-type-list'>
                    {mockData.map(i => (
wangshuo committed
389 390 391 392 393
                        <RadioItem
                            thumb={<i className={`iconfont ${i.icon} ${payType === i.value ? 'checked' : ''}`}></i>}
                            key={i.value}
                            checked={payType === i.value}
                            onChange={() => this.onChange(i.value)}>
394 395 396
                            {/* {i.label} */}
                            {
                                i.value === 2 ? (
zhanghaozhe committed
397 398 399 400
                                    <Flex direction='column' align='start' style={{width: '100%', marginTop: '6px'}}>
                                        <Flex direction='row' justify='between'
                                              style={{width: '100%', paddingRight: '30px'}}>
                                            <span style={{color: '#555555', fontSize: '14px'}}>{i.label}</span>
401 402
                                            {
                                                checkPeriod ? (
zhanghaozhe committed
403 404 405 406
                                                    <span style={{
                                                        color: '#333333',
                                                        fontSize: '12px'
                                                    }}>{`${singleMoney}元 × ${periodNumber}期`}</span>
407 408 409 410
                                                ) : null
                                            }
                                        </Flex>
                                        <Flex justify='start'>
zhanghaozhe committed
411
                                            <span style={{color: '#999999', fontSize: '12px'}}>支付上限受限于您的花呗额度</span>
412 413 414 415
                                        </Flex>
                                    </Flex>
                                ) : (i.label)
                            }
wangshuo committed
416 417 418
                        </RadioItem>
                    ))}
                </List>
xuzhenghua committed
419
                <div className='pay-tip'>请在15分钟内完成支付,否则届时系统将关闭该订单。</div>
wangshuo committed
420

wangshuo committed
421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
                <div className='pay-button' onClick={this.pay}>确认支付</div>

                {
                    huabei ? (
                        <div className='check-staging'>
                            <div className='container'>
                                <p className='check-title'>请选择分期</p>
                                {fenqiList.map(i => (
                                    <RadioItem
                                        key={i.value}
                                        checked={stageNumber === i.value}
                                        onChange={() => this.checkStaging(i)}>
                                        {`${i.everyTotal}元 × ${i.stage}期`}
                                        <List.Item.Brief>{`手续费${i.serviceFee}元/期,费率${i.moneyRate}`}</List.Item.Brief>
                                    </RadioItem>
                                ))}
                            </div>
                        </div>
                    ) : null
                }
wangshuo committed
441 442 443 444
            </div>
        )
    }
}