<?php
/*
 本代码由 焕岱科技 创建
 技术支持 WX：15285007200
 严禁反编译、逆向等任何形式的侵权行为，违者将追究法律责任
*/

namespace app\common\model\bbfxshop;
use think\Db;
// 接口文档：https://paas.huifu.com/open/home/
// 开放平台：https://dashboard.huifu.com/partners/welcome

class Dougong
{

    public function getSet(){
        global $_W;
        $base = $_W['base'];

        $platform = Db::name("platform")->where(['id'=>UNIACID])->find();

        $config = [
            'status'=>$platform['dg_status'],
            'dg_status'=>$platform['dg_status'],
            'dg_fenzhang'=>$platform['dg_fenzhang'],
            'dg_fenzhang_rate'=>$platform['dg_fenzhang_rate'],
            'rsaPrivateKey'=>$platform['dg_rsaPrivateKey'],
            'rsaPublicKey'=>$platform['dg_rsaPublicKey'],
            'sys_id'=>$platform['dg_sys_id'],
            'product_id'=>$platform['dg_product_id'],
            'dg_wxapp_huifu_id'=>$platform['dg_wxapp_huifu_id'],
            'dg_gzh_huifu_id'=>$platform['dg_gzh_huifu_id'],
            'dg_zfb_huifu_id'=>$platform['dg_zfb_huifu_id'],
            'dg_huifu_id'=>$platform['dg_huifu_id'],
            'dg_quxian_fee_rate'=>$platform['dg_quxian_fee_rate'],
            'dg_quxian_out_fee_flag'=>$platform['dg_quxian_out_fee_flag'],
            'AppId'=>$platform['AppId'],
            'wxapp_AppId'=>$platform['wxapp_AppId']
        ];

        return $config;
    }

    public function number($money){
        $money = number_format($money, 2, '.', '');
        return (string)$money;
    }

    // 订单支付
    public function pay($params,$type){

        $config = $this->getSet();

        if(empty($params['order_trade_no'])){
            return __json(0,"缺失订单编号");
        }
        if(empty($params['fee'])){
            return __json(0,"缺失订单金额");
        }
        if(empty($config['dg_huifu_id'])){
            return __json(0,"未配置商户号");
        }

        $acct_split_bunch = [
            'acct_infos'=>[
                [
                    'div_amt'=>$this->number(2.20),
                    'huifu_id'=>'xxxx'
                ],
                [
                    'div_amt'=>$this->number(0.80),
                    'huifu_id'=>'xxxx'
                ]
            ]
        ];

        $data = [
            'req_date'=>date('Ymd'),
            'req_seq_id'=>$params['order_trade_no'],
            'huifu_id'=>$config['dg_huifu_id'],
            'trans_amt'=>$this->number($params['fee']),
            'delay_acct_flag'=>'N',
            'goods_desc'=>$params['title'],
            'remark'=>$params['type'],
            'notify_url'=>request()->domain()."/api/pay/dgNotify/i/".UNIACID,
            'time_expire'=>date('YmdHis',strtotime("+1 day")),
            // 'acct_split_bunch'=>json_encode($acct_split_bunch)
        ];

        if($config['dg_fenzhang'] == 1){
            $data['delay_acct_flag'] = 'Y';
        }

        if($type == 1 && ($params['type'] == 'wxapp' || $params['type'] == 'WXAPP')){
            if(empty($params['openid'])){
                return __json(0,"缺失用户openid");
            }
            // $data['huifu_id'] = $config['dg_wxapp_huifu_id'];
            $data['trade_type'] = 'T_MINIAPP';
            $data['method_expand'] = [
                'sub_appid'=>$config['wxapp_AppId'],
                'sub_openid'=>$params['openid'],
                'attach'=>$params['type'],
                'body'=>$params['title'],
            ];
        }
        else if($type == 1 && $params['type'] == 'GZH'){
            if(empty($params['openid'])){
                return __json(0,"缺失用户openid");
            }
            // $data['huifu_id'] = $config['dg_gzh_huifu_id'];
            $data['trade_type'] = 'T_JSAPI';
            $data['method_expand'] = [
                'sub_appid'=>$config['AppId'],
                'sub_openid'=>$params['openid'],
                'attach'=>$params['type'],
                'body'=>$params['title'],
            ];
        }
        else if($type == 1 && ($params['type'] == 'APP' || $params['type'] == 'H5')){
            $data['trade_type'] = 'T_APP';
            $data['method_expand'] = [
                'attach'=>$params['type'],
                'body'=>$params['title'],
            ];
        }
        else if($type == 5){
            // $data['huifu_id'] = $config['dg_zfb_huifu_id'];
            $data['trade_type'] = 'A_NATIVE';
            $data['method_expand'] = [
                'subject'=>$params['title'],
                'body'=>$params['title'],
            ];
        }
        else{
            return __json(0,"不支持该交易类型");
        }

        $data['method_expand'] = json_encode($data['method_expand']);

        $sign = $this->getSign($data,$config['rsaPrivateKey']);

        $post_data = [
            'sys_id'=>$config['sys_id'],
            'product_id'=>$config['product_id'],
            'sign'=>$sign,
            'data'=>$data,
        ];
        
        // echo "<pre>";
        // print_r($post_data);die;
        $url = 'https://api.huifu.com/v4/trade/payment/create';
        $result = $this->request($url,'POST',$post_data);
 
        addFileLog("dg_dd",json_encode($post_data));
        addFileLog("dg",json_encode($result));

        if($result['data']['resp_code'] == '00000100'){
            if($type == 1){
                
                $pay_info = json_decode($result['data']['pay_info'],true);

                if($params['type'] == 'GZH'){
                    $pay_info['timestamp'] = $pay_info['timeStamp'];
                    unset($pay_info['timeStamp']);
                    unset($pay_info['appId']);
                }

                return __json(1,"操作成功",$pay_info);
            }
            else if($type == 5){
                return __json(1,"操作成功",['url'=>$result['data']['qr_code']]);
            }
            return __json(0,"不支持该交易类型");
        }

        $message = $result['data']['resp_desc'];
        if(!empty($result['data']['bank_message'])){
            $message .= "，".$result['data']['bank_message'];
        }

        $message = $result['data']['resp_desc'];
        if(empty($message)) $message = "接口调用失败";

        return __json(0,$message,$result);
    }

