<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta id="viewport" name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,viewport-fit=cover,user-scalable=0;">
    <meta content="telephone=no" name="format-detection">
    <style>
        * {
            padding: 0;
            margin: 0;
            font-family: system-ui,-apple-system,BlinkMacSystemFont,Helvetica Neue,PingFang SC,Hiragino Sans GB,Microsoft YaHei UI,Microsoft YaHei,Arial,sans-serif;
        }
        body {
            background: #fff;
        }
        .warning {
            width: 80px;
            height: 80px;
            margin: 30px auto 15px;
        }
        .warning img {
            width: 85px;
            height: 85px;
        }
        .warntext {
            width: 80%;
            margin: 0 auto;
            text-align: center; 
            font-size: 20px;
            font-weight: bold;
        }
        .header {
            position: fixed;
            top: 0;
            width: 100%;
            line-height: 40px;
            background: #fff;
            font-size: 13px;
            text-align: center;
            color: #999;
        }
        .order_bzCode {
            width: 80%;
            margin: 45px auto 0;
            text-align: center;
            background: #f5f5f5;
            color: #666;
            padding: 15px 0;
            border-radius: 10px;
        }
        .qrcode {
            width: 80%;
            margin: 15px auto 0;
            border-radius: 10px;
            border: 1px solid #eee;
        }
        .qrcode img {
            width: 100%;
            border-radius: 10px;
        }
        .chatroom_leader_wxid {
            width: 80%;
            margin: 0 auto;
            text-align: center;
            padding: 15px 0;
            font-size: 14px;
            color: #999;
            border-radius: 10px;
        }
    </style>
</head>

