<?php

namespace app\common\library;

use think\Exception;

class SuningPay
{


    public function __construct(){
        $this->private_key = APP_PATH.'common/library/suning/private.pem';//私钥
        $this->public_key  = APP_PATH.'common/library/suning/public.pem';//公钥
        $this->wxappid = 'wxdada9bc45300a359';  //小程序id
       // $this->wxkey = 'UYko5ZEZHb9WrGL8Jws6Qr14kGkOBrxf';
    }

    /**
     * 微信支付
     * @return void
     */
    public function wechath5($params=[])
    {
        $result = [
            'status' => 1,
            'msg' => '',
            'data' => [],
        ];
        try {
            //交易地址
            $url = 'https://mfg.suning.com/ftpgs/trade/aggrpay/aggrProgramPay';
           // $url = 'https://ftpgspre.cnsuning.com/ftpgs/trade/aggrpay/aggrProgramPay';
            $noticeUrl = request()->root(true).'/api/Supay/notify'; 
            //var_dump($params);exit;
            $toParams = [
                'mchtNo'    => 'SJ103596',//商户代码 SJ+六位数字(平台分配固定值)
                'orderName' => $params['goods_name'],//订单名称
                'amount'    => $params['money'],//订单金额 元
                'orderId'   => $params['order_no'],//支付单号 全局唯一,不低于14位
                'noticeUrl' => $noticeUrl,//回调通知地址 https地址
                'returnUrl' => '',//没有可以不写
                'remark'    => $params['goods_name'],//备注
            ];
            
        ksort($toParams);
        $newpar = json_encode($toParams,JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);
        $timestamp = date('YmdHms',time());
             
            $str = 'appId=yfbmSJ103596e2023092201&params='.$newpar.'&timestamp='.$timestamp.'&version=1.0';
       
            $newstr = strtoupper(md5($str)); 
            // echo $newstr;exit;
            $sign = $this->signNew($newstr);
            
              
            //公共参数
            $pubParams = [
                'version'      => '1.0',//接口版本号 固定送1.0
                'appId'        => 'yfbmSJ103596e2023092201',//应用唯一标识 提供给第三方应用的唯一标识,
                'signType'     => 'RSA',//签名类型 固定送RSA,签名算法SHA1withRSA
                'signkeyIndex' => '0001',//公钥索引 商户应用接入前自行生成密钥对,将公钥提供苏宁后配置产生的索引号
                'sign'         => $sign,//签名 使用商户私钥加签后产生的签名信息
                'timestamp'    => $timestamp,//请求时间戳 yyyyMMddHHmmss
                'params'       => $newpar,//业务报文参数 业务接口请求报文参数,JSON格式。
            ];
           // $header = 'content-type=applicaton/json';
           $pubParams = json_encode($pubParams,JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE); 
            $res = $this->postcurl($url,$pubParams);
     
            $result['data'] = json_decode($res,true);
      
              return $result;
        } catch (Exception $e) {
            $result['status'] = 0;
            $result['msg'] = $e->getMessage();
        }
        return $result;
    }
       private function signNew($str) {
        $file = file_get_contents($this->private_key);
        if (!$file) {
            throw new \Exception('loadPk12Cert::file
                    _get_contents');
        }
        $pkeyid = openssl_pkey_get_private($file);  
        // if (!openssl_pkcs12_read($file, $cert, $pkeyid)) { 
        //     throw new \Exception('loadPk12Cert::openssl_pkcs12_read ERROR');
        // }
     
       // $pem = $cert['pkey'];
       openssl_sign($str, $sign, $pkeyid);  
        $sign = base64_encode($sign); 
        return $sign;
    }
    	//获取签名
	private function createSignaTure($dates) {
		ksort($dates); 
		$str = '';
		foreach($dates as $k => $v) {
			if($v != '') {
				$str .= $k.'='.$v.'&';
			}
		}
		//$str .= strtolower(md5($key));
		return $str;
	}
    	//获取参数
	private function getToStr($arr) {
		
		$info = $this -> createSignaTure($arr);
		$str = '';
		foreach($arr as $k => $v) {
			if($v != '') {
				$str .= $k.'='.urlencode($v).'&';
			}	
		}
// 		$str .= Config::TRADE_SIGNATURE_KEY.Config::TRADE_QSTRING_EQUAL.$info;
// 		file_put_contents('../baowen.log', $str."\r\n");
		return $str;
	}
    private function postcurl($url, $data)
    {

 
        $curl = curl_init();
 
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        if(!$data){
            return 'data is null';
        }
        if(is_array($data))
        {
            $data = json_encode($data);
        }
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_HTTPHEADER,array(
                'Content-Type: application/json; charset=utf-8',
                'Content-Length:' . strlen($data),
                'Cache-Control: no-cache',
                'Pragma: no-cache'
        ));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $res = curl_exec($curl);
        $errorno = curl_errno($curl);
        if ($errorno) {
            return $errorno;
        }
        curl_close($curl);
        return $res;
 
  

    }
    private function getSignContent($params) {
        ksort($params);

        $stringToBeSigned = "";
        $i = 0;
        foreach ($params as $k => $v) {
            //false === $this->checkEmpty($v) &&
            if ("@" != substr($v, 0, 1)) {

                if ($i == 0) {
                    $stringToBeSigned .= "$k" . "=" . "$v";
                } else {
                    $stringToBeSigned .= "&" . "$k" . "=" . "$v";
                }
                $i++;
            }
        }

        unset ($k, $v);
        return $stringToBeSigned;
    }

    private function checkEmpty($value)
    {
        if (!isset($value))
            return true;
        if ($value === null)
            return true;
        if (trim($value) === "")
            return true;

        return false;
    }
}