<?php
    
    // 编码
    header("Content-type:application/json");
    
    // 签名生成
    function generate_sign($data, $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 .= $key;
    
        // 计算MD5签名
        return md5($string);
    }
    
    // 获取客户端ip地址
    function getClientIP() {
        $ipaddress = '';
        if (isset($_SERVER['HTTP_CLIENT_IP'])) {
            $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
        } else if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
        } else if (isset($_SERVER['HTTP_X_FORWARDED'])) {
            $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
        } else if (isset($_SERVER['HTTP_X_CLUSTER_CLIENT_IP'])) {
            $ipaddress = $_SERVER['HTTP_X_CLUSTER_CLIENT_IP'];
        } else if (isset($_SERVER['HTTP_FORWARDED_FOR'])) {
            $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
        } else if (isset($_SERVER['HTTP_FORWARDED'])) {
            $ipaddress = $_SERVER['HTTP_FORWARDED'];
        } else if (isset($_SERVER['REMOTE_ADDR'])) {
            $ipaddress = $_SERVER['REMOTE_ADDR'];
        } else {
            $ipaddress = 'UNKNOWN';
        }
        return $ipaddress;
    }
    
    // 获取openid和付费群id（crid）
    $openid = $_GET['openid'];
    $chatroom_id = $_GET['crid'];
    
    // 查询当前openid、付费群id是否已支付
    // 数据库配置
	include '../../console/Db.php';

	// 实例化类
	$db = new DB_API($config);

    // 获取当前openid、chatroom_id的订单支付状态
    $getOrderStatus = $db->set_table('ylb_ChatroomPayOrders')->find(
        [
            'order_openid' => $openid,
            'chatroom_id' => $chatroom_id,
            'order_status' => 1
        ]
    );
    
    // 验证订单支付状态
    if($getOrderStatus) {
        
        // 该订单已支付
        $result = array(
            'code' => 201,
            'msg' => '该订单已支付'
        );
        echo json_encode($result,JSON_UNESCAPED_UNICODE);
        exit;
    }
    
    // 获取群信息
    $getChatroom = $db->set_table('ylb_ChatroomPay')->find(['chatroom_id' => $chatroom_id]);
    
    if($getChatroom) {
        
        // 价格
        $chatroom_amount = $getChatroom['chatroom_amount'];
    
        // 群名称
        $chatroom_name = $getChatroom['chatroom_name'];
        
        // chatroom_create_user
        $chatroom_create_user = $getChatroom['chatroom_create_user'];
    }else {
        
        // 群信息获取失败
        $result = array(
            'code' => 201,
            'msg' => '群信息获取失败'
        );
        echo json_encode($result,JSON_UNESCAPED_UNICODE);
        exit;
    }
    
    // 获取支付配置
    $getChatroomPayConfig = $db->set_table('ylb_ChatroomPayConfig')->find(['id' => 1]);
    
    if($getChatroomPayConfig) {
        
        // 易支付的接口域名
        $payapi_domain = $getChatroomPayConfig['payapi_domain'];
    
        // 易支付的商户ID	
        $payapi_merchant_id = $getChatroomPayConfig['payapi_merchant_id'];
        
        // 易支付的商户密钥	
        $payapi_merchant_key = $getChatroomPayConfig['payapi_merchant_key'];
        
        // OAuth2.0网页授权可信域名
        $qywx_auth_domain = $getChatroomPayConfig['qywx_auth_domain'];
    }else {
        
        // 支付配置获取失败
        $result = array(
            'code' => 201,
            'msg' => '支付配置获取失败'
        );
        echo json_encode($result,JSON_UNESCAPED_UNICODE);
        exit;
    }
    
    // 初始化cURL会话
    $ch = curl_init();
    
    // 请求的URL
    $url = $payapi_domain.'/mapi.php';
    curl_setopt($ch, CURLOPT_URL, $url);
    
    // POST请求
    curl_setopt($ch, CURLOPT_POST, true);
    
    // 密钥
    $key = $payapi_merchant_key;
    
    // 获取common目录URL
    $common_url = $qywx_auth_domain . dirname(dirname($_SERVER["REQUEST_URI"]));
    
    // 订单号生成规则
    $order_num = date('Ymd').rand(100000,999999);
    
    // 设置POST字段
    $data = array(
        'pid' => $payapi_merchant_id,
        'type' => 'wxpay',
        'out_trade_no' => $order_num,
        'notify_url' => $common_url.'/addchatroombyinvite/notify_url.php', // 异步通知Url
        'return_url' => $common_url.'/addchatroombyinvite/cgi-bin/qr/return.php', // 同步通知Url
        'name' => '付费群', // 如果希望订单标题改为群名称则改为 $chatroom_name（不用带引号）
        'money' => $chatroom_amount,
        'clientip' => getClientIP(),
        'device' => 'wechat',
        'param' => $openid.'|'.$chatroom_id.'|'.$chatroom_name // // 自定义业务参数
    );
    
    // 生成签名
    $data['sign'] = generate_sign($data, $key);
    $data['sign_type'] = 'MD5';
    
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
    
    // 返回响应而不是直接输出
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    
    // 执行cURL请求并获取响应
    $response = curl_exec($ch);
    
    // 检查是否有错误
    if (curl_errno($ch)) {
        
        // 订单创建失败
        $result = array(
            'code' => 202,
            'msg' => '订单创建失败：' . curl_error($ch)
        );
    } else {
        
        if(json_decode($response)->code == 1) {
            
            // 订单创建成功
            $createOrderParams = [
                'order_num' => $order_num,
                'chatroom_id' => $chatroom_id,
                'chatroom_name' => $chatroom_name,
                'order_amount' => $chatroom_amount,
                'order_paytype' => 'wxpay',
                'order_openid' => $openid,
                'order_ip' => getClientIP(),
                'Action_User' => $chatroom_create_user,
            ];
            
            // 执行创建
            $db->set_table('ylb_ChatroomPayOrders')->add($createOrderParams);
    
            $result = array(
                'code' => 200,
                'msg' => '订单创建成功',
                'payurl' => json_decode($response)->payurl
            );
        }else {
            
            // 易支付订单创建失败
            if(json_decode($response)->msg) {
               
               // 弹出发生错误的原因
               $result = array(
                    'code' => 201,
                    'msg' => json_decode($response)->msg
                ); 
            }else {
                
                // 弹出具体的错误信息
                $result = array(
                    'code' => 201,
                    'msg' => $response
                );
            }
        }
    }
    
    // 关闭cURL会话
    curl_close($ch);
    
    // 返回JSON
    echo json_encode($result,JSON_UNESCAPED_UNICODE);
    
?>
