<?php
include_once __DIR__ . '/../common/function.php';
session_start();
if ( !is_array($_SESSION[ 'wxPayQrcodeData' ])) {
    exit(ReturnError('参数配置有误'));
}
$order        = $_SESSION[ 'wxPayQrcodeData' ][ 'order' ];
$money        = $_SESSION[ 'wxPayQrcodeData' ][ 'money' ];
$name         = $_SESSION[ 'wxPayQrcodeData' ][ 'name' ];
$qr_code      = $_SESSION[ 'wxPayQrcodeData' ][ 'qr_code' ];
$order_time   = $_SESSION[ 'wxPayQrcodeData' ][ 'time' ];
$out_trade_no = isset($_GET[ 'trade_no' ]) ? purge($_GET[ 'trade_no' ]) : '';;
$type = isset($_GET[ 'type' ]) ? purge($_GET[ 'type' ]) : '';;
$act = isset($_GET[ 'act' ]) ? purge($_GET[ 'act' ]) : '';

$type = isset($_GET[ 'type' ]) ? purge($_GET[ 'type' ]) : '';;
if ($act === 'check') {
    $wxPAy = new WxpayService(__WX_MCHID__ , __WX_APPID__ , __WX_KEY__);
    if ($order !== $out_trade_no) {
        exit(return_msg(203 , '订单号不匹配'));
    }
    $queryResults = $wxPAy->orderquery($out_trade_no);
    if ( !$queryResults[ 'code' ]) {
        exit(ReturnError($queryResults[ 'msg' ]));
    } else {
        if ( !Db::table('app_order')
                ->where([
                    'pay_order'  => $out_trade_no ,
                    'pay_status' => 1
                ])
                ->find()) {
            Db::table('app_order')
              ->where(['pay_order' => $out_trade_no])
              ->update([
                  'pay_orderno' => $out_trade_no ,
                  'pay_status'  => 3
                  // 处理中
              ]);
        }
        // 查询订单是否存在
        $query = Db::table('app_order')
                   ->where([
                       'pay_order'   => $order ,
                       'pay_orderno' => $out_trade_no ,
                       'pay_type'    => $type
                   ])
                   ->find();
        if ( !$query) {
            $order_status = 0; // 不存在直接返回 0
        } else {
            // 获取订单内容的数据
            $query_data = json_decode($query[ 'pay_content' ] , true);
            // 判断订单状态
            switch ($query[ 'pay_status' ]) {
                case 3:
                    // 1 | 开通会员 2 | 续费会员
                    if ($query_data[ 'group_type' ] == 1) {
                        $action = openMember($query_data[ 'user_id' ] , NULL , $query_data[ 'plans_id' ]);
                        if ($action) {
                            $order_status = 1;
                        }
                    } else if ($query_data[ 'group_type' ] == 2) {
                        $action = renewMemberWithChatLimit($query_data[ 'userid' ] , $query_data[ 'plans_period' ] , $query_data[ 'plans_chat_limit' ]);
                        if ($action) {
                            $order_status = 1;
                        }
                    }
                    if ($action) {
                        Db::table('app_order')
                          ->where(['pay_order' => $query[ 'pay_order' ]])
                          ->update(['pay_status' => 1]);
                    }
                    break;
                case 1:
                    $order_status = 2;
                    break;
                case 0:
                    $order_status = 0;
                    break;
            }

        }

        if ($order_status === 1) {
            exit(return_msg(200 , '支付成功' , ['backurl' => 'index.php']));
        } else {
            exit(return_msg(201 , '未支付'));
        }
    }
}
?>

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta http-equiv="Content-Language" content="zh-cn">
    <meta name="renderer" content="webkit">
    <title>微信扫码支付</title>
    <style>html {
            font-size: 62.5%;
            font-family: 'helvetica neue', tahoma, arial, 'hiragino sans gb', 'microsoft yahei', 'Simsun', sans-serif
        }

        body, div, dl, dt, dd, ul, ol, li, h1, h2, h3, h4, h5, h6, pre, code, form, fieldset, legend, input, button, textarea, p, blockquote, th, td, hr {
            margin: 0;
            padding: 0
        }

        body {
            line-height: 1.333;
            font-size: 12px
        }

        h1, h2, h3, h4, h5, h6 {
            font-size: 100%;
            font-family: arial, 'hiragino sans gb', 'microsoft yahei', 'Simsun', sans-serif
        }

        input, textarea, select, button {
            font-size: 12px;
            font-weight: normal
        }

        input[type="button"], input[type="submit"], select, button {
            cursor: pointer
        }

        table {
            border-collapse: collapse;
            border-spacing: 0
        }

        address, caption, cite, code, dfn, em, th, var {
            font-style: normal;
            font-weight: normal
        }

        li {
            list-style: none
        }

        caption, th {
            text-align: left
        }

        q:before, q:after {
            content: ''
        }

        abbr, acronym {
            border: 0;
            font-variant: normal
        }

        sup {
            vertical-align: text-top
        }

        sub {
            vertical-align: text-bottom
        }

        fieldset, img, a img, iframe {
            border-width: 0;
            border-style: none
        }

        img {
            -ms-interpolation-mode: bicubic
        }

        textarea {
            overflow-y: auto
        }

        legend {
            color: #000
        }

        a:link, a:visited {
            text-decoration: none
        }

        hr {
            height: 0
        }

        label {
            cursor: pointer
        }

        .clearfix:after {
            content: "\200B";
            display: block;
            height: 0;
            clear: both
        }

        .clearfix {
            *zoom: 1
        }

        a {
            color: #328CE5
        }

        a:hover {
            color: #2b8ae8;
            text-decoration: none
        }

        a.hit {
            color: #C06C6C
        }

        a:focus {
            outline: none
        }

        .hit {
            color: #8DC27E
        }

        .txt_auxiliary {
            color: #A2A2A2
        }

        .clear {
            *zoom: 1
        }

        .clear:before, .clear:after {
            content: "";
            display: table
        }

        .clear:after {
            clear: both
        }

        body, .body {
            background: #f7f7f7;
            height: 100%
        }

        .mod-title {
            height: 60px;
            line-height: 60px;
            text-align: center;
            border-bottom: 1px solid #ddd;
            background: #fff
        }

        .mod-title .ico-wechat {
            display: inline-block;
            width: 41px;
            height: 36px;
            background: url("../assets/media/image/wechat-pay.png") 0 -115px no-repeat;
            vertical-align: middle;
            margin-right: 7px
        }

        .mod-title .text {
            font-size: 20px;
            color: #333;
            font-weight: normal;
            vertical-align: middle
        }

        .mod-ct {
            width: 610px;
            padding: 0 135px;
            margin: 0 auto;
            margin-top: 15px;
            background: #fff url("../assets/media/image/wave.png") top center repeat-x;
            text-align: center;
            color: #333;
            border: 1px solid #e5e5e5;
            border-top: none
        }

        .mod-ct .order {
            font-size: 20px;
            padding-top: 30px
        }

        .mod-ct .amount {
            font-size: 48px;
            margin-top: 20px
        }

        .mod-ct .qr-image {
            margin-top: 30px
        }

        .mod-ct .qr-image img {
            width: 230px;
            height: 230px
        }

        .mod-ct .detail {
            margin-top: 60px;
            padding-top: 25px
        }

        .mod-ct .detail .arrow .ico-arrow {
            display: inline-block;
            width: 20px;
            height: 11px;
            background: url("../assets/media/image/wechat-pay.png") -25px -100px no-repeat
        }

        .mod-ct .detail .detail-ct {
            display: none;
            font-size: 14px;
            text-align: right;
            line-height: 28px
        }

        .mod-ct .detail .detail-ct dt {
            float: left
        }

        .mod-ct .detail-open {
            border-top: 1px solid #e5e5e5
        }

        .mod-ct .detail .arrow {
            padding: 6px 34px;
            border: 1px solid #e5e5e5
        }

        .mod-ct .detail .arrow .ico-arrow {
            display: inline-block;
            width: 20px;
            height: 11px;
            background: url("../assets/media/image/wechat-pay.png") -25px -100px no-repeat
        }

        .mod-ct .detail-open .arrow .ico-arrow {
            display: inline-block;
            width: 20px;
            height: 11px;
            background: url("../assets/media/image/wechat-pay.png") 0 -100px no-repeat
        }

        .mod-ct .detail-open .detail-ct {
            display: block
        }

        .mod-ct .tip {
            margin-top: 40px;
            border-top: 1px dashed #e5e5e5;
            padding: 30px 0;
            position: relative
        }

        .mod-ct .tip .ico-scan {
            display: inline-block;
            width: 56px;
            height: 55px;
            background: url("../assets/media/image/wechat-pay.png") 0 0 no-repeat;
            vertical-align: middle;
            *display: inline;
            *zoom: 1
        }

        .mod-ct .tip .tip-text {
            display: inline-block;
            vertical-align: middle;
            text-align: left;
            margin-left: 23px;
            font-size: 16px;
            line-height: 28px;
            *display: inline;
            *zoom: 1
        }

        .mod-ct .tip .dec {
            display: inline-block;
            width: 22px;
            height: 45px;
            background: url("../assets/media/image/wechat-pay.png") 0 -55px no-repeat;
            position: absolute;
            top: -23px
        }

        .mod-ct .tip .dec-left {
            background-position: 0 -55px;
            left: -136px
        }

        .mod-ct .tip .dec-right {
            background-position: -25px -55px;
            right: -136px
        }


        .foot .link {
            color: #0071ce
        }

        @media (max-width: 768px) {
            .mod-ct {
                width: 100%;
                padding: 0;
                border: 0
            }

            .mod-ct .tip .dec-right {
                display: none
            }

            .mod-ct .detail {
                margin-top: 30px
            }

            .mod-ct .detail .detail-ct {
                padding: 0 19px;
                margin-bottom: 19px
            }
        }
    </style>
