PayResult.js 18.9 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 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 51 52 53 54 55 56 57 58 59 60 61 62 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 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 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 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 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 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 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 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 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 383 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 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575
/**
 * Created by mac on 2017/5/14.
 */
import React, {Component} from "react";
import {Alert, Image, StyleSheet, Text, TouchableOpacity, View,NativeModules,Linking,Platform} from "react-native";
import NavBar from "../NavBar/NavBar";
import {isIphoneX, NoDoublePress, xnToast} from "../../utils/utils";
import {pay} from "react-native-alipay";
import * as NativeAlipay from "react-native-alipay";
import * as Wechat from "./wechat.js";
import AppService from "../../service/AppService";
import LoadingView from '../component/LoadingView';
import PropTypes from 'prop-types';
 // var Wechat = NativeModules.Wechat;
//支付页面点点滴滴
const wechat = require("../../img/weixinqianbao.png");
const alipay = require('../../img/zhifubao.png');

const xuanze_no = require('../../img/xuanze-02.png');

const xuanze_select = require("../../img/xuanze-01.png");

const item = [
  {icon: alipay, type: "ALIPAY", text: "支付宝支付"},
  // {icon: wechat, type: "WECHAT", text: "微信支付"}
];
const __IOS__ = Platform.OS == "ios";

export default class PayResult extends Component {
  // static contextTypes = {
  //   navigator: PropTypes.object,
  // };
  static navigationOptions = ({navigation, screenProps}) => ({
    header: null
  });

