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

xuzhenghua committed
9

wangshuo committed
10 11
const RadioItem = Radio.RadioItem;

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


wangshuo committed
26
export default class PayOrder extends Component {
zhanghaozhe committed
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
  constructor(props) {
    super(props);
    this.state = {
      pay_amount: 0,
      payType: 1,
      stageNumber: 0,
      checkPeriod: false,
      singleMoney: 0,
      periodNumber: 0,
      orderId: getParam('oid'),
      huabei: false,
      fenqiList: [
        {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},
      ],
      categoryList: [],
wangshuo committed
44
    }
zhanghaozhe committed
45
  }
xuzhenghua committed
46

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

zhanghaozhe committed
72 73 74 75 76 77 78 79 80
  onChange = (value) => {
    this.setState({
      payType: value,
      checkPeriod: false,
    });
    if (value === 2) {
      this.setState({
        huabei: true,
      });
wangshuo committed
81
    }
zhanghaozhe committed
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
  };
  checkStaging = (item) => {
    // console.log(item);
    this.setState({
      huabei: false,
      stageNumber: item.value,
      singleMoney: item.everyTotal,
      periodNumber: item.stage,
      checkPeriod: true,
    });
  }
  print = (...e) => {
    console.log(e);
  };
  // 确定购买
  pay = () => {
    const {payType, orderId} = this.state;
    if (payType === 0) {
      this.alipayPay(orderId);
    } else if (payType === 1) {
      this.weixinPay(orderId)
wangshuo committed
103
    }
zhanghaozhe committed
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
    // else { // 花呗分期暂时不做
    //     this.huabeiPay(orderId)
    // }
  }
  // 微信支付
  weixinPay = (orderId) => {
    // 微信内部-支付
    if (browser.isWeixin) {
      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') === -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";
      // }
    } else {
      // 微信外部-支付
      http.get(`${API['base-api']}/pay/wxpay/wap_charge/oid/${orderId}`).then((res) => {
        // console.log(res);
        if (res.data.errno === 0) {
          window.location.href = res.data.data.url + "&redirect_url=" + encodeURIComponent(window.location.href + "&weixinpay=1").toLowerCase();
wangshuo committed
128
        } else {
zhanghaozhe committed
129
          Toast.info(res.data.msg, 2)
wangshuo committed
130
        }
zhanghaozhe committed
131
      })
wangshuo committed
132
    }
zhanghaozhe committed
133 134 135 136 137 138 139 140 141 142
  }
  // 微信内部支付
  isweixinPay = () => {
    let _this = this;
    let weixin_code = getParam('code');
    if (weixin_code) {
      if (getParam('oid') !== undefined) {
        http.get(`${API['base-api']}/pay/wxpay/pub_charge/oid/${getParam('oid')}/code/${weixin_code}`).then((res) => {
          if (res.data.errno === 0) {
            let data = res.data.data;
zhanghaozhe committed
143

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

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

zhanghaozhe committed
218
          });
xuzhenghua committed
219
        }
zhanghaozhe committed
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
      })
    }, 1000)
  }

  onBridgeReady1 = (data) => {
    let _this = this;
    data = data || _this.BridgeData;

    WeixinJSBridge.invoke(
      'getBrandWCPayRequest', {
        "appId": "wx23dac6775ac82877",                //公众号名称,由商户传入
        "timeStamp": data.timeStamp,        //时间戳,自1970年以来的秒数
        "nonceStr": data.nonceStr,          //随机串
        "package": data.package,
        "signType": data.signType,          //微信签名方式:
        "paySign": data.paySign,             //微信签名
      },
      function (res) {
        // eslint-disable-next-line eqeqeq
        if (res.err_msg == "get_brand_wcpay_request:ok") {
          Toast.info('支付成功', 2);
          _this.payCallback();
        } else {
          alert('支付失败')
wangshuo committed
244
        }
zhanghaozhe committed
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
      },
    )
  }
  // 支付宝支付
  alipayPay = (orderId) => {
    http.get(`${API['base-api']}/pay/alipay/wap_charge_new/oid/${orderId}`).then((res) => {
      if (res.data.errno === 0) {
        this.payCallback();
        window.location = res.data.data.url;
      } else {
        Toast.info(res.data.msg, 2)
      }
    })
  }
  // 花呗分期 暂时不做
  huabeiPay = (orderId) => {
    const {periodNumber} = this.state;

    // console.log('花呗分期支付');
    http.get(`/pay/alipay/wap_charge/oid/${orderId}/plat/{plat} /hb_num/${periodNumber}`).then(res => {
      // console.log(res);
      if (res.data.errno === 0) {
        window.location = res.data.data.url;
      } else {
        Toast.info(res.data.msg, 2)
      }
    });
  }

  componentDidMount() {
    this.redirectAfterPay()
    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) => {
      if (res.data.errno !== 200) {
        Toast.info(res.data.msg, 2);
        return;
      }
      const {course, pay_amount} = res.data.data;
      const fenqiList = [];
      [1, 2, 3].forEach((item) => {
        let obj = {};
        obj.value = item;
        if (item === 1) {
          obj.stage = 3; //期数
          obj.moneyRate = '2.30%'; // 分期费率展示
          obj.rate = 0.023; // 分期费率计算
          obj.periodic = (pay_amount / 3).toFixed(2); // 每期本金
        } else if (item === 2) {
          obj.stage = 6; //期数
          obj.moneyRate = '4.50%'; // 分期费率展示
          obj.rate = 0.045; // 分期费率计算
          obj.periodic = (pay_amount / 6).toFixed(2); // 每期本金
        } else {
          obj.stage = 12; //期数
          obj.moneyRate = '7.50%'; // 分期费率展示
          obj.rate = 0.075; // 分期费率计算
          obj.periodic = (pay_amount / 9).toFixed(2); // 每期本金
wangshuo committed
312
        }
zhanghaozhe committed
313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
        obj.serviceFee = ((pay_amount * obj.rate) / obj.stage).toFixed(2); // 每期的手续费 = 总金额 * 费率 / 期数
        obj.everyTotal = (parseFloat(obj.periodic) + parseFloat(obj.serviceFee)).toFixed(2);// 每期总费用 = 每期本金 + 每期手续费
        fenqiList.push(obj);
      });
      // console.log(fenqiList);
      // { 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 (browser.isWeixin) {
      this.setState({
        payType: 1,
      })
      this.isweixinPay()
wangshuo committed
335
    }
zhanghaozhe committed
336
  }
zhanghaozhe committed
337

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

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

zhanghaozhe committed
419
        <div className='pay-button' onClick={this.pay}>确认支付</div>
wangshuo committed
420

zhanghaozhe committed
421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
        {
          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>
wangshuo committed
436
            </div>
zhanghaozhe committed
437 438 439 440 441
          ) : null
        }
      </div>
    )
  }
wangshuo committed
442
}