react native 原生js整理数据结构 收银付款

React Native 版本执行0.57的规则

在这里插入图片描述


import React, { Component } from 'react';
import { StyleSheet, Text, View, ScrollView, Image, TouchableOpacity, StatusBar, BackHandler } from 'react-native';
import Nav from '../../components/Nav';
import { global } from '../../utils/Global';
import { requestUrl } from '../../network/Url';// 请求url
import Loading from '../../components/Loading';
import Fetch from '../../network/Fetch';
import * as WeChat from '../../utils/WeChat';
import Confirm from '../../components/Confirm';

export default class Pay extends Component {
    constructor(props) {
        super(props);
        this.state = {
            isLoading: false,
            commonpayArr: [
                {
                    "name": "微信支付",
                    "picIcon": require('../../images/wechat_pay.png'),
                }, {
                    "name": "支付宝支付",
                    "picIcon": require('../../images/alibaba_pay.png')
                }
            ],// 支付方式
            otherCommonpayArr: [
                {
                    "name": "花呗支付",
                    "picIcon": require('../../images/Tokio.png'),
                    "open": false
                }
            ],//快捷支付方式
            payIndex: 0, // 支付方式索引index 
            otherPayIndex: 0, // 其他支付方式索引index 
            childrenIndex: null,// 其他支付方式子数组索引index 
            iphoneIp: "", //手机IP地址
            payData: {},// 是否时用的支付信息
            payVisible: false,// 退出接口
            activeInfo: {}, //当前选中的花呗分期信息
            isFenqi: true, //是否可以分期
        }
    }

    componentWillMount() {
        if (this.props.navigation.state.params) {
            this.setState({
                payData: this.props.navigation.state.params.payData
            })
        }
    }
    componentDidMount() {
        this._getPhoneIp(); //获取手机IP地址
        // 查询分期信息
        Fetch(requestUrl, {
            "total_fee": this.state.payData.goodsSum,// 总钱数分
        }).then(data => {
            console.log(data)
            //整合数据结构
            if (data.status == "SUCCESS") {
                let newArr = [], otherCommonpay = this.state.otherCommonpayArr;
                if (data.sixFenQI && data.threeFenQI && data.twelveFenQI) {
                    newArr.push(data.sixFenQI)
                    newArr.push(data.threeFenQI)
                    newArr.push(data.twelveFenQI)
                }
                otherCommonpay.map((item) => {
                    if (item.name == "花呗支付") {
                        item.children = newArr.sort(this.compare('hb_fq_num'))
                    }
                })
                this.setState({
                    otherCommonpayArr: otherCommonpay
                })
                console.log(this.state.otherCommonpayArr)
            }
            else if (data.status == "ERROR") {
                this.setState({
                    isFenqi: false
                })
            }
            // eachFee 用户每期手续费
            // eachPrin 用户每期本金
            // prinAndFee 用户每期总额
            // hb_fq_num 用户分期期数
        })
        BackHandler.addEventListener('hardwareBackPress', this.handleBackPress);
    }