</head>
<body>
<div class="body">
    <h1 class="mod-title">
        <span class="ico-wechat"></span><span class="text">微信扫码支付</span>
    </h1>
    <div class="mod-ct">
        <div class="order"></div>
        <div class="amount">￥<?php echo $money ?></div>
        <div class="qr-image" id="qrcode">

        </div>
        <div class="detail" id="orderDetail">
            <dl class="detail-ct" style="display: none;">
                <dt>购买物品</dt>
                <dd id="productName"><?php echo $name ?></dd>
                <dt>商户订单号</dt>
                <dd id="billId"><?php echo $order ?></dd>
                <dt>创建时间</dt>
                <dd id="createTime"><?php echo $order_time ?></dd>
            </dl>
            <a href="javascript:void(0)" class="arrow"><i class="ico-arrow"></i></a>
        </div>
        <div class="tip">
            <span class="dec dec-left"></span>
            <span class="dec dec-right"></span>
            <div class="ico-scan"></div>
            <div class="tip-text">
                <p>请使用微信扫一扫</p>
                <p>扫描二维码完成支付</p>
            </div>
        </div>
        <div class="tip-text">

        </div>
    </div>
    <script src="//cdn.staticfile.org/jquery/1.12.4/jquery.min.js"></script>
    <script src="//cdn.staticfile.org/layer/3.1.1/layer.min.js"></script>
    <script src="//cdn.staticfile.org/jquery.qrcode/1.0/jquery.qrcode.min.js"></script>
    <script>
        var code_url = '<?php echo $qr_code ?>';
        $('#qrcode').qrcode({
            text      : code_url,
            width     : 230,
            height    : 230,
            foreground: "#000000",
            background: "#ffffff",
            typeNumber: -1
        });
        // 订单详情
        $('#orderDetail .arrow').click(function (event) {
            if ($('#orderDetail').hasClass('detail-open')) {
                $('#orderDetail .detail-ct').slideUp(500, function () {
                    $('#orderDetail').removeClass('detail-open');
                });
            }
            else {
                $('#orderDetail .detail-ct').slideDown(500, function () {
                    $('#orderDetail').addClass('detail-open');
                });
            }
        });

        // 检查是否支付完成
        function loadmsg ()
        {
            $.ajax({
                type    : "GET",
                dataType: "json",
                url     : "getshop2.php",
                timeout : 10000, //ajax请求超时时间10s
                data    : {act: "check", type: "wxpay", trade_no: "<?php echo $order ?>"}, //post数据
                success : function (data, textStatus) {
                    //从服务器得到数据，显示数据并继续查询
                    if (data.code === 200) {
                        layer.msg('支付成功，正在跳转中...', {icon: 16, shade: 0.1, time: 15000});
                        setTimeout(window.location.href = data.data.backurl, 1000);
                    }
                    else {
                        setTimeout(() => {
                            loadmsg()
                        }, 2000);
                    }
                },
                //Ajax请求超时，继续查询
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    if (textStatus === "timeout") {
                        setTimeout(() => {
                            loadmsg()
                        }, 1000);
                    }
                    else { //异常
                        setTimeout(() => {
                            loadmsg()
                        }, 3000);
                    }
                }
            });
        }

        function checkresult ()
        {

            $.ajax({
                type    : "GET",
                dataType: "json",
                url     : "getshop.php",
                timeout : 10000, //ajax请求超时时间10s
                data    : {act: "check", type: "alipay", trade_no: "<?php echo $order ?>"},
                success : function (data, textStatus) {
                    //从服务器得到数据，显示数据并继续查询
                    if (data.code === 200) {
                        layer.msg('支付成功，正在跳转中...', {icon: 16, shade: 0.1, time: 15000});
                        setTimeout(window.location.href = data.data.backurl, 1000);
                    }
                    else {
                        layer.msg('您还未完成付款，请继续付款', {shade: 0, time: 1500});
                    }
                }
            });
        }

        var isMobile = function () {
            var ua = navigator.userAgent;
            var ipad      = ua.match(/(iPad).*OS\s([\d_]+)/),
                isIphone  = !ipad && ua.match(/(iPhone\sOS)\s([\d_]+)/),
                isAndroid = ua.match(/(Android)\s+([\d.]+)/);
            return isIphone || isAndroid;
        }

        window.onload = function () {
            if (isMobile()) {
                $('.open_app').show();
                if (navigator.userAgent.indexOf('MicroMessenger/') > 0) {
                    $('.btn-open-app').attr('onclick', 'wx_open()');
                }
            }
            setTimeout(() => {
                loadmsg()
            }, 2000);
        }
    </script>
</body>
</html>