  payCon = (v, i) => {
    if (i === 0) {
      return (
        <TouchableOpacity style={[styles.pay, styles.borderBottomVisi]} key={i}
                          onPress={() => this.setState({type: v.type})}>
          <View style={styles.leftPay}>
            <Image
              source={v.icon}
              style={styles.iconPay}
              resizeMode="contain"
            />
            <Text style={styles.font5}>{v.text}</Text>
          </View>
          <View style={styles.rightPay}>
            {
              this.state.type === v.type ?
                <Image
                  source={xuanze_select}
                  resizeMode="contain"
                />
                :
                <Image
                  source={xuanze_no}
                  resizeMode="contain"
                />
            }
          </View>
        </TouchableOpacity>
      )
    }
    return (
      <TouchableOpacity style={[styles.pay, styles.borderBottomVisi]} key={i}
                        onPress={() => this.setState({type: v.type})}>
        <View style={styles.leftPay}>
          <Image
            source={v.icon}
            style={styles.iconPay}
            resizeMode="contain"
          />
          <Text style={styles.font5}>{v.text}</Text>
        </View>
        <View style={styles.rightPay}>
          {
            this.state.type === v.type ?
              <Image
                source={xuanze_select}
                resizeMode="contain"
              />
              :
              <Image
                source={xuanze_no}
                resizeMode="contain"
              />
          }
        </View>
      </TouchableOpacity>
    )
  };
  info = () => {
    return (
      <View style={styles.info}>
        <View style={[styles.infoitem, styles.borderBottomVisi]}>
          <Text style={styles.font1}>课程</Text>
          <Text style={styles.font2} numberOfLines={1}>{this.props.navigation.state.params.course.name}</Text>
        </View>
        <View style={[styles.infoitem, styles.borderBottomVisi]}>
          <Text style={styles.font1}>课次</Text>
          <Text style={styles.font2}>{this.props.navigation.state.params.lessonCount}课次</Text>
        </View>
        <View style={styles.infoitem}>
          <Text style={styles.font1}>价格</Text>
          <View style={styles.rightCon}>
            <Text style={styles.font3}>¥</Text>
            <Text style={styles.font4}>{this.props.navigation.state.params.course.salePrice}</Text>
          </View>
        </View>
      </View>
    )
  };
  buyClass = () => {
    let that = this;
    let url = '';
    if (this.state.type === "ALIPAY"){
      url = Platform.OS == "ios"? 'alipay://':'alipays://platformapi/startApp';
    }else {
      url = 'weixin://'
    }

    Linking.canOpenURL(url).then(supported => {
      if (!supported) {
        if (that.state.type === "ALIPAY"){
          xnToast('未安装支付宝');
        }else {
          xnToast('未安装微信');
        }

      } else {
        that.setState({loading:true});
        // 对课程进行下单
        // 1087985315550986240是测试环境开的门店!!!
        var _shopId = '1087985315550986240';
        if(global.appTarget == 'xntalkTest' || global.appTarget == 'fang'){
          _shopId = '1087985315550986240';
        }
        // 芳聊的门店
        if(global.appTarget == 'fangPartner'){
          _shopId = '1101420857298911232';
        }

        AppService.coursePurchaseRequest({courseId:this.props.navigation.state.params.course.id,payType:this.state.type,shopId:_shopId,appTarget:global.appTarget}).then((data) => {
          that.setState({loading:false});
          if (data.message) {
            xnToast(data.message);
            return;
          }
          if (data.errors.length > 0) {
            xnToast(data.errors[0].message);
          } else {
            if (this.state.type === "ALIPAY") {
              console.log("----alipayOrderString------",data.alipayOrderString);
              // 启动支付宝进行付款
              NativeAlipay.pay(data.alipayOrderString, true).then(result => {
                let alipayResult = JSON.parse(result.result);
                let lineList = [{
                  type:"THIRD",
                  payType:this.state.type,
                  payOrderId:data.order.id,
                  payAccount:"ALIPAY",
                  amount:alipayResult.alipay_trade_app_pay_response.total_amount,
                  // lineInfo:{responseText:result.result}
                }];

                if (result.resultStatus === '9000') {
                  xnToast("付款成功,正在确认订单");

                  // 调用后台支付接口
                  AppService.courseOrderPayRequest({id:data.paymentId,orderId:data.order.id,totalAmount:data.order.totalAmount,lineList:lineList}).then((data1) => {
                    if (data1.message) {
                      xnToast(data1.message);
                      return;
                    }
                    if (data1.errors.length > 0) {
                      xnToast(data1.errors[0].message);
                    } else {
                      Alert.alert('提示', '付款成功');
                      that.props.navigation.state.params.buy();
                      that.props.navigation.goBack();
                      // that.props.navigation.replace('ClassGrade',{
                      //   id:this.props.navigation.state.params.course.id
                      // });
                    }
                  }).catch(error => {
                    xnToast(error);
                  });

                } else if (result.resultStatus === '8000') {
                  Alert.alert('提示', '支付结果确认中,请稍后查看您的账户确认支付结果');

                } else if (result.resultStatus !== '6001') {
                  // 如果用户不是主动取消
                  Alert.alert('提示', '支付失败'+alipayResult.alipay_trade_app_pay_response.sub_msg);

                }
              });
            } else if (this.state.type === "WECHAT") {
              let that = this;
              // 启动微信进行付款
              try{
                Wechat.pay(JSON.parse(data.wechatOrderString)).then(result => {
                  // 调用后台支付接口
                  let lineList = [{
                    type:"THIRD",
                    payType:this.state.type,
                    payOrderId:data.order.id,
                    payAccount:"WECHAT",
                    amount:data.order.totalAmount,
                    lineInfo:JSON.stringify({responseText:result})
                  }];

                  AppService.courseOrderPayRequest({id:data.paymentId,orderId:data.order.id,totalAmount:data.order.totalAmount,lineList:lineList}).then((data1) => {
                    if (data1.message) {
                      xnToast(data1.message);
                      return;
                    }
                    if (data1.errors.length > 0) {
                      xnToast(data1.errors[0].message);
                    } else {
                      Alert.alert('提示', '付款成功');
                      that.props.navigation.state.params.buy();
                      that.props.navigation.goBack();
                      // that.props.navigation.replace('ClassGrade',{
                      //   id:this.props.navigation.state.params.course.id
                      // });
                    }
                  }).catch(error => {
                    xnToast(error);
                  });

                  // let payRequest = new CourseOrderPayRequest();
                  // payRequest.setId(data.paymentId);
                  // payRequest.setOrderId(data.order.id);
                  // payRequest.setTotalAmount(data.order.totalAmount);
                  // let lineList = [{
                  //   type:"THIRD",
                  //   payType:this.state.type,
                  //   payOrderId:data.order.id,
                  //   payAccount:"WECHAT",
                  //   amount:data.order.totalAmount,
                  //   lineInfo:JSON.stringify({responseText:result})
                  // }];
                  // payRequest.setLineList(lineList);
                  // that.refs.appService.postRequest(payRequest, function (data) {
                  //
                  //   if (!!data.errors === true && !!data.errors.length > 0) {
                  //     xnToast(data.errors[0].message);
                  //   } else {
                  //     Alert.alert('提示', '付款成功');
                  //     that.props.buy();
                  //     that.context.navigator.replace({location: "/video/classgrade", passProps: {id: that.props.course.id}});
                  //   }
                  // }, false);

                }).catch(error => {});
              } catch (error){
              }
            } else {
              Alert.alert("购买失败:未知的付款方式");
            }
          }
        }).catch(error => {
          xnToast(error);
        });
      }
    }).catch(err => console.error('An error occurred', err));


    // let purchaseRequest = new CoursePurchaseRequest();
    // purchaseRequest.setCourseId(this.props.navigation.state.params.course.id);
    // purchaseRequest.setShopId(global.cache.union.sourceId);
    // purchaseRequest.setPayType(this.state.type);
    // post(purchaseRequest).then(data => {
    //   if (!!data.errors === true && !!data.errors.length > 0) {
    //     Toast.show(data.errors[0].message);
    //   } else {
    //     if (this.state.type === "ALIPAY") {
    //       // 启动支付宝进行付款
    //       NativeAlipay.pay(data.alipayOrderString, true).then(result => {
    //         let alipayResult = JSON.parse(result.result);
    //
    //         if (result.resultStatus === '9000') {
    //           Toast.show("付款成功,正在确认订单");
    //
    //           // 调用后台支付接口
    //           let payRequest = new CourseOrderPayRequest();
    //           payRequest.setId(data.paymentId);
    //           payRequest.setOrderId(data.order.id);
    //           payRequest.setTotalAmount(data.order.totalAmount);
    //           let lineList = [{
    //             type:"THIRD",
    //             payType:this.state.type,
    //             payOrderId:data.order.id,
    //             payAccount:"ALIPAY",
    //             amount:alipayResult.alipay_trade_app_pay_response.total_amount,
    //             // lineInfo:{responseText:result.result}
    //           }];
    //
    //           payRequest.setLineList(lineList);
    //           this.refs.appService.postRequest(payRequest, function (data) {
    //
    //               if (!!data.errors === true && !!data.errors.length > 0) {
    //                   Toast.show(data.errors[0].message);
    //               } else {
    //                   that.props.buy();
    //                   that.context.navigator.replace({location: "/video/classgrade", passProps: {id: that.props.course.id}});
    //               }
    //
    //           }, false);
    //         } else if (result.resultStatus === '8000') {
    //           Alert.alert('提示', '支付结果确认中,请稍后查看您的账户确认支付结果');
    //
    //         } else if (result.resultStatus !== '6001') {
    //           // 如果用户不是主动取消
    //           Alert.alert('提示', '支付失败'+alipayResult.alipay_trade_app_pay_response.sub_msg);
    //
    //         }
    //       });
    //     } else if (this.state.type === "WECHAT") {
    //       let that = this;
    //       // 启动微信进行付款
    //       try{
    //         Wechat.pay(JSON.parse(data.wechatOrderString)).then(result => {
    //           // 调用后台支付接口
    //           let payRequest = new CourseOrderPayRequest();
    //           payRequest.setId(data.paymentId);
    //           payRequest.setOrderId(data.order.id);
    //           payRequest.setTotalAmount(data.order.totalAmount);
    //           let lineList = [{
    //             type:"THIRD",
    //             payType:this.state.type,
    //             payOrderId:data.order.id,
    //             payAccount:"WECHAT",
    //             amount:data.order.totalAmount,
    //             lineInfo:JSON.stringify({responseText:result})
    //           }];
    //           payRequest.setLineList(lineList);
    //           that.refs.appService.postRequest(payRequest, function (data) {
    //
    //             if (!!data.errors === true && !!data.errors.length > 0) {
    //               Toast.show(data.errors[0].message);
    //             } else {
    //               Alert.alert('提示', '付款成功');
    //               that.props.buy();
    //               that.context.navigator.replace({location: "/video/classgrade", passProps: {id: that.props.course.id}});
    //             }
    //           }, false);
    //
    //         }).catch(error => {
    //         });
    //       } catch (error){
    //       }
    //     } else {
    //       Alert.alert("购买失败:未知的付款方式");
    //     }
    //   }
    // });
  };