    // 分账
    public function fenzhang($params){
        $config = $this->getSet();

        $data = [
            'req_date'=>date('Ymd'),
            'req_seq_id'=>$params['req_seq_id'],
            'huifu_id'=>$config['dg_huifu_id'],
            'org_req_date'=>$params['org_req_date'],
            'org_req_seq_id'=>$params['order_trade_no'],
            'acct_split_bunch'=>[
                'acct_infos'=>$params['acct_infos']
            ],
            'notify_url'=>request()->domain()."/api/pay/dgFenzhangNotify/i/".UNIACID,
        ];

        $sign = $this->getSign($data,$config['rsaPrivateKey']);

        $post_data = [
            'sys_id'=>$config['sys_id'],
            'product_id'=>$config['product_id'],
            'sign'=>$sign,
            'data'=>$data,
        ];
        
        // echo "<pre>";
        // print_r($post_data);die;
        $url = 'https://api.huifu.com/v2/trade/payment/delaytrans/confirm';
        $result = $this->request($url,'POST',$post_data);

        addFileLog("dgfz_dd",json_encode($post_data));
        addFileLog("dgfz",json_encode($result));

        if($result['data']['resp_code'] == '00000100' || $result['data']['resp_code'] == '00000000'){
            return __json(1,"操作成功",$result['data']);
        }

        $message = $result['data']['resp_desc'];
        if(empty($message)) $message = "接口调用失败";

        return __json(0,$message,$result);
    }

