<?php

namespace xh\run\gateway\controller;

use xh\library\mysql;
use xh\library\request;
use xh\library\functions;
use xh\library\url;
use xh\library\view;
use xh\library\ip;

class pay
{

    private $mysql;

    public function __construct()
    {
        $this->mysql = new mysql();
    }

	public function curl_post($sUrl, $aHeader, $aData){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_URL, $sUrl);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $aHeader);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($aData));
    $sResult = curl_exec($ch);
    if($sError=curl_error($ch)){
        die($sError);
    }
    curl_close($ch);
    return $sResult;
	}


    //全自动版支付宝 v1.0
    public function automaticAlipay()
    {
        $type = request::filter('get.content_type', '', 'htmlspecialchars');
        $id = intval(request::filter('get.id'));
        $order = $this->mysql->query('client_alipay_automatic_orders', "id={$id}")[0];
        $data = $this->mysql->query("client_alipay_automatic_account", "id={$order['alipay_id']}", 'cookie,uid')[0];
        if (!is_array($order)) functions::json(-1, '当前交易号不存在');
        if ($order['status'] == 3) functions::json(-1, '当前订单已经过期,请重新发起支付');
        if ($order['status'] == 4) functions::json(200, '当前订单已经支付成功!');
        if (($order['creation_time'] + 600) < time()) {
            $this->mysql->update('client_alipay_automatic_orders', ['status' => 3], "id={$order['id']}");

            functions::json(-2, '当前订单已经过期,请重新发起支付');
        }
		$pay_url = '';
        //查询微信信息
        $order['alipay_name'] = $this->mysql->query("client_alipay_automatic_account", "id={$order['alipay_id']}")[0]['name'];

        //检测是否手机访问
        if (ip::isMobile()) {
            $path = 'alipay/alipayMobile';
        } else {
            $path = 'alipay/alipay';
        }
		
		if($order['order_id']==0){
			
			
		$uid = $this->mysql->query("client_alipay_automatic_account", "id={$order['alipay_id']}")[0]['uid'];
		$kuk = $this->mysql->query("client_alipay_automatic_account", "id={$order['alipay_id']}")[0]['cookie'];



		            $cookie='Cookie:'.$kuk;
            		$msgid=$uid;
            	

            
            
                            // 第一步创建红包
                $sUrl = 'http://mall.e.weibo.com/aj/redenvelope/create';
                //post数据
                
                if($order['amount']>200){

                	$age=$order['amount']/200;
                	if(!is_numeric($age)||strpos($age,".")!==false){
					
					//不是整数
					$singalAmount='100';
					$count=$order['amount']/100;

					}else{
						
					//是整数	
					$singalAmount='200';
					$count=$order['amount']/200;

				   }
                	
                	
                     $aData = array(
                    'bag_type' => '1',
                    'puicode' => '10000073',
                    'msgtype' => '1',
                    'msgid'   => $msgid,
                    'singalAmount' =>$singalAmount,
                    'blessing' => '恭喜发财,大吉大利',
                    'count'   => $count,
                    'amount'  => $order['amount'],
                    '_t'      => '0'
                ); 	
                	
                	
                }else{
                	
                     $aData = array(
                    'bag_type' => '1',
                    'puicode' => '10000073',
                    'msgtype' => '1',
                    'msgid'   => $msgid,
                    'singalAmount' => $order['amount'],
                    'blessing' => '恭喜发财,今晚吃鸡',
                    'count'   => '1',
                    'amount'  => $order['amount'],
                    '_t'      => '0'
                );
                	
                	
                }
                

                $aHeader = array('Content-type:application/x-www-form-urlencoded','User-Agent:Mozilla/5.0 (Linux; Android 5.1.1; DUK-AL20 Build/LMY48Z) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/39.0.0.0 Safari/537.36 Weibo (HUAWEI-DUK-AL20__weibo__9.7.2.1__android__android5.1.1))','X-Requested-With:XMLHttpRequest',$cookie);
                $sResult = $this->curl_post($sUrl, $aHeader, $aData);
                $aResData = json_decode($sResult, true);
                $payurl=$aResData['data']['url'];
                $code=$aResData['code'];
                

                //开始第二步测试
                if($code==100000){
                
                $header="User-Agent:Mozilla/5.0 (Linux; Android 5.0; SM-G900P Build/LRX21T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Mobile Safari/537.36\r\nCookie:".$kuk."\r\n";
                
                //请求地址
                $url = $payurl;
                //headers请求头
                $context_options = array(
                 'http' =>
                  array(
                   'method' => "GET",
                   'header' => $header,
                  ));
                $context = stream_context_create($context_options);
                //获取资源
                $html = file_get_contents($url,FALSE,$context);
				
				$printhtml="/www/wwwroot/wb.totspay.com/weibo/html/".$order['id'];
				$fp = fopen ($printhtml . '.html',"w");
				 
				if (fwrite ($fp,$html)){
				
					
				fclose ($fp);
				
				
				
				} else { 
				fclose ($fp); 
				
				
				} 
				
				$pay_html="http://wb.totspay.com/weibo/html/".$order['id'].".html";
				
                $matches = array();
                
                preg_match_all('<input name="biz_content" type="hidden" value="(.*)"/>', $html, $matches);
                
                $json=$matches['1']['0'];
                $json=htmlspecialchars_decode($json);
                $arr = json_decode($json, true);    // 将获取到的 JSON 数据解析成数组
                
                $tradeId=$arr['out_trade_no'];
                
                $this->mysql->update('client_alipay_automatic_orders', ['order_id' => $tradeId,'pay_html' => $pay_html], "id={$order['id']}");
                }else{
                    
                
                    functions::json(-1, '订单发起失败,请检查uid和cookie');
                }

}
		$pay_data = [
            'id'            => $order['id'],
            'alipay_name'   => $order['alipay_name'],
            'creation_time' => $order['creation_time'],
            'status'        => $order['status'],
            'amount'        => $order['amount'],
            'success_url'   => $order['success_url'],
            'error_url'     => $order['error_url'],
            'out_trade_no'  => $order['out_trade_no'],
            'trade_no'      => $order['trade_no'],
            'qrcode'        => $order['qrcode'],
            'h5url'         => $order['pay_html'],
        ];








     


        new view($path, $pay_data);
    }

    //订单查询
    public function automaticAlipayQuery()
    {
        $id = intval(request::filter('get.id'));

        $order = $this->mysql->query('client_alipay_automatic_orders', "id={$id}", 'status,creation_time,qrcode,order_id,cookie,key_id,amount,syrmb,pay_html')[0];
        


         


     
         
        if (!is_array($order)) functions::json(-1, '当前交易号不存在');
        if ($order['status'] == 1) functions::json(1, '正在与网关连接中..');
        if ($order['status'] == 2) {
        
        
        
            /*   $header="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36\r\nCookie:".$order['cookie']."\r\n";
                
                //请求地址
                $url = "https://pay.sc.weibo.com/aj/pc/biz/list?biz_type=0&status=0&biz_id=".$order['order_id'];
                
                //headers请求头
                $context_options = array(
                 'http' =>
                  array(
                   'method' => "GET",
                   'header' => $header,
                  ));
                $context = stream_context_create($context_options);
                //获取资源
                $paylist = file_get_contents($url,FALSE,$context);
				 $arr = json_decode($paylist, true);
				 $res=$arr['data']['biz'];
				 $amount=$res[0]['amount'];
				 $status=$res[0]['status'];
				 $out_pay_id=$res[0]['order_id'];
                 $this->mysql->update('client_alipay_automatic_orders', ['aliddh' => $out_pay_id], "id={$id}");
        		if($status==2){
        			
        			
        			//支付成功开始回调orderid
					$data = array(
						'key'=>'12345678',
						'uid'=>$order['order_id'],
						'orderid'=>$out_pay_id,
					    'id'=>$id,
					    'keyid'=>$order['key_id'],
					    'rmb'=>$order['amount'],
					    ); 
					
					$query = http_build_query($data); 
					
					$options['http'] = array(
					     'timeout'=>60,
					     'method' => 'POST',
					     'header' => 'Content-type:application/x-www-form-urlencoded',
					     'content' => $query
					    );
					
					$url = "http://weibo.b7c.net/server/alipayAutomatic/uploadOrder.do";
					$context = stream_context_create($options);
					$reault = file_get_contents($url, false, $context);
					file_put_contents("log/htlog.txt", date('Y-m-d H:i:s')."|回调信息:|".$reault.'|'."\n", FILE_APPEND);
        			


        		
        		
        			
        		}
        
        */
        
        
        
        
        
        
        
        
        
        
        
        

		 if (($order['creation_time'] + 600) < time()) {
                $this->mysql->update('client_alipay_automatic_orders', ['status' => 3], "id={$order['id']}");

                functions::json(-2, '当前订单已经过期,请重新发起支付');
            }

            functions::json(100, '请扫码支付', ['qrcode' => $order['qrcode'],'payurl' => $order['pay_html']]);
        
        	
        	
        	
        }
        if ($order['status'] == 3) functions::json(-2, '当前订单已经过期,请重新发起支付');
        if ($order['status'] == 4) functions::json(200, '当前订单已经支付成功!');
    
    	
    	
    	
    }


  
  //服务版
    public function service()
    {
        $type = request::filter('request.content_type', 'text', 'htmlspecialchars');
        $id = intval(request::filter('get.id'));
        $order = $this->mysql->query('service_order', "id={$id}")[0];
        $data = $this->mysql->query("service_account", "id={$order['service_id']}", 'account_user_id,gathering_name')[0];
        if (!is_array($order)) functions::json(-1, '当前交易号不存在');
        if ($order['status'] == 3) functions::json(-1, '当前订单已经过期,请重新发起支付');
        if ($order['status'] == 4) functions::json(200, '当前订单已经支付成功!');
        if (($order['creation_time'] + 600) < time()) {
            $this->mysql->update('service_order', ['status' => 3], "id={$order['id']}");

            functions::json(-2, '当前订单已经过期,请重新发起支付');
        }

        //查询服务信息
        $service = $this->mysql->query("service_account", "id={$order['service_id']}")[0];
        //检测是否手机访问
        if (ip::isMobile()) {
            if ($service['types'] == 2) $path = 'service/alipayMobile';
        } else {
            if ($service['types'] == 2) $path = 'service/alipay';
        }
      
      	$ewm = $this->mysql->query("service_order","id={$order['id']}")[0]['qrcode'];
        $pay_data = [
            'id'            => $order['id'],
            'creation_time' => $order['creation_time'],
          	'name' 			=> $order['name'],
			'card' 			=> $order['card'],
			'kahao'			=> $order['kahao'],
			'banktype' 		=> $order['banktype'],
            'status'        => $order['status'],
            'amount'        => $order['amount'],
            'success_url'   => $order['success_url'],
            'error_url'     => $order['error_url'],
            'out_trade_no'  => $order['out_trade_no'],
            'trade_no'      => $order['trade_no'],
            'qrcode'        => $ewm,
        ];



            new view($path, $pay_data);
        
    }

    //订单查询
    public function serviceQuery()
    {
        $id = intval(request::filter('get.id'));
		$order = $this->mysql->query('service_order', "id={$id}", 'status,creation_time,qrcode')[0];
        if ($order['status'] == 1) functions::json(1, '正在与网关连接中..');
        if ($order['status'] == 2) {
            if (($order['creation_time'] + 299) < time()) {
                $this->mysql->update('service_order', ['status' => 3], "id={$order['id']}");

                functions::json(-2, '当前订单已经过期,请重新发起支付');
            }


            functions::json(100, '请扫码支付', ['qrcode' => $order['qrcode']]);

        }
        if ($order['status'] == 3) functions::json(-2, '当前订单已经过期,请重新发起支付');
        if ($order['status'] == 4) functions::json(200, '当前订单已经支付成功!');
    }

    function file_exists_S3($url)
    {
        $state = @file_get_contents($url, 0, null, 0, 1);//获取网络资源的字符内容
        if ($state) {
            $filename = date("dMYHis") . '.jpg';//文件名称生成
            ob_start();//打开输出
            readfile($url);//输出图片文件
            $img = ob_get_contents();//得到浏览器输出
            ob_end_clean();//清除输出并关闭
            $size = strlen($img);//得到图片大小
            $fp2 = @fopen($filename, "a");
            fwrite($fp2, $img);//向当前目录写入图片文件，并重新命名
            fclose($fp2);

            return $this->base64EncodeImage($filename);
        } else {
            return 0;
        }
    }

    /*图片转换为 base64格式编码*/
    function base64EncodeImage($image_file)
    {

        $base64_image = '';
        $image_info = getimagesize($image_file);
        $image_data = fread(fopen($image_file, 'r'), filesize($image_file));
        $base64_image = 'data:' . $image_info['mime'] . ';base64,' . chunk_split(base64_encode($image_data));

        return $base64_image;
    }


    function pay_curl($url, $data = '')
    {
        $ch = curl_init($url);
        $header[] = 'Mozilla/5.0 (Linux; U; Android 7.1.2; zh-cn; GiONEE F100 Build/N2G47E) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30';
        if (!empty($data)) {
            curl_setopt($ch, 47, 1);
            curl_setopt($ch, 10015, $data);
        }
        curl_setopt($ch, 10023, $header);
        curl_setopt($ch, 64, FALSE); // 对认证证书来源的检查
        curl_setopt($ch, 81, FALSE); // 从证书中检查SSL加密算法是否存在
        curl_setopt($ch, 19913, true);
        curl_setopt($ch, 19914, true);
        curl_setopt($ch, 52, 1);
        curl_setopt($ch, 13, 60);
        ob_start();
        @$data = curl_exec($ch);
        ob_end_clean();
        curl_close($ch);

        return $data;
    }


  	//商户收款模式
    public function skpay()
    {
        $order_id = intval(request::filter('request.id'));
        if (empty($order_id)) functions::str_json('json', -1, 'order_id不能为空');

        $order = $this->mysql->query("client_alipay_automatic_orders", "id={$order_id}", 'id,alipay_id,amount,trade_no')[0];
        $key_id = $this->mysql->query("client_alipay_automatic_account","id={$order['alipay_id']}")[0]['key_id'];
       	$uid = $this->mysql->query("client_alipay_automatic_account","id={$order['alipay_id']}")[0]['user_id'];
      	$appid = $this->mysql->query("client_alipay_automatic_account","id={$order['alipay_id']}")[0]['appid'];
      	$siyue=$this->mysql->query("client_alipay_automatic_account","id={$order['alipay_id']}")[0]['siyue'];
		$method= url::s('gateway/pay/automaticAlipayQuery', "id={$order_id}");
       	$url= url::s('gateway/pay/automaticAlipay', "id={$order_id}");
        $mark = $order['id'] .'|'.$key_id.'|'.$appid;
        $order['mark'] = $mark;
        if (empty($appid)) functions::str_json('json', -1, '支付宝PID不能为空');

        $pay_data = [
          	'did'	  => $order_id,
            'url'	  => $url,
            'key_id'  => $key_id,
            'uid'     => $uid,          
            'appid' => $appid,
            'siyue'    => $siyue,
            'amount'  => $order['amount'],
            'out_trade_no'  => $mark,
          	'method'  =>  $method,
         	'zh'      =>  $key_id,
        ];

        $path = 'alipay/sk';
        new view($path, $pay_data);

    }


  	//服务版收款模式
    public function paysk()
    {
        //error_reporting(E_ALL);
        $order_id = intval(request::filter('request.id'));

        $order = $this->mysql->query("service_order", "id={$order_id}", 'id,service_id,amount')[0];

        $data = $this->mysql->query("service_account", "id={$order['service_id']}", 'account_user_id')[0];
        $order['alipay_id'] = $order['service_id'];
        $key_id = $this->mysql->query("service_account","id={$order['service_id']}")[0]['key_id'];
       	$uid = $this->mysql->query("service_account","id={$order['service_id']}")[0]['user_id'];      
		$method = url::s('gateway/pay/serviceQuery', "id={$order_id}");
        $url = url::s('gateway/pay/service', "id={$order_id}");
        $mark = $order['service_id'] . '|' . $order['id'];
		 $order['user_id'] = $data['account_user_id'];
         $order['mark'] = $mark;
		 if (empty($data['account_user_id'])) functions::str_json('json', -1, 'account_user_id不能为空');

        $pay_data = [
            'url'     => $url,
          	'order_id'     => $order_id,
            'user_id' => $data['account_user_id'],
          	'key_id ' => $key_id,
          	'uid '    => $uid,
            'mark'    => $mark,
            'amount'  => $order['amount'],
          	'method'  =>  $method,
            'zh'      =>  $key_id,
        ];

        $path = 'service/sk';
        new view ($path, $pay_data);
    }
  

  
}