<?php
/**
 * User: 呆呆
 * Agreement: 禁止使用本软件（系统）用于任何违法违规业务或项目,造成的任何法律后果允由使用者（或运营者）承担
 * Date: 2021/3/3
 * Time: 14:34
 */
namespace app\common\zfb_dmf\controller;//跟目录路径一样
use think\Db;
use think\Controller;

class Index extends Controller
{
    public function getReturn($code = 1, $data = "成功", $json = null)//系统需，要不要动
    {
        return array("code" => $code, "data" => $data, "json" => $json);
    }

    public function Cookie($atad)//监控心跳
    {
        $code = 1;
        $data = '该通道不支持监控心跳';
        return $this->getReturn($code,$data,array("time"=>time()));
    }
    
    public function cehsald($atad,$api='')//监控回调
    {
        if(!$api){
            return $this->getReturn(-1, '交易失败', $atad);
        }
        $row = Db::name("pay_gfg")->where("pid", $atad['pid'])->where("mid",$atad['mid'])->find();
        $priKey = $row['bfbf'];
        $result = $this->rsaCheck($api,$priKey);
        if($result===true){
           return $this->getReturn(1, '交易成功', $atad); 
        }else{
           return $this->getReturn(-1, '交易失败', $atad); 
        }
    }
    
    public function fukyem($data)//支付页面
    {
        $sz = Db::name("pay_sz")->find();
        $atad= Db::name("pay_gfg")->where("pid", $data['pid'])->where("mid", $data['mid'])->find();
        $user = Db::name("pay_user")->where("id", $data['pid'])->find();
        $data['timeOut'] = $user['bug_close'];//订单有效期
        
        if($atad['ms']==0){//H5
            return redirect($data['mid_url']);
        }else{//扫码
            $data['src'] = url('enQrcode').'?url='.$data['mid_url'];//二维码
            // 模板变量赋值
            $data['luji'] = iphtml('pay');//模板路径
            $this->assign('data',$data);
            return $this->fetch(ippublic('pay').'/index.html');
        }
    }
    
    public function exec($api,$atad,$money,$type)//拉起支付
    {
        if(!config("ms")){//回调通知地址
            $notify_url = url('/pay/index/api_notify','','html',true);
        }else{
            $notify_url = url('api_notify','','html',true);
        }
        $appid = $atad['zhanghao'];//https://open.alipay.com 账户中心->密钥管理->开放平台密钥，填写添加了电脑网站支付的应用的APPID
        $notifyUrl = $notify_url;//付款成功后的异步回调地址
        $outTradeNo = time().uniqid().uniqid();//你自己的商品订单号，不能重复
        $payAmount = $money;//付款金额，单位:元
        $orderName = '公益捐赠';//订单标题
        $signType = 'RSA2';//签名算法类型，支持RSA2和RSA，推荐使用RSA2
        $rsaPrivateKey=$atad['bf'];//商户私钥，填写对应签名算法类型的私钥，如何生成密钥参考：https://docs.open.alipay.com/291/105971和https://docs.open.alipay.com/200/105310
        //请求参数
        $requestConfigs = array(
            'out_trade_no'=>$outTradeNo,
            'total_amount'=>$payAmount, //单位 元
            'subject'=>$orderName,  //订单标题
            'timeout_express'=>'2h'       //该笔订单允许的最晚付款时间，逾期将关闭交易。取值范围：1m～15d。m-分钟，h-小时，d-天，1c-当天（1c-当天的情况下，无论交易何时创建，都在0点关闭）。 该参数数值不接受小数点， 如 1.5h，可转换为 90m。
        );
        $commonConfigs = array(
            //公共参数
            'app_id' => $appid,
            'method' => 'alipay.trade.precreate',//接口名称
            'format' => 'JSON',
            'charset'=> 'utf-8',
            'sign_type'=>'RSA2',
            'timestamp'=>date('Y-m-d H:i:s'),
            'version'=>'1.0',
            'notify_url' => $notifyUrl,
            'biz_content'=>json_encode($requestConfigs),
        );
        $sign = $this->sign($rsaPrivateKey,$this->getSignContent($commonConfigs), $commonConfigs['sign_type']);
        if(!$sign){
            return $this->getReturn(-1, $atad['typec_name']."您使用的私钥格式错误，请检查RSA私钥配置");
        }
        $commonConfigs["sign"] = $sign;
        $result = $this->curlPost('https://openapi.alipay.com/gateway.do?charset=utf-8',$commonConfigs);
        $json = json_decode($result,TRUE);
        $json = $json['alipay_trade_precreate_response'];
        if($json['code'] && $json['code']=='10000'){
            $atad['pay_id'] = $json['out_trade_no'];//通道订单号
            $atad['mid_url'] = $json['qr_code'];//通道二维码
            return $this->getReturn(1, $atad, $ret);
        }else if($json['sub_msg']=='缺少签名参数'){
            return $this->getReturn(-1, $atad['typec_name'].'商户私钥错误');
        }else{
            return $this->getReturn(-1, $atad['typec_name'].$json['sub_msg']);
        }
    }
    