    // 查询商户基本信息
    public function queryMerch($huifu_id){
        $config = $this->getSet();

        $data = [
            'req_date'=>date('Ymd'),
            'req_seq_id'=>date('YmdHis').random(8,true),
            'huifu_id'=>$huifu_id
        ];

        $sign = $this->getSign($data,$config['rsaPrivateKey']);

        $post_data = [
            'sys_id'=>$config['sys_id'],
            'product_id'=>$config['product_id'],
            'sign'=>$sign,
            'data'=>$data,
        ];
        
        // echo "<pre>";
        // print_r($post_data);die;
        $url = 'https://api.huifu.com/v2/merchant/basicdata/query';
        $result = $this->request($url,'POST',$post_data);

        if($result['data']['resp_code'] == '00000100' || $result['data']['resp_code'] == '00000000'){
            return __json(1,"操作成功",$result['data']);
        }

        $message = $result['data']['resp_desc'];
        if(empty($message)) $message = "接口调用失败";

        return __json(0,$message,$result);
    }

    // 订单退款
    public function refund($params,$type){

        $config = $this->getSet();

        $data = [
            'req_date'=>date('Ymd'),
            'req_seq_id'=>$params['out_refund_no'],
            'huifu_id'=>'',
            'ord_amt'=>$params['refund_fee'],
            'org_req_date'=>$params['org_req_date'],
            'org_req_seq_id'=>$params['order_trade_no'],
            'notify_url'=>request()->domain()."/api/pay/dgRefundNotify/i/".UNIACID,
        ];
        $data['huifu_id'] = $config['dg_huifu_id'];
        if($type == 1 && ($params['platform'] == 'wxapp' || $params['platform'] == 'WXAPP')){
            // $data['huifu_id'] = $config['dg_wxapp_huifu_id'];
        }
        else if($type == 1 && $params['platform'] == 'GZH'){
            // $data['huifu_id'] = $config['dg_gzh_huifu_id'];
        }
        else if($type == 5){
            // $data['huifu_id'] = $config['dg_zfb_huifu_id'];
        }
        else{
            return __json(0,"不支持该交易类型");
        }

        $sign = $this->getSign($data,$config['rsaPrivateKey']);

        $post_data = [
            'sys_id'=>$config['sys_id'],
            'product_id'=>$config['product_id'],
            'sign'=>$sign,
            'data'=>$data,
        ];
        
        // echo "<pre>";
        // print_r($post_data);die;
        $url = 'https://api.huifu.com/v4/trade/payment/scanpay/refund';
        $result = $this->request($url,'POST',$post_data);

        addFileLog("dg_r_dd",json_encode($post_data));
        addFileLog("dg_r",json_encode($result));

        if($result['data']['resp_code'] == '00000100' || $result['data']['resp_code'] == '00000000'){
            return __json(1,"操作成功",$result['data']);
        }

        $message = $result['data']['resp_desc'];
        if(empty($message)) $message = "接口调用失败";

        return __json(0,$message,$result);
    }


    // 查询订单
    public function query($order_no,$req_date){

        if(empty($order_no)){
            return __json(0,'订单编号不能为空');
        }

        $config = $this->getSet();
        $url = 'https://api.huifu.com/v4/trade/payment/scanpay/query';
        $data = [
            'huifu_id'=>$config['huifu_id'],
            'req_date'=>$req_date,
            'req_seq_id'=>$order_no
        ];
        $sign = $this->getSign($data,$config['rsaPrivateKey']);
        $post_data = [
            'sys_id'=>$config['sys_id'],
            'product_id'=>$config['product_id'],
            'sign'=>$sign,
            'data'=>$data,
        ];
        $result = $this->request($url,'POST',$post_data);
        if($result['data']['resp_code'] == '00000000'){
            return __json(1,"查询成功",$result['data']);
        }
        
        $message = $result['data']['resp_desc'];
        if(empty($message)) $message = "接口调用失败";

        return __json(0,$message,$result);
    }