<body>
    
    <?php
    
        // 获取URL传过来的param
        @$param = $_GET['param'];
        
        // 获取到支付回调中的openid
        $param_openid = explode("|", $param)[0];
        
        // 获取到支付回调中的chatroom_id
        $param_chatroom_id = explode("|", $param)[1];
        
        // 从URL中提取chatroom_id
        @$url_chatroom_id = $_GET['crid'];
        
        // 从URL中提取openid
        @$url_openid = $_GET['openid'];
        
        // 接收其它回调参数
        $money = $_GET['money'];
        $name = $_GET['name'];
        $out_trade_no = $_GET['out_trade_no'];
        $pid = $_GET['pid'];
        $trade_no = $_GET['trade_no'];
        $trade_status = $_GET['trade_status'];
        $type = $_GET['type'];
        
        // 参与签名的参数
        $sign_params = [
            'money' => $money,
            'name' => $name,
            'out_trade_no' => $out_trade_no,
            'param' => $param,
            'pid' => $pid,
            'trade_no' => $trade_no,
            'trade_status' => $trade_status,
            'type' => $type
        ];
        
        // 提醒信息
        function warnInfo($title,$warnText){
            
            return '
            <title>'.$title.'</title>
            <div class="warning">
                <img src="../../../../static/img/warn.png" />
            </div>
            <p class="warntext">'.$warnText.'</p>';
        }
        
        // 数据库配置
    	include '../../../../console/Db.php';
    
    	// 实例化类
    	$db = new DB_API($config);
        
        // 获取支付配置
        $getChatroomPayConfig = $db->set_table('ylb_ChatroomPayConfig')->find(['id' => 1]);
        
        if($getChatroomPayConfig) {
            
            // 易支付的商户密钥	
            $payapi_merchant_key = $getChatroomPayConfig['payapi_merchant_key'];
        }else {
            
            // 支付配置获取失败
            echo warnInfo('温馨提示', '支付配置获取失败');
            exit;
        }
        
        // 生成的签名
        $sign = generate_sign($sign_params, $payapi_merchant_key);
        
        // 回调的签名
        $sign_form_url = $_GET['sign'];
        
        // 验证当前环境是否有SESSION
        session_start();
        
        if(isset($_SESSION["payuser_openid"])){
            
            // 验证payuser_openid和param_openid是否一致
            if($param_openid == $_SESSION["payuser_openid"]) {
                
                // 一致
                // 验证签名
                if($sign_form_url == $sign) {
                    
                    // 签名正确
                    // 查询这个订单是否已支付
                    $checkOrder = $db->set_table('ylb_ChatroomPayOrders')->find(['order_num' => $out_trade_no]);
                    if($checkOrder) {
                        
                        $order_status = $checkOrder['order_status'];
                        if($order_status == 1) {
                            
                            // 该订单已支付
                            showQrcode($param_chatroom_id,$url_chatroom_id,$db,$checkOrder);
                        }else {
                            
                            // 该订单未支付
                            echo warnInfo('温馨提示', '该订单未支付');
                        }
                    }else {
                        
                        // 该订单不存在
                        echo warnInfo('温馨提示', '该订单不存在或已被管理员删除');
                    }
                }else {
                    
                    // 签名不正确
                    echo warnInfo('温馨提示', '该链接的签名不正确');
                }
            }else {
                
                // 验证其它情况
                if($url_openid && $url_openid == $_SESSION["payuser_openid"]) {
                    
                    // 从URL中提取openid与SESSION中的openid一致
                    // 开始验证当前openid与chatroom_id是否存在已支付的订单
                    $checkOrder = $db->set_table('ylb_ChatroomPayOrders')->find(
                        ['chatroom_id' => $url_chatroom_id,'order_openid' => $url_openid, 'order_status' => 1]
                    );
                    if($checkOrder) {
                        
                        // 有已支付的订单
                        showQrcode($param_chatroom_id,$url_chatroom_id,$db,$checkOrder);
                    }else {
                        
                        // 没有已支付的订单
                        echo warnInfo('温馨提示', '没有已支付的订单');
                    }
                }else {
                    
                    // 不一致
                    // 重新走一次网页授权流程
                    if($param_chatroom_id) {
                        getOpenid($db,$param_chatroom_id);
                    }else {
                        getOpenid($db,$url_chatroom_id);
                    }
                }
            }
        }else {
            
            // 没有SESSION
            // 重新走一次网页授权流程
            if($param_chatroom_id) {
                getOpenid($db,$param_chatroom_id);
            }else {
                getOpenid($db,$url_chatroom_id);
            }
        }
        
        // 展示群二维码
        function showQrcode($param_chatroom_id,$url_chatroom_id,$db,$checkOrder) {
            
            // 获取这个chatroom_id的信息
            if($param_chatroom_id) {
                $crid = $param_chatroom_id;
            }else {
                $crid = $url_chatroom_id;
            }
            $get_chatroom_info = $db->set_table('ylb_ChatroomPay')->find(['chatroom_id' => $crid]);
            
            if($get_chatroom_info) {
                
                if($get_chatroom_info['chatroom_status'] == 1) {
                    
                    // 正常
                    // 有已支付的订单
                    echo '<title>长按扫码进群</title>';
                    echo '<div class="header">进群后请将备注码设置到 [我在本群的昵称]</div>';
                    echo '<div class="order_bzCode">备注码：'.$checkOrder['order_bzCode'].'</div>';
                    echo '<div class="qrcode"><img src="'.$get_chatroom_info['chatroom_qrcode'].'" /></div>';
                    
                    if($get_chatroom_info['chatroom_leader_wxid']) {
                        
                        // 如果设置了才会显示
                        echo '<p class="chatroom_leader_wxid">群主微信号：'.$get_chatroom_info['chatroom_leader_wxid'].'</p>';
                    }
                }else {
                    
                    // 暂停使用
                    echo warnInfo('温馨提示', '该群已被管理员暂停使用');
                }
            }else {
                
                // 获取失败
                echo warnInfo('温馨提示', '无法获取到群二维码');
            }
        }
        
        // 网页授权流程
        function getOpenid($db,$chatroom_id) {
    	
            // 获取网页授权配置
            $getAuthConfig = $db->set_table('ylb_ChatroomPayConfig')->find(['id' => 1]);
            
            if($getAuthConfig) {
                
                // 企业微信企业ID
                $qywx_Appid = $getAuthConfig['qywx_Appid'];
                
                // 企业微信应用网页授权域名	
                $qywx_auth_domain = $getAuthConfig['qywx_auth_domain'];
                
                // 企业微信应用ID	
                $qywx_AgentId = $getAuthConfig['qywx_AgentId'];
                
                // 1. 获取qr目录URL
                $qr_url = $qywx_auth_domain . dirname($_SERVER["REQUEST_URI"]);
                
                // 2. 构建redirect_uri
                $redirect_uri = $qr_url . '/Auth_return.php';
                
                // 3. 构建完整的网页授权URL
                $jump_url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$qywx_Appid.'&redirect_uri='.$redirect_uri.'&response_type=code&scope=snsapi_base&state='.$chatroom_id.'&agentid='.$qywx_AgentId.'#wechat_redirect';
                
                // 4. 跳转到网页授权URL
                echo '<script>location.href="'.$jump_url.'";</script>';
            }else {
                
                // 网页授权配置获取失败
                echo warnInfo('温馨提示', '网页授权配置获取失败');
                exit;
            }
        }
        
        // 生成签名
        function generate_sign($data, $payapi_merchant_key) {
            
            // 移除sign和sign_type参数以及空值
            unset($data['sign']);
            unset($data['sign_type']);
            foreach ($data as $k => $v) {
                if ($v == '') {
                    unset($data[$k]);
                }
            }
        
            // 按键名排序
            ksort($data);
        
            // 拼接成URL键值对的格式
            $string = '';
            foreach ($data as $k => $v) {
                $string .= "$k=$v&";
            }
        
            // 移除最后一个&符号并添加密钥
            $string = rtrim($string, '&');
            $string .= $payapi_merchant_key;
        
            // 计算MD5签名
            return md5($string);
        }

    ?>
</body>

<script>

    // 屏蔽分享
    document.addEventListener('WeixinJSBridgeReady', function onBridgeReady() {
        WeixinJSBridge.call('hideOptionMenu');
    });
</script>
</html>