  callWechat (data) {
    // Wechat.pay({
    //   partnerId:"",   // 商家向财付通申请的商家id
    //   prepayId: '',   // 预支付订单
    //   nonceStr: '',   // 随机串,防重发
    //   timeStamp: '',  // 时间戳,防重发
    //   package: '',    // 商家根据财付通文档填写的数据和签名
    //   sign: ''        // 商家根据微信开放平台文档对数据做的签名
    // }).then(data=>{
    //
    // })

    try {
      // let req = {
      //   partnerId: data.partnerId,  // 商家向财付通申请的商家id
      //   prepayId: data.prepayId,    // 预支付订单
      //   nonceStr: data.nonceStr,    // 随机串,防重发
      //   timeStamp: data.timeStamp,  // 时间戳,防重发
      //   package: 'WXPay',           // 商家根据财付通文档填写的数据和签名
      //   sign: data.sign             // 商家根据微信开放平台文档对数据做的签名
      // };
      // console.warn(JSON.stringify(req));
      // Wechat.pay(data).then(result => {
      //   console.warn("完成")
      //   console.warn(JSON.stringify(result));
      // }).catch(error => {
      //   console.warn("异常")
      //   console.warn(error);
      // })
    }
    catch (error){
      console.warn(JSON.stringify(error));
    }
  }