    // 用户进件-个人用户开户
    public function kaihu($params){
        $config = $this->getSet();
        
        if(!empty($params['huifu_id'])){
            $url = 'https://api.huifu.com/v2/user/basicdata/indv/modify';
            $data = [
                'req_seq_id'=>date('YmsHis').random(8,true),
                'req_date'=>date('Ymd'),
                'cert_validity_type'=>(string)$params['cert_validity_type'],
                'cert_begin_date'=>date('Ymd',strtotime($params['cert_begin_date'])),
                'mobile_no'=>$params['mobile_no'],
                'huifu_id'=>$params['huifu_id'],
            ];
        }
        else{
            $url = 'https://api.huifu.com/v2/user/basicdata/indv';
            $data = [
                'req_seq_id'=>date('YmsHis').random(8,true),
                'req_date'=>date('Ymd'),
                'name'=>$params['name'],
                'cert_type'=>(string)$params['cert_type'],
                'cert_no'=>$params['cert_no'],
                'cert_validity_type'=>(string)$params['cert_validity_type'],
                'cert_begin_date'=>date('Ymd',strtotime($params['cert_begin_date'])),
                'mobile_no'=>$params['mobile_no'],
            ];
        }

        if($data['cert_validity_type'] === '0'){
            $data['cert_end_date'] = date('Ymd',strtotime($params['cert_end_date']));
        }
        
        $sign = $this->getSign($data,$config['rsaPrivateKey']);
        $post_data = [
            'sys_id'=>$config['sys_id'],
            'product_id'=>$config['product_id'],
            'sign'=>$sign,
            'data'=>$data,
        ];
        $result = $this->request($url,'POST',$post_data);
        addFileLog("dgkh_dd",json_encode($post_data));
        addFileLog("dgkh",json_encode($result));
        if($result['data']['resp_code'] == '00000000'){
            return __json(1,"操作成功",$result['data']);
        }

        $message = $result['data']['resp_desc'];
        if(empty($message)) $message = "接口调用失败";

        return __json(0,$message,$result);
    }

    // 用户进件-用户业务入驻
    public function ruzhu($params){
        $config = $this->getSet();

        $settle_config = [
            'settle_cycle'=>'D1',
            'min_amt'=>'0.01',
            'remained_amt'=>'0.01',
            'out_settle_flag'=>'2',
            'settle_pattern'=>'P0',
            'settle_batch_no'=>'100',
            'is_priority_receipt'=>'Y',
            'fixed_ratio'=>'0.00',
            'workday_fixed_ratio'=>'0.00',
            'workday_constant_amt'=>'0.00',
            'constant_amt'=>'0.00'
        ];
        $cash_config = [
            [
                'switch_state'=>'1',
                'cash_type'=>'D1',
                // 'fix_amt'=>'0.00',
                'fee_rate'=>$this->number($config['dg_quxian_fee_rate']),
                // 'out_fee_flag'=>$config['dg_quxian_out_fee_flag'],
                // 'weekday_fee_rate'=>'0.00',
                // 'weekday_fix_amt'=>'0.00'
            ]
        ];
        if(!empty($params['token_no'])){
            $settle_config['settle_status'] = '1';
            $cash_config[0]['switch_state'] = '1';
        }

        $data = [
            'req_seq_id'=>date('YmsHis').random(8,true),
            'req_date'=>date('Ymd'),
            'huifu_id'=>$params['huifu_id'],
            'upper_huifu_id'=>$config['dg_huifu_id'],
            // 'settle_config'=>$settle_config,
            'card_info'=>[
                'card_type'=>(string)$params['card_type'],
                'card_name'=>$params['name'],
                'card_no'=>$params['card_no'],
                'prov_id'=>$params['prov_id'],
                'area_id'=>$params['area_id'], 
                'cert_type'=>(string)$params['cert_type'], 
                'cert_no'=>$params['cert_no'],
                'cert_validity_type'=>(string)$params['cert_validity_type'],
                'cert_begin_date'=>date('Ymd',strtotime($params['cert_begin_date'])),
            ],
            'cash_config'=>$cash_config,
            'async_return_url'=>request()->domain()."/api/pay/dgRuzhuNotify/i/".UNIACID,
        ];

        if($data['card_info']['cert_validity_type'] === '0'){
            $data['card_info']['cert_end_date'] = date('Ymd',strtotime($params['cert_end_date']));
        }

        // $data['settle_config'] = json_encode($data['settle_config']);
        $data['card_info'] = json_encode($data['card_info']);
        $data['cash_config'] = json_encode($data['cash_config']);

        if($params['qx_status'] == 1){
            $url = 'https://api.huifu.com/v2/user/busi/modify';
        }
        else{
            $url = 'https://api.huifu.com/v2/user/busi/open';
            $data['upper_huifu_id'] = $config['dg_huifu_id'];
        }
        
        $sign = $this->getSign($data,$config['rsaPrivateKey']);
        $post_data = [
            'sys_id'=>$config['sys_id'],
            'product_id'=>$config['product_id'],
            'sign'=>$sign,
            'data'=>$data,
        ];
        $result = $this->request($url,'POST',$post_data);
        addFileLog("dgrz_dd",json_encode($post_data));
        addFileLog("dgrz",json_encode($result));
        if($result['data']['resp_code'] == '00000000'){
            return __json(1,"操作成功",$result['data']);
        }

        $message = $result['data']['resp_desc'];
        if(empty($message)) $message = "接口调用失败";

        return __json(0,$message,$result);
    }