    handleBackPress = () => {
        this.setState({
            payVisible: true,
        })
        return true;
    }
    //数组对象属性值排序
    compare(property) {
        return function (a, b) {
            var value1 = a[property];
            var value2 = b[property];
            return value1 - value2;
        }
    }
    componentWillUnmount() {
        BackHandler.removeEventListener('hardwareBackPress', this.handleBackPress);
    }
    render() {
        const { navigate, goBack } = this.props.navigation;
        return (
            <View style={styles.container}>
                <StatusBar
                    animated={true}//是否动画
                    hidden={false}//是否隐藏
                    backgroundColor={'#000'}//android 设置状态栏背景颜色
                    translucent={false}//android 设置状态栏是否为透明
                    showHideTransition="fade"//IOS状态栏改变时动画 fade:默认 slide
                    networkActivityIndicatorVisible={this.state.isLoading}//IOS设定网络活动指示器(就是那个菊花)是否显示在状态栏。
                    statusBarStyle={"default"}//状态栏样式 default	默认(IOS为白底黑字、Android为黑底白字)
                    barStyle={"default"}// 状态栏文本的颜色。
                />
                <Nav
                    title={"收银台"}
                    leftClick={() => {
                        this.setState({
                            payVisible: true,
                        })
                    }}
                />
                <ScrollView>
                    {/* 应付金额 */}
                    <View style={[styles.payItems, { marginTop: Px2dp(20) }]}>
                        <Text style={styles.payTexts}>应付金额</Text>
                        <Text style={styles.payPrice}>¥{this.state.payData.goodsSum / 100}</Text>
                    </View>
                    {/* 快捷支付 */}
                    <Text style={styles.payTitle}>快捷支付</Text>
                    {
                        this.state.commonpayArr.map((item, index) => {
                            return (
                                <View key={index} style={{ backgroundColor: Colors.white }}>
                                    <TouchableOpacity
                                        activeOpacity={0.8}
                                        style={index == 1 ? styles.payItems : styles.payItem}
                                        onPress={() => {
                                            this.setState({
                                                payIndex: index,
                                                otherPayIndex: null,
                                                childrenIndex: null
                                            })
                                        }}>
                                        <Image source={item.picIcon} />
                                        <Text style={styles.payText}>{item.name}</Text>
                                        <Image source={this.state.payIndex == index ? require('../../images/on_icon.png') : require('../../images/off_icon.png')} />
                                    </TouchableOpacity>
                                </View>
                            )
                        })
                    }
                    {/* 快捷支付 */}
                    <Text style={styles.payTitle}>分期付款</Text>
                    {
                        this.state.otherCommonpayArr.map((item, index) => {
                            return (
                                <View key={index} style={this.state.isFenqi ? { backgroundColor: Colors.white, opacity: 1 } : { backgroundColor: Colors.white, opacity: 0.6 }}>
                                    <TouchableOpacity
                                        activeOpacity={0.8}
                                        style={index == 0 ? styles.payItems : styles.payItem}
                                        onPress={() => {
                                            if (this.state.isFenqi) {
                                                var newArr = this.state.otherCommonpayArr
                                                newArr[index].open = !newArr[index].open
                                                this.setState({
                                                    otherPayIndex: index,
                                                    otherCommonpayArr: newArr,
                                                })
                                            }
                                        }}>
                                        <Image source={item.picIcon} />
                                        <Text style={styles.payText}>{item.name}</Text>
                                        <Image source={item.open == false ? require('../../images/Downaway.png') : require('../../images/Putaway.png')} />
                                    </TouchableOpacity>
                                    {
                                        item.open == true && item.children ?
                                            item.children.map((items, inx) => {
                                                return (
                                                    <View key={inx} style={inx == item.children.length - 1 ? { paddingBottom: Px2dp(10), backgroundColor: Colors.white } : { backgroundColor: Colors.white }}>
                                                        <TouchableOpacity
                                                            activeOpacity={0.8}
                                                            style={inx == item.children.length - 1 ? styles.ChildrenItems : styles.ChildrenItem}
                                                            onPress={() => {
                                                                this.setState({
                                                                    childrenIndex: inx,
                                                                    activeInfo: items,
                                                                    payIndex: null
                                                                })
                                                            }}>
                                                            <Text style={styles.childerpayText}><Text>¥</Text>{items.prinAndFee}x{items.hb_fq_num}({items.eachFee ? "手续费¥" + items.eachFee + "/期" : "免手续费"})</Text>
                                                            <Image source={this.state.childrenIndex == inx ? require('../../images/on_icon.png') : require('../../images/off_icon.png')} />
                                                        </TouchableOpacity>
                                                    </View>
                                                )
                                            }) : null
                                    }
                                </View>
                            )
                        })
                    }
                </ScrollView>
                <View style={styles.payBottomContent}>
                    <TouchableOpacity
                        activeOpacity={0.8}
                        onPress={() => {
                            if (this.state.payIndex == 0) {
                                this._weixinPay(this.state.payData);
                            } else if (this.state.payIndex == 1) {
                                this._aliPay(this.state.payData);
                            } else if (this.state.childrenIndex != null) {
                                this._huaBeiPay(this.state.payData);
                            }
                        }}
                        style={styles.payMoney}
                    >
                        <Text style={styles.payMoneytxt}>去付款</Text>
                    </TouchableOpacity>
                </View>
                <Confirm
                    visible={this.state.payVisible}
                    yesClick={() => {
                        this.setState({ payVisible: false })
                        this.props.navigation.navigate("OrderDetail", { orderId: this.state.payData.orderId, source: "pay" })
                    }}
                    noClick={() => { this.setState({ payVisible: false }) }}
                    text="确认取消支付?"
                />
                {this.state.isLoading ? <Loading /> : null}
            </View>
        );
    }
    //获取手机ip
    _getPhoneIp() {
        Fetch('http://ip.360.cn/IPShare/info').then(data => {
            this.setState({
                iphoneIp: data.ip
            })
        })
    }
    //微信下单接口
    _weixinPay(payData) {
        Fetch(requestUrl, {
            "openid": UserInfo.appOpenId ? UserInfo.appOpenId : '',
            "bodyContent": "迪信通商品购买",
            "out_trade_no": payData.orderId,
            // "total_fee": payData.goodsSum,// 下单金额
            "total_fee": 1,// 
            "ip": this.state.iphoneIp,
            "attach": payData.payInfoId
        }).then(data => {
            console.log(data)
            if (data.status == "SUCCESS") {
                this.setState({
                    visibleFlag: false,
                    isLoading: false,
                })
                // 微信支付
                WeChat.weChatPay({
                    appid: data.data.androidData.appid,
                    partnerid: data.data.androidData.partnerid,  // 商家向财付通申请的商家id
                    prepayid: data.data.androidData.prepayid,   // 预支付订单
                    noncestr: data.data.androidData.noncestr,   // 随机串,防重发
                    timestamp: data.data.androidData.timestamp,  // 时间戳,防重发
                    package: data.data.androidData.package,    // 商家根据财付通文档填写的数据和签名
                    sign: data.data.androidData.sign      // 商家根据微信开放平台文档对数据做的签名
                }).then(data => {
                    if (data.errCode == 0) {
                        setTimeout(() => {
                            this.props.navigation.navigate("PaySuccess", { "payData": payData });
                        })
                    } else if (data.code == -2) {
                        ToastShow({ "text": "用户已取消" })
                        setTimeout(() => {
                            this.props.navigation.navigate("OrderDetail", { orderId: payData.orderId, source: 'pay' })
                        })
                    } else {
                        ToastShow({ "text": "付款失败" })
                        setTimeout(() => {
                            this.props.navigation.navigate("OrderDetail", { orderId: payData.orderId, source: 'pay' })
                        })
                    }
                }).catch(error => {
                    setTimeout(() => {
                        this.props.navigation.navigate("OrderDetail", { orderId: payData.orderId, source: 'pay' })
                    })
                })
            } else if (data.status == "ERROR") {
                this.setState({
                    isLoading: false,
                })
            } else {
                this.setState({
                    isLoading: false,
                })
            }
        })
    }
    // 支付宝下单
    _aliPay(payData) {
        Fetch(requestUrl, {
            "userId": UserInfo.id,// 用户id
            "body_content": "",
            "out_trade_no": payData.orderId,
            // "total_fee": payData.goodsSum,// 下单金额
            "total_fee": 1,// 测试下单金额
            "attach": payData.payInfoId,
            'subject': '',// 商品名称
        }).then(data => {
            console.log(data)
            if (data.status == "0") {
                this.setState({
                    visibleFlag: false,
                    isLoading: false,
                })
                // 支付宝支付
                WeChat.AliPay(data.data).then(data => {
                    ToastShow({ "text": "支付成功" })
                    setTimeout(() => {
                        this.props.navigation.navigate("PaySuccess", { "payData": payData, source: 'pay' });
                    })
                }).catch(error => {
                    ToastShow({ "text": "支付失败" })
                    setTimeout(() => {
                        this.props.navigation.navigate("OrderDetail", { orderId: payData.orderId, source: 'pay' })
                    })
                })
            } else if (data.status == "ERROR") {
                this.setState({
                    isLoading: false,
                })
                ToastShow({ "text": '支付宝下单失败' })
            } else {
                this.setState({
                    isLoading: false,
                })
            }
        })
    }
    // 花呗下单接口
    _huaBeiPay(payData) {
        Fetch(requestUrl, {
            "userId": UserInfo.id,// 用户id
            "body_content": "",
            "out_trade_no": payData.orderId,
            "total_fee": payData.goodsSum,// 下单金额
            "attach": payData.payInfoId,
            'subject': '',// 商品名称
            "hb_fq_num": String(this.state.activeInfo.hb_fq_num),// 花呗分期 3 6 12
            "enablePayChannels": 'pcreditpayInstallment',
        }).then(data => {
            console.log(data)
            if (data.status == "0") {
                this.setState({
                    visibleFlag: false,
                    isLoading: false,
                })
                // 支付宝支付
                WeChat.AliPay(data.data).then(data => {
                    ToastShow({ "text": "支付成功" })
                    setTimeout(() => {
                        this.props.navigation.navigate("PaySuccess", { "payData": payData, source: 'pay' });
                    })
                }).catch(error => {
                    ToastShow({ "text": "支付失败" })
                    setTimeout(() => {
                        this.props.navigation.navigate("OrderDetail", { orderId: payData.orderId, source: 'pay' })
                    })
                })
            } else if (data.status == "ERROR") {
                this.setState({
                    isLoading: false,
                })
                ToastShow({ "text": '支付宝下单失败' })
            } else {
                this.setState({
                    isLoading: false,
                })
            }
        })
    }
}
const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: Colors.mainBg,
    },
    payItem: {
        borderBottomWidth: Pixel,
        flexDirection: 'row',
        alignItems: 'center',
        borderBottomColor: "#ececec",
        height: Px2dp(50),
        marginLeft: Px2dp(16),
        marginRight: Px2dp(16),
    },
    payItems: {
        flexDirection: 'row',
        alignItems: 'center',
        height: Px2dp(50),
        paddingLeft: Px2dp(16),
        paddingRight: Px2dp(16),
        backgroundColor: Colors.white,
    },
    ChildrenItems: {
        flexDirection: 'row',
        alignItems: 'center',
        height: Px2dp(40),
        marginLeft: Px2dp(45),
        marginRight: Px2dp(16),
        backgroundColor: Colors.white,
    },
    ChildrenItem: {
        borderBottomWidth: Pixel,
        flexDirection: 'row',
        alignItems: 'center',
        borderBottomColor: "#ececec",
        height: Px2dp(40),
        marginLeft: Px2dp(45),
        marginRight: Px2dp(16),
    },
    payText: {
        fontSize: Px2dp(15),
        color: Colors.text333,
        flex: 1,
        marginLeft: Px2dp(10)
    },
    payTexts: {
        fontSize: Px2dp(15),
        color: Colors.text333,
        flex: 1,
    },
    payPrice: {
        fontSize: Px2dp(15),
        color: Colors.red
    },
    childerpayText: {
        fontSize: Px2dp(14),
        color: Colors.text666,
        flex: 1,
    },
    payTitle: {
        fontSize: Px2dp(13),
        color: Colors.text888,
        marginTop: Px2dp(16),
        marginBottom: Px2dp(8),
        paddingLeft: Px2dp(16)
    },
    payBottomContent: {
        flexDirection: "row",
        alignItems: "center",
        height: IOS ? Px2dp(50) + TabBar : Px2dp(50),
        paddingBottom: IOS ? TabBar : 0,
        backgroundColor: Colors.white,
    },
    commonPayItemBomTit: {
        fontSize: Px2dp(14),
        color: Colors.text333,
        flex: 1,
        textAlign: "center"
    },
    payMoney: {
        backgroundColor: Colors.red,
        height: Px2dp(50),
        flex: 1,
        alignItems: 'center',
        justifyContent: "center"
    },
    payMoneytxt: {
        fontSize: Px2dp(15),
        color: Colors.white
    }
});
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值