  constructor(props) {
    super(props);
    this.state = {
      type: "ALIPAY",
      loading:false
    }
  }

  componentDidMount (){
     // Wechat.registerApp('wxbf8b4b97e9ca4e41');
    // 这个基于犀牛企业云测试环境
    Wechat.registerApp('wxa20ad2e448ad43dd');

  }

  render() {
    return (
      <View style={styles.container}>
        <NavBar
          renderBack
          noShadow
          nav={this.props.navigation}
        >

          <Text style={styles.fontTitle}>确认支付</Text>
        </NavBar>

        {this.info()}

        <View style={styles.payType}>
          <View style={[styles.title, styles.borderBottomVisi]}>
            <Text style={styles.font1}>请选择支付方式</Text>
          </View>
          {
            item.map((v, i) => this.payCon(v, i))
          }
        </View>

        <View style={styles.ps}>
          <Text style={styles.fontps1}>温馨提示:</Text>
          <Text style={styles.fontps2}>课程购买后,不可以退款哦</Text>
        </View>
        <View style={styles.bottomBtn}>
          <TouchableOpacity style={styles.redBtn} onPress={()=>NoDoublePress.onPress(()=>this.buyClass())}>
            <Text style={styles.fontBtnBuy}>立即购买</Text>
          </TouchableOpacity>
        </View>
        {this.state.loading && (
            <LoadingView/>
        )}
      </View>
    )
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'rgb(239,240,241)',
    marginTop: __IOS__ ? isIphoneX()? 44:20 : 0
  },
  fontTitle: {
    fontSize: 16,
    fontWeight: 'bold'
  },
  info: {
    marginTop: 10
  },
  fontLogin: {
    fontSize: 16,
    fontWeight: 'bold'
  },
  infoitem: {
    paddingLeft: 15,
    paddingRight: 15,
    alignItems: 'center',
    flexDirection: 'row',
    justifyContent: 'space-between',
    height: 44,
    backgroundColor: 'white'
  },
  borderBottomVisi: {
    borderWidth: 1,
    borderLeftWidth: 0,
    borderTopWidth: 0,
    borderBottomWidth: 1,
    borderRightWidth: 0,
    borderColor: '#dddddd'
  },
  font1: {
    fontSize: 14,
    color: '#999'
  },
  font2: {
    fontSize: 14,
    color: "#333",
    marginLeft:10,
    marginRight:10
  },
  font3: {
    fontSize: 12,
    color: "#e52d43"
  },
  font4: {
    fontSize: 18,
    color: "#e52d43"
  },
  rightCon: {
    flexDirection: "row",
    alignItems: 'flex-end'
  },
  payType: {
    marginTop: 10
  },
  title: {
    height: 44,
    backgroundColor: 'white',
    alignItems: 'center',
    flexDirection: 'row',
    paddingLeft: 15
  },
  pay: {
    height: 60,
    alignItems: 'center',
    paddingLeft: 15,
    paddingRight: 15,
    justifyContent: 'space-between',
    flexDirection: 'row',
    backgroundColor: 'white'
  },
  iconPay: {
    width: 40,
    height: 40
  },
  leftPay: {
    flexDirection: 'row',
    alignItems: 'center'
  },
  font5: {
    fontSize: 16,
    color: '#333',
    marginLeft: 5
  },
  ps: {
    flex: 1,
    paddingLeft: 15
  },
  bottomBtn: {
    height: 50,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: 'white'
  },
  redBtn: {
    width: 100,
    height: 33,
    borderRadius: 15,
    backgroundColor: "#e52d43",
    alignItems: 'center',
    justifyContent: 'center'
  },
  fontBtnBuy: {
    fontSize: 14,
    color: 'white'
  },
  fontps1: {
    fontSize: 20,
    color: '#333',
    fontWeight: 'bold',
    marginTop: 25,
    marginBottom: 5
  },
  fontps2: {
    marginTop: 5,
    fontSize: 14,
    color: "#999"
  }
});