    // 余额支付
    public function balancePay($params){
        if(empty($params['ord_amt'])){
            return __json(0,'支付金额不能为空');
        }
        if($params['huifu_id'] <= 0){
            return __json(0,'用户商户号不能为空');
        }
        if($params['req_seq_id'] <= 0){
            return __json(0,'取现金额不能为空');
        }
        $config = $this->getSet();
        $url = 'https://api.huifu.com/v2/trade/acctpayment/pay';

        $acct_split_bunch = [
            'acct_infos'=>[
                [
                    'div_amt'=>$this->number($params['ord_amt']),
                    'huifu_id'=>$params['huifu_id']
                ]
            ]
        ];

        $risk_check_data = [
            'transfer_type'=>'05'
        ];

        $data = [
            'out_huifu_id'=>$config['dg_huifu_id'],
            'req_date'=>date('Ymd'),
            'req_seq_id'=>$params['req_seq_id'],
            'ord_amt'=>$this->number($params['ord_amt']),
            'acct_split_bunch'=>json_encode($acct_split_bunch),
            'risk_check_data'=>json_encode($risk_check_data),
            'notify_url'=>request()->domain()."/api/pay/dgBalancePayNotify/i/".UNIACID,
        ];
        $sign = $this->getSign($data,$config['rsaPrivateKey']);
        $post_data = [
            'sys_id'=>$config['sys_id'],
            'product_id'=>$config['product_id'],
            'sign'=>$sign,
            'data'=>$data,
        ];
        $result = $this->request($url,'POST',$post_data);
        addFileLog("dgyezf_dd",json_encode($post_data));
        addFileLog("dgyezf",json_encode($result));
        if($result['data']['resp_code'] == '00000000'){
            return __json(1,"支付成功",$result['data']);
        }
        
        $message = $result['data']['resp_desc'];
        if(empty($message)) $message = "接口调用失败";

        return __json(0,$message,$result);
    }

    // 手动取现
    public function quxian($params){
        if($params['cash_amt'] <= 0){
            return __json(0,'取现金额不能为空');
        }
        if(empty($params['huifu_id'])){
            return __json(0,'取现方ID号不能为空');
        }
        if(empty($params['req_seq_id'])){
            return __json(0,'流水号不能为空');
        }

        $config = $this->getSet();
        $url = 'https://api.huifu.com/v2/trade/settlement/encashment';
        $data = [
            'huifu_id'=>$params['huifu_id'],
            'req_date'=>date('Ymd'),
            'req_seq_id'=>$params['req_seq_id'],
            'cash_amt'=>$params['cash_amt'],
            'into_acct_date_type'=>'D1',
            'token_no'=>$params['token_no'],
            'notify_url'=>request()->domain()."/api/pay/dgQuxianNotify/i/".UNIACID,
        ];
        $sign = $this->getSign($data,$config['rsaPrivateKey']);
        $post_data = [
            'sys_id'=>$config['sys_id'],
            'product_id'=>$config['product_id'],
            'sign'=>$sign,
            'data'=>$data,
        ];
        $result = $this->request($url,'POST',$post_data);
        addFileLog("dgqx_dd",json_encode($post_data));
        addFileLog("dgqx",json_encode($result));
        if($result['data']['resp_code'] == '00000000'){
            return __json(1,"查询成功",$result['data']);
        }
        
        $message = $result['data']['resp_desc'];
        if(empty($message)) $message = "接口调用失败";

        return __json(0,$message,$result);
    }