    protected function sign($priKey,$data, $signType = "RSA") {
        error_reporting(0);
        $res = "-----BEGIN RSA PRIVATE KEY-----\n" .
            wordwrap($priKey, 64, "\n", true) .
            "\n-----END RSA PRIVATE KEY-----";
        ($res) or die('');
        if ("RSA2" == $signType) {
            openssl_sign($data, $sign, $res, version_compare(PHP_VERSION,'5.4.0', '<') ? SHA256 : OPENSSL_ALGO_SHA256); //OPENSSL_ALGO_SHA256是php5.4.8以上版本才支持
        } else {
            openssl_sign($data, $sign, $res);
        }
        $sign = base64_encode($sign);
        return $sign;
    }
    protected function checkEmpty($value) {
        if (!isset($value))
            return true;
        if ($value === null)
            return true;
        if (trim($value) === "")
            return true;
        return false;
    }
    public function getSignContent($params) {
        ksort($params);
        $stringToBeSigned = "";
        $i = 0;
        foreach ($params as $k => $v) {
            if (false === $this->checkEmpty($v) && "@" != substr($v, 0, 1)) {
                // 转换成目标字符集
                $v = $this->characet($v, 'utf-8');
                if ($i == 0) {
                    $stringToBeSigned .= "$k" . "=" . "$v";
                } else {
                    $stringToBeSigned .= "&" . "$k" . "=" . "$v";
                }
                $i++;
            }
        }
        unset ($k, $v);
        return $stringToBeSigned;
    }
    function characet($data, $targetCharset) {
        if (!empty($data)) {
            $fileType = 'utf-8';
            if (strcasecmp($fileType, $targetCharset) != 0) {
                $data = mb_convert_encoding($data, $targetCharset, $fileType);
                //$data = iconv($fileType, $targetCharset.'//IGNORE', $data);
            }
        }
        return $data;
    }
    public function curlPost($url = '', $postData = '', $options = array())
    {
        if (is_array($postData)) {
            $postData = http_build_query($postData);
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30); //设置cURL允许执行的最长秒数
        if (!empty($options)) {
            curl_setopt_array($ch, $options);
        }
        //https请求 不验证证书和host
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }
    
    public function rsaCheck($params,$priKey) {
        $sign = $params['sign'];
        $signType = $params['sign_type'];
        unset($params['sign_type']);
        unset($params['sign']);
        return $this->verify($priKey,$this->getSignContent($params),$sign,$signType);
    }
    
    public function verify($priKey,$data,$sign,$signType = 'RSA') {
        
        $res = "-----BEGIN PUBLIC KEY-----\n" .
            wordwrap($priKey, 64, "\n", true) .
            "\n-----END PUBLIC KEY-----";
        ($res) or die('');
        //调用openssl内置方法验签，返回bool值
        if ("RSA2" == $signType) {
            $result = (bool)openssl_verify($data, base64_decode($sign), $res, version_compare(PHP_VERSION,'5.4.0', '<') ? SHA256 : OPENSSL_ALGO_SHA256);
        } else {
            $result = (bool)openssl_verify($data, base64_decode($sign), $res);
        }
        return $result;
    }
    
}