    // 查询账户
    public function queryAcct($huifu_id){
        $url = "https://api.huifu.com/v2/trade/acctpayment/balance/query";
        if(empty($huifu_id)){
            return __json(0,'商户号不能为空');
        }
        $config = $this->getSet();
        $order_no = date('YmdHis').random(8,true);
        $data = [
            'huifu_id'=>$huifu_id,
            'req_date'=>date('Ymd'),
            'req_seq_id'=>$order_no
        ];
        $sign = $this->getSign($data,$config['rsaPrivateKey']);
        $post_data = [
            'sys_id'=>$config['sys_id'],
            'product_id'=>$config['product_id'],
            'sign'=>$sign,
            'data'=>$data,
        ];
        $result = $this->request($url,'POST',$post_data);
        if($result['data']['resp_code'] == '00000000'){
            return __json(1,"查询成功",$result['data']);
        }
        
        $message = $result['data']['resp_desc'];
        if(empty($message)) $message = "接口调用失败";

        return __json(0,$message,$result);
    }

    // 用户信息查询
    public function queryUser($huifu_id){
        if(empty($huifu_id)){
            return __json(0,'商户号不能为空');
        }

        $config = $this->getSet();
        $url = 'https://api.huifu.com/v2/user/basicdata/query';
        $order_no = date('YmdHis').random(8,true);
        $data = [
            'huifu_id'=>$huifu_id,
            'req_date'=>date('Ymd'),
            'req_seq_id'=>$order_no
        ];
        $sign = $this->getSign($data,$config['rsaPrivateKey']);
        $post_data = [
            'sys_id'=>$config['sys_id'],
            'product_id'=>$config['product_id'],
            'sign'=>$sign,
            'data'=>$data,
        ];
        $result = $this->request($url,'POST',$post_data);
        if($result['data']['resp_code'] == '00000000'){
            return __json(1,"查询成功",$result['data']);
        }
        
        $message = $result['data']['resp_desc'];
        if(empty($message)) $message = "接口调用失败";

        return __json(0,$message,$result);
    }

    // 用户申请状态查询
    public function queryUserStatus($params){
        if(empty($params['huifu_id'])){
            return __json(0,'商户号不能为空');
        }
        if(empty($params['apply_no'])){
            return __json(0,'申请单号不能为空');
        }

        $config = $this->getSet();
        $url = 'https://api.huifu.com/v2/user/apply/query';
        $order_no = date('YmdHis').random(8,true);
        $data = [
            'huifu_id'=>$params['huifu_id'],
            'req_date'=>date('Ymd'),
            'req_seq_id'=>$order_no,
            'apply_no'=>$params['apply_no'],
        ];
        $sign = $this->getSign($data,$config['rsaPrivateKey']);
        $post_data = [
            'sys_id'=>$config['sys_id'],
            'product_id'=>$config['product_id'],
            'sign'=>$sign,
            'data'=>$data,
        ];
        $result = $this->request($url,'POST',$post_data);
        if($result['data']['resp_code'] == '00000000'){
            return __json(1,"查询成功",$result['data']);
        }
        
        $message = $result['data']['resp_desc'];
        if(empty($message)) $message = "接口调用失败";

        return __json(0,$message,$result);
    }

    // 银行卡代发
    public function tixian($params){
        $config = $this->getSet();
        if($config['status'] != 1){
            return __json(0,'未开启汇付功能');
        }
        if($params['cash_amt'] <= 0){
            return __json(0,'提现金额不能为空');
        }
        if(empty($params['req_seq_id'])){
            return __json(0,'请求流水号不能为空');
        }
        if(empty($params['prov_id'])){
            return __json(0,'省份不能为空');
        }
        if(empty($params['area_id'])){
            return __json(0,'地区不能为空');
        }
        if(empty($params['name'])){
            return __json(0,'银行卡用户名不能为空');
        }
        if(empty($params['card_no'])){
            return __json(0,'银行卡号不能为空');
        }
        if(empty($params['cert_no'])){
            return __json(0,'身份证号不能为空');
        }
        if(empty($params['purpose_desc'])){
            $params['purpose_desc'] = "提现";
        }
        // echo "<pre>";
        // print_r($params);die;
        
        
        $certificate_no_crypt = $this->rsaCrypt($params['cert_no'],$config['rsaPublicKey']);
        $bank_card_no_crypt = $this->rsaCrypt($params['card_no'],$config['rsaPublicKey']);
        

        $config = $this->getSet();
        $url = "https://api.huifu.com/v2/trade/settlement/surrogate";
        $data = [
            'huifu_id'=>$config['dg_huifu_id'],
            'req_date'=>date('Ymd'),
            'req_seq_id'=>$params['req_seq_id'],
            'cash_amt'=>$this->number($params['cash_amt']),
            'purpose_desc'=>$params['purpose_desc'],
            'province'=>$params['prov_id'],
            'area'=>$params['area_id'],
            'bank_account_name'=>$params['name'],
            'card_acct_type'=>'P',
            'bank_card_no_crypt'=>$bank_card_no_crypt,
            'certificate_no_crypt'=>$certificate_no_crypt,
            'certificate_type'=>'01',
            'into_acct_date_type'=>'D1',
            'notify_url'=>request()->domain()."/api/pay/dgTixianNotify/i/".UNIACID,
        ];

        if(!empty($params['subbranch_bank_name'])){
            $data['subbranch_bank_name'] = $params['subbranch_bank_name'];
        }

        $sign = $this->getSign($data,$config['rsaPrivateKey']);
        $post_data = [
            'sys_id'=>$config['sys_id'],
            'product_id'=>$config['product_id'],
            'sign'=>$sign,
            'data'=>$data,
        ];

        // echo "<pre>";
        // print_r($post_data);die;

        $result = $this->request($url,'POST',$post_data);
        addFileLog("dgtx_dd",json_encode($post_data));
        addFileLog("dgtx",json_encode($result));
        if($result['data']['resp_code'] == '00000000'){
            return __json(1,"查询成功",$result['data']);
        }
        
        $message = $result['data']['resp_desc'];
        if(empty($message)) $message = "接口调用失败";

        return __json(0,$message,$result);
    }

    // 商户业务开通
    public function kaitongYewu($params){
        $config = $this->getSet();
        if($config['status'] != 1){
            return __json(0,'未开启汇付功能');
        }
        if(empty($params['req_seq_id'])){
            return __json(0,'请求流水号不能为空');
        }
        // echo "<pre>";
        // print_r($params);die;
        
        
        $certificate_no_crypt = $this->rsaCrypt($params['cert_no'],$config['rsaPublicKey']);
        $bank_card_no_crypt = $this->rsaCrypt($params['card_no'],$config['rsaPublicKey']);
        
        // 接口文档：https://paas.huifu.com/open/doc/api/#/shgl/shywkt/api_shjj_shywkt_kyc
        $config = $this->getSet();
        $url = "https://api.huifu.com/v2/merchant/busi/open";
        $data = [
            'huifu_id'=>$config['dg_huifu_id'],
            'upper_huifu_id'=>$config['sys_id'],
            'req_date'=>date('Ymd'),
            'req_seq_id'=>$params['req_seq_id'],
            'surrogate_config_list'=>[
                [
                    'surrogate_type'=>'D0',
                    'fix_amt'=>'0.00',
                    'fee_rate'=>'0.00',
                    'surrogate_private_flag'=>'Y',
                    'fee_formula_type'=>'06',
                    // 'fee_min_amt'=>'0.00'
                ]
            ],
            'agreement_info'=>[
                'agreement_type'=>'0',// 0-电子协议 1-纸质协议 3-挂网协议；
                // 'agreement_url'=>'https://cloudpnrcdn.oss-cn-shanghai.aliyuncs.com/opps/api/prod/download_file/PaymentServiceAgreement.htm',

            ],
            'sign_user_info'=>[
                'type'=>'LEGAL',
                'mobile_no'=>$params['mobile'],
            ],
            'async_return_url'=>request()->domain()."/api/pay/dgYewuNotify/i/".UNIACID,
            'busi_async_return_url'=>request()->domain()."/api/pay/dgYewuNotify1/i/".UNIACID,
        ];

        $data['surrogate_config_list'] = json_encode($data['surrogate_config_list']);
        $data['sign_user_info'] = json_encode($data['sign_user_info']);
        $data['agreement_info'] = json_encode($data['agreement_info']);

        $sign = $this->getSign($data,$config['rsaPrivateKey']);
        $post_data = [
            'sys_id'=>$config['sys_id'],
            'product_id'=>$config['product_id'],
            'sign'=>$sign,
            'data'=>$data,
        ];

        // echo "<pre>";
        // print_r($post_data);die;

        $result = $this->request($url,'POST',$post_data);
        addFileLog("dgshyw_dd",json_encode($post_data));
        addFileLog("dgshyw",json_encode($result));
        if($result['data']['resp_code'] == '00000000'){
            return __json(1,"查询成功",$result['data']);
        }
        
        $message = $result['data']['resp_desc'];
        if(empty($message)) $message = "接口调用失败";

        return __json(0,$message,$result);
    }

    public function rsaCrypt($data,$rsaPublicKey){
        $key = "-----BEGIN PUBLIC KEY-----\n".wordwrap($rsaPublicKey, 64, "\n", true)."\n-----END PUBLIC KEY-----";
        $str = '';
        openssl_public_encrypt($data, $str, $key);
        return base64_encode($str);
    }

    // 验证签名
    public function payVerify($sign,$data){
        $config = $this->getSet();
        $res = $this->verifySign($sign, $data, $config['rsaPublicKey']);
        if(!$res){

            if(is_string($data)){
                $data = json_encode($data,true);
            }

            $result = $this->query($data['req_seq_id'],$data['req_date']);
            
            if($result['code'] == 1){
                if($result['data']['trans_stat'] == 'S'){
                    $res = true;
                }
            }
        }
        if($res){
            return __json(1,"签名验证成功");
        }
        else{
            return __json(0,"签名验证失败");
        }
    }

    public function getSign($data,$rsaPrivateKey){
        ksort($data); 
        $data = json_encode($data, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);

        $key = "-----BEGIN PRIVATE KEY-----\n".wordwrap($rsaPrivateKey, 64, "\n", true)."\n-----END PRIVATE KEY-----";
        $signature= '';
        $alg = OPENSSL_ALGO_SHA256;
        try {
            openssl_sign($data, $signature, $key, $alg);
        } catch (\Exception $e) {
            // echo $e->getMessage();
        }
        return base64_encode($signature);
    }

    /**
     * 汇付公钥验签（对数据源排序），可用于 V2 版本接口返回数据验签
     *
     * @param string $signature 签文
     * @param array $data 原数据(array)
     * @param string $rsaPublicKey 公钥
     * @param int $alg 默认 OPENSSL_ALGO_SHA256
     *
     * @return false|int 验证结果：成功/失败
     */
    public function verifySign($signature, $data, $rsaPublicKey, $alg=OPENSSL_ALGO_SHA256){
        $key = "-----BEGIN PUBLIC KEY-----\n".wordwrap($rsaPublicKey, 64, "\n", true)."\n-----END PUBLIC KEY-----";
        
        if(is_array($data)){
            ksort($data);
            $data = json_encode($data, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);
        }

        return openssl_verify($data, base64_decode($signature), $key, $alg);
    }

    public function request($url,$method,$data,$headers=[]){

        if(empty($headers)){
            $headers = ["Content-Type".":"."application/json; charset=UTF-8"];
        }

        $querys = "";
        $bodys = json_encode($data);

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, false);
        if (1 == strpos("$".$url, "https://"))
        {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        curl_setopt($curl, CURLOPT_POSTFIELDS, $bodys);
        
        // 执行cURL会话
        $response = curl_exec($curl);
        // 检查是否有错误发生
        if (curl_errno($curl)) {
            return ['code'=>curl_error($curl),'msg'=>'Curl error: ' . curl_error($curl)];
        }
        // 关闭cURL资源
        curl_close($curl);
        if(is_string($response) && !empty($response)){
            $response1 = json_decode($response,true);
            if(!empty($response1)){
                $response = $response1;
            }
        }

        return $response;
    }
}