<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Pay extends CI_Controller {

    function __construct(){
		parent::__construct();
        	$this->load->helper('url');
        	$this->load->helper('form');
                $this->load->library('session'); //加载session
		$this->load->model('CsdjDB');
		$this->load->model('CsdjAlipay');
		$this->load->model('CsdjSkins');
		$this->load->model('CsdjUser');
		$this->CsdjUser->User_Login();
    }

    public function index(){
                $data='';

                $this->load->get_user_templates();
		$template=$this->load->view('pay-index.html',$data,true);
		$template=$this->CsdjSkins->TopandBottom($template,'user');

		$Mark_Text=str_replace("{cscms:title}","充值 - 会员管理中心",$template);
		$Mark_Text=str_replace("{cscms:keywords}",stripslashes(html_entity_decode(Web_Keywords)),$Mark_Text);
		$Mark_Text=str_replace("{cscms:description}",stripslashes(html_entity_decode(Web_Description)),$Mark_Text);
		$Mark_Text=str_replace("[user:paysave]",site_url('user/pay/topay'),$Mark_Text);
        $token=md5(uniqid(rand(), true));
		$this->session->set_userdata('token',$token);
		$Mark_Text=str_replace("[user:token]",$token,$Mark_Text);

		$Mark_Text=$this->CsdjSkins->Common_Mark($Mark_Text,$this->session->userdata('cs_name'));
	        $row=$this->CsdjDB->get_select ('user','CS_ID','*',''.$this->session->userdata('cs_id').'');
		$Mark_Text=$this->CsdjUser->getuser($Mark_Text,$row);
                $this->CsdjSkins->skins($Mark_Text,$data);
    }

    public function vip(){
                $data='';
                $this->load->get_user_templates();
		$template=$this->load->view('vip-index.html',$data,true);
		$template=$this->CsdjSkins->TopandBottom($template,'user');

		$Mark_Text=str_replace("{cscms:title}","升级 - 会员管理中心",$template);
		$Mark_Text=str_replace("{cscms:keywords}",stripslashes(html_entity_decode(Web_Keywords)),$Mark_Text);
		$Mark_Text=str_replace("{cscms:description}",stripslashes(html_entity_decode(Web_Description)),$Mark_Text);
		$Mark_Text=str_replace("[user:paysave]",site_url('user/pay/tovip'),$Mark_Text);

		$Mark_Text=$this->CsdjSkins->Common_Mark($Mark_Text,$this->session->userdata('cs_name'));
	        $row=$this->CsdjDB->get_select ('user','CS_ID','*',''.$this->session->userdata('cs_id').'');
		$Mark_Text=$this->CsdjUser->getuser($Mark_Text,$row);
                $this->CsdjSkins->skins($Mark_Text,$data);
    }

    public function lists(){
                $data='';
                $op = $this->input->get('op', TRUE);   //op，默认为空为全部，ok为已完成，no为未完成
                $page = intval($this->input->get('page', TRUE));   //page
                if($page==0) $page=1;

                $this->load->get_user_templates();
		$template=$this->load->view('pay-list.html',$data,true);
		$template=$this->CsdjSkins->TopandBottom($template,'user');

		$Mark_Text=str_replace("{cscms:title}","充值记录 - 会员管理中心",$template);
		$Mark_Text=str_replace("{cscms:keywords}",stripslashes(html_entity_decode(Web_Keywords)),$Mark_Text);
		$Mark_Text=str_replace("{cscms:description}",stripslashes(html_entity_decode(Web_Description)),$Mark_Text);
		$Mark_Text=str_replace("[pay:op]",$op,$Mark_Text);


		//预先除了分页
		$pagenum=$this->CsdjSkins->GetPageNum($Mark_Text);
		preg_match_all('/{cscms:pay(.*?pagesize=([\S]+).*?)}([\s\S]+?){\/cscms:pay}/',$Mark_Text,$page_arr);//判断是否有分页标识
		if(!empty($page_arr) && !empty($page_arr[2])){

                        $sqlstr="select * from ".CS_SqlPrefix."pay where CS_User='".$this->session->userdata('cs_name')."'";
                        if($op=='ok'){
                            $sqlstr.=" and cs_pid=1";
                        }elseif($op=='no'){
                             $sqlstr.=" and cs_pid=0";
                        }

                        $sqlstr.=" order by CS_AddTime desc";
                        $data_content='';
			$Arr=$this->CsdjSkins->SpanUsersPage($sqlstr,$page_arr[2][0],$pagenum,'user/pay?op='.$op,$page);//sql,每页显示条数
			$result=$this->CsdjDB->db->query($Arr[2]);
			$recount=$result->num_rows();
			if($recount==0){
				$data_content="<div align=center><strong><font style=font-size:12px;>暂无数据！</font></strong></div>";
			}else{
				if($result){
					$sorti=1;
					foreach ($result->result() as $row2) {
						$datatmp=$this->CsdjSkins->DataPay($page_arr[0][0],$page_arr[3][0],$row2,$sorti);
						$sorti=$sorti+1;
						$data_content.=$datatmp;
					}
				}
			}// end if recount
			$Mark_Text=$this->CsdjSkins->Page_Mark($Mark_Text,$Arr);	
			$Mark_Text=str_replace($page_arr[0][0],$data_content,$Mark_Text);
			unset($Arr);
                }
		unset($page_arr);
		$Mark_Text=$this->CsdjSkins->Common_Mark($Mark_Text,$this->session->userdata('cs_name'));
	        $row=$this->CsdjDB->get_select ('user','CS_ID','*',''.$this->session->userdata('cs_id').'');
		$Mark_Text=$this->CsdjUser->getuser($Mark_Text,$row);
                $this->CsdjSkins->skins($Mark_Text,$data);
    }

    //升级VIP
    public function tovip(){
        $vip=$this->input->post('cs_vip', TRUE);
        if(empty($vip) || $vip==0) $this->CsdjSkins->Msg_url('请选择要升级的会员组!','javascript:history.back();'); 

        //分割组ID和天数
        $Arr=explode('-',$vip);
        $cs_vip=intval(@$Arr[0]);
        $cs_ts=intval(@$Arr[1]);
        if($cs_vip==0 || $cs_ts==0) $this->CsdjSkins->Msg_url('参数错误!','javascript:history.back();'); 

        //获取当前组需要金币
        $row=$this->CsdjDB->get_select('userzu','CS_ID','*',''.$cs_vip.'');
        if(!$row) $this->CsdjSkins->Msg_url('该会员组不存在!','javascript:history.back();'); 
       
        if($cs_ts==30){
              $cion=$row[0]->CS_Cion_30;
        } elseif($cs_ts==180){
              $cion=$row[0]->CS_Cion_180;
        } elseif($cs_ts==365){
              $cion=$row[0]->CS_Cion_365;
        }else{
              $this->CsdjSkins->Msg_url('时间参数错误!','javascript:history.back();'); 
        }


        $rowu=$this->CsdjDB->get_select('user','CS_ID','CS_Cion,CS_Vip,CS_VipTime,CS_EndTime',''.$this->session->userdata('cs_id').'');
        //判断金币是否够用
        if($rowu[0]->CS_Cion < $cion){
              $this->CsdjSkins->Msg_url('抱歉，您当前的金币不够升级'.$cs_ts.'天'.$row[0]->CS_Name.',请先充值!',site_url('user/pay'));
        }

        //判断当前级别
        if($rowu[0]->CS_Vip!=$cs_vip){

                     $newscion=$rowu[0]->CS_Cion - $cion;
		     $mydate=mktime(date("H"),date("i"),date("s"),date("m"),date("d")+$cs_ts,date("Y"));
		     $NewUseDate= date("Y-m-d H:i:s",$mydate);

                     $this->db->query("update ".CS_SqlPrefix."user set CS_Vip=".$cs_vip.",CS_Cion=".$newscion.",CS_VipTime='".date('Y-m-d H:i:s')."',CS_EndTime='".$NewUseDate."' where cs_id='".$this->session->userdata('cs_id')."'");

                     //发送消息
                       $msg['CS_Name']='升级'.$row[0]->CS_Name.'成功';
                       $msg['CS_Neir']=$this->session->userdata('cs_name').'，您好，恭喜您，升级《'.$row[0]->CS_Name.'》成功，同时系统给您扣除'.$cion.'个金币，到期时间：'.$NewUseDate.'，如有问题，请联系管理员。';
                       $msg['CS_Usera']=$this->session->userdata('cs_name');
                       $msg['CS_Userb']='管理员';
                       $msg['CS_AddTime']=date('Y-m-d h:i:s');
                       $this->CsdjDB->get_insert('xiaoxi',$msg);

                     $this->CsdjSkins->Msg_url('恭喜您，升级'.$cs_ts.'天'.$row[0]->CS_Name.'成功,到期时间：'.$NewUseDate,site_url('user/pay/vip'));

        }else{
                     $newscion=$rowu[0]->CS_Cion - $cion;

                     if($rowu[0]->CS_Vip>0){
		            $strtimes = explode(" ",$rowu[0]->CS_EndTime);
		            $timearray = explode("-",$strtimes[0]);
		            $timearray2 = explode(":",$strtimes[1]);
		            $mydate2=mktime($timearray2[0],$timearray2[1],$timearray2[2],$timearray[1],$timearray[2]+$cs_ts,$timearray[0]);
		            $NewUseDate=date("Y-m-d H:i:s",$mydate2);
                            $viptime=$rowu[0]->CS_VipTime;
                     }else{
		            $mydate=mktime(date("H"),date("i"),date("s"),date("m"),date("d")+$cs_ts,date("Y"));
		            $NewUseDate= date("Y-m-d H:i:s",$mydate);
                            $viptime=date('Y-m-d H:i:s');
                     }

                     $this->db->query("update ".CS_SqlPrefix."user set CS_Vip=".$cs_vip.",CS_Cion=".$newscion.",CS_VipTime='".$viptime."',CS_EndTime='".$NewUseDate."' where cs_id='".$this->session->userdata('cs_id')."'");
                     //发送消息
                            $msg['CS_Name']='升级'.$row[0]->CS_Name.'成功';
                            $msg['CS_Neir']=$this->session->userdata('cs_name').'，您好，恭喜您，升级《'.$row[0]->CS_Name.'》成功，同时系统给您扣除'.$cion.'个金币，到期时间：'.$NewUseDate.'，如有问题，请联系管理员。';
                            $msg['CS_Usera']=$this->session->userdata('cs_name');
                            $msg['CS_Userb']='管理员';
                            $msg['CS_AddTime']=date('Y-m-d h:i:s');
                            $this->CsdjDB->get_insert('xiaoxi',$msg);

                     $this->CsdjSkins->Msg_url('恭喜您，升级'.$cs_ts.'天'.$row[0]->CS_Name.'成功,到期时间：'.$NewUseDate,site_url('user/pay/vip'));
        }
    }

    //记录充值定单
    public function topay(){
        $pay['cs_rmb']=intval($this->input->post('cs_rmb', TRUE));
        $pay['cs_type']=$this->input->post('cs_type', TRUE);
        if($pay['cs_rmb']==0) $this->CsdjSkins->Msg_url('充值金额不能为空!','javascript:history.back();'); 
        if($pay['cs_rmb']<1) $this->CsdjSkins->Msg_url('充值金额错误!','javascript:history.back();'); 
        if(empty($pay['cs_type'])) $this->CsdjSkins->Msg_url('请选择充值方式!','javascript:history.back();'); 

				//token check
                $token=$this->input->post('token', TRUE);
				if(!$this->session->userdata('token') || $token!=$this->session->userdata('token'))  $this->CsdjSkins->Msg_url('非法提交数据!','javascript:history.back();');

           //生成定单
           $this->load->helper('string');
           $pay['cs_dingdan']=date('Ymd').time().random_string('numeric',5);
           $pay['cs_ip']=$this->CsdjSkins->GetIP();
           $pay['cs_user']=$this->session->userdata('cs_name');
           $pay['cs_addtime']=date('Y-m-d H:i:s');
           $res=$this->CsdjDB->get_insert('pay',$pay);
           if($res>0){
                 $this->session->unset_userdata('token');
                 if($pay['cs_type']=='alipay'){ //支付宝
                       $tourl=site_url('user/pay/alipay_'.CS_Alipay_JK).'?id='.$res;
                 }elseif($pay['cs_type']=='tenpay'){  //财富通
                       $tourl=site_url('user/pay/tenpay').'?id='.$res;
                 }else{  //网银在线
                       $tourl=site_url('user/pay/wypay').'?id='.$res;
                 }
                 exit("<script>window.location='".$tourl."';</script>");
           }else{
                 $this->CsdjSkins->Msg_url('抱歉，定单记录失败!','javascript:history.back();'); 
           }
    }

    //网银在线支付入口
    public function wypay(){

        $id=intval($this->input->get('id', TRUE));
        if($id==0) $this->CsdjSkins->Msg_url('参数错误!','javascript:history.back();');  

        //获取数据库定单记录
        $row=$this->CsdjDB->get_select('pay','CS_ID','*',''.$id.'');
        if(!$row) $this->CsdjSkins->Msg_url('该定单不存在!','javascript:history.back();'); 

           $v_amount    = $row[0]->CS_RMB;
           $v_moneytype = 'CNY';
           $v_oid       = $row[0]->CS_Dingdan;
           $v_mid       = CS_Wypay_ID;
           $v_url       = site_url('user/pay/wypay_return_url');
           $key         = CS_Wypay_Key;
           $text        = $v_amount.$v_moneytype.$v_oid.$v_mid.$v_url.$key;
           $md5info     = strtoupper(md5($text));

           echo '
	      <form method="post" id="form1" name="form1" action="https://Pay3.chinabank.com.cn/PayGate">
	      <input type="hidden" name="v_mid" value="'.$v_mid.'">
	      <input type="hidden" name="v_oid" value="'.$v_oid.'">
	      <input type="hidden" name="v_amount" value="'.$v_amount.'">
	      <input type="hidden" name="v_moneytype" value="'.$v_moneytype.'">
	      <input type="hidden" name="v_url" value="'.$v_url.'">
	      <input type="hidden" name="v_md5info" value="'.$md5info.'">
	      </form><script language="javascript">document.form1.submit();</script>';
    }

    //网银在线返回接口
    public function wypay_return_url(){

	$v_oid=$this->input->get_post('v_oid', TRUE);     
	$v_pmode=$this->input->get_post('v_oid', TRUE);  
	$v_pstatus=$this->input->get_post('v_pstatus', TRUE);    
	$v_pstring=$this->input->get_post('v_pstring', TRUE);   
	$v_amount=$this->input->get_post('v_amount', TRUE);  
	$v_moneytype=$this->input->get_post('v_moneytype', TRUE);   
	$v_md5str=$this->input->get_post('v_md5str', TRUE);  
	//重新计算md5的值
	$md5string=strtoupper(md5($v_oid.$v_pstatus.$v_amount.$v_moneytype.CS_Wypay_Key)); //拼凑加密串

	if ($v_md5str==$md5string){


            $row=$this->db->query("select * from ".CS_SqlPrefix."pay where CS_Dingdan='".addslashes($v_oid)."'")->row();
            if(!$row){
                    $this->CsdjSkins->Msg_url('验证失败,该定单不存在!',site_url('user')); 
            }

                    if($row->CS_PID==0){ //定单存在则加金币
                           //人民币转金币
                           $CION=$row->CS_RMB*Cion_RmbToCion;
                           $this->db->query("update ".CS_SqlPrefix."user set CS_Cion=CS_Cion+".$CION." where cs_name='".$row->CS_User."'");
                           //改变状态
                           $this->db->query("update ".CS_SqlPrefix."pay set CS_PID=1 where cs_id='".$row->CS_ID."'");
                           //发送消息
                              $msg['CS_Name']='金币充值成功消息';
                              $msg['CS_Neir']=$row->CS_User.'，您好，您已成功充值《'.$CION.'》个金币，定单号：'.$v_oid.'，如有问题，请联系管理员。';
                              $msg['CS_Usera']=$row->CS_User;
                              $msg['CS_Userb']='管理员';
                              $msg['CS_AddTime']=date('Y-m-d h:i:s');
                              $this->CsdjDB->get_insert('xiaoxi',$msg);
                          $this->CsdjSkins->Msg_url('抱歉，非法定单!',site_url('user')); 
                    }else{
                          $this->CsdjSkins->Msg_url('恭喜您，成功充值了 '.$CION.' 个金币，若出现问题请尽快联系客服,请牢记您的定单号：'.$v_oid.'!',site_url('user')); 
                    }

        }else{
            $this->CsdjSkins->Msg_url('非法交易，验证失败!',site_url('user')); 
        }
    }

    //财付通支付入口
    public function tenpay(){

        require_once (CSCMSPATH."tenpay/RequestHandler.class.php");

        $partner = CS_Tenpay_ID;
        $key = CS_Tenpay_Key;

        $return_url = site_url('user/pay/tenpay_return_url');
        $notify_url = site_url('user/pay/tenpay_notify_url');

        $id=intval($this->input->get('id', TRUE));
        if($id==0) $this->CsdjSkins->Msg_url('参数错误!','javascript:history.back();'); 

        //获取数据库定单记录
        $row=$this->CsdjDB->get_select('pay','CS_ID','*',''.$id.'');
        if(!$row) $this->CsdjSkins->Msg_url('该定单不存在!','javascript:history.back();'); 

        /* 创建支付请求对象 */
        $reqHandler = new RequestHandler();
        $reqHandler->init();
        $reqHandler->setKey($key);
        $reqHandler->setGateUrl("https://gw.tenpay.com/gateway/pay.htm");

        $reqHandler->setParameter("partner", $partner);
        $reqHandler->setParameter("out_trade_no", $row[0]->CS_Dingdan);
        $reqHandler->setParameter("total_fee", $row[0]->CS_RMB."00");  //总金额
        $reqHandler->setParameter("return_url",  $return_url);
        $reqHandler->setParameter("notify_url", $notify_url);
        $reqHandler->setParameter("body", $row[0]->CS_User."充值金币");
        $reqHandler->setParameter("bank_type", "DEFAULT");  	  //银行类型，默认为财付通
        //用户ip
        $reqHandler->setParameter("spbill_create_ip", @$_SERVER['REMOTE_ADDR']);//客户端IP
        $reqHandler->setParameter("fee_type", "1");               //币种
        $reqHandler->setParameter("subject",$row[0]->CS_User."充值金币");          //商品名称，（中介交易时必填）

        //系统可选参数
        $reqHandler->setParameter("sign_type", "MD5");  	 	  //签名方式，默认为MD5，可选RSA
        $reqHandler->setParameter("service_version", "1.0"); 	  //接口版本号
        $reqHandler->setParameter("input_charset", "GBK");   	  //字符集
        $reqHandler->setParameter("sign_key_index", "1");    	  //密钥序号

        //业务可选参数
        $reqHandler->setParameter("attach", "");             	  //附件数据，原样返回就可以了
        $reqHandler->setParameter("product_fee", "");        	  //商品费用
        $reqHandler->setParameter("transport_fee", "0");      	  //物流费用
        $reqHandler->setParameter("time_start", date("YmdHis"));  //订单生成时间
        $reqHandler->setParameter("time_expire", "");             //订单失效时间
        $reqHandler->setParameter("buyer_id", "");                //买方财付通帐号
        $reqHandler->setParameter("goods_tag", "");               //商品标记
        $reqHandler->setParameter("trade_mode","1");              //交易模式（1.即时到帐模式，2.中介担保模式，3.后台选择（卖家进入支付中心列表选择））
        $reqHandler->setParameter("transport_desc","");              //物流说明
        $reqHandler->setParameter("trans_type","1");              //交易类型
        $reqHandler->setParameter("agentid","");                  //平台ID
        $reqHandler->setParameter("agent_type","");               //代理模式（0.无代理，1.表示卡易售模式，2.表示网店模式）
        $reqHandler->setParameter("seller_id","");                //卖家的商户号

        //请求的URL
        $reqUrl = $reqHandler->getRequestURL();

        //获取debug信息,建议把请求和debug信息写入日志，方便定位问题
        /**/
        $debugInfo = $reqHandler->getDebugInfo();

        echo '<form action="'.$reqHandler->getGateUrl().'" name="form1" method="post">';

        $params = $reqHandler->getAllParameters();
        foreach($params as $k => $v) {
	        echo "<input type=\"hidden\" name=\"{$k}\" value=\"{$v}\" />\n";
        }

        echo '<script language="javascript">document.form1.submit();</script></form>';

    }

    //财富通同步返回
    public function tenpay_return_url() { 
	
	    $partner = CS_Tenpay_ID;
        $key = CS_Tenpay_Key;
        require_once (CSCMSPATH."tenpay/ResponseHandler.class.php");
        $resHandler = new ResponseHandler();
        $resHandler->setKey($key);


	    //通知id
	    $notify_id = $this->input->get_post('notify_id', TRUE); 
	    //商户订单号
	    $out_trade_no = $this->input->get_post('out_trade_no', TRUE); 
	    //财付通订单号
	    $transaction_id = $this->input->get_post('transaction_id', TRUE); 
	    //如果有使用折扣券，discount有值，total_fee+discount=原请求的total_fee
	    $discount = $this->input->get_post('discount', TRUE); 
	    //支付结果
	    $trade_statess = $_GET['trade_state']; 
	    //交易模式,1即时到账
	    $trade_mode = $this->input->get_post('trade_mode', TRUE); 


        //判断签名
        if($resHandler->isTenpaySign()) {

	        if("1" == $trade_mode ) {
		        if( "0" == $trade_statess){ 
                                $row=$this->db->query("select CS_ID,CS_User,CS_RMB from ".CS_SqlPrefix."pay where CS_Dingdan='".addslashes($out_trade_no)."'")->row();
                                if(!$row){
                                        $this->CsdjSkins->Msg_url('验证失败,该定单不存在!',site_url('user')); 
                                }else{
                          		         //人民币转金币
                           		        $CION=$row->CS_RMB*Cion_RmbToCion;
                           		        $this->db->query("update ".CS_SqlPrefix."user set CS_Cion=CS_Cion+".$CION." where cs_name='".$row->CS_User."'");
                           		        //改变状态
                           		        $this->db->query("update ".CS_SqlPrefix."pay set CS_PID=1 where cs_id='".$row->CS_ID."'");
                           		        //发送消息
                             		        $msg['CS_Name']='金币充值成功消息';
                              		        $msg['CS_Neir']=$row->CS_User.'，您好，您已成功充值《'.$CION.'》个金币，定单号：'.$out_trade_no.'，如有问题，请联系管理员。';
                              		        $msg['CS_Usera']=$row->CS_User;
                              		        $msg['CS_Userb']='管理员';
                              		        $msg['CS_AddTime']=date('Y-m-d h:i:s');
                              		        $this->CsdjDB->get_insert('xiaoxi',$msg);
								}
                                $this->CsdjSkins->Msg_url('恭喜您，成功充值了 '.$row->CS_RMB.' 元，若出现问题请尽快联系客服,请牢记您的定单号：'.$out_trade_no.'!',site_url('user')); 
		        } else {
			        //当做不成功处理
			        echo "<br/>" . "即时到帐支付失败" . "<br/>";
		        }
	        }elseif( "2" == $trade_mode  ) {
		        if( "0" == $trade_statess) {
			        echo "<br/>" . "中介担保支付成功" . "<br/>";
		        } else {
			        echo "<br/>" . "中介担保支付失败" . "<br/>";
		        }
	        }
        } else {
	        echo "<br/>" . "认证签名失败" . "<br/>";
	        //echo $resHandler->getDebugInfo() . "<br>";
        }

    }


    //财富通异步返回
    public function tenpay_notify_url() { 

	    $partner = CS_Tenpay_ID;
        $key = CS_Tenpay_Key;
	
        require (CSCMSPATH."tenpay/ResponseHandler.class.php");
        require (CSCMSPATH."tenpay/RequestHandler.class.php");
        require (CSCMSPATH."tenpay/client/ClientResponseHandler.class.php");
        require (CSCMSPATH."tenpay/client/TenpayHttpClient.class.php");

	$resHandler = new ResponseHandler();
	$resHandler->setKey($key);
	if($resHandler->isTenpaySign()) {
		$notify_id = $resHandler->getParameter("notify_id");
		$queryReq = new RequestHandler();
		$queryReq->init();
		$queryReq->setKey($key);
		$queryReq->setGateUrl("https://gw.tenpay.com/gateway/simpleverifynotifyid.xml");
	        $queryReq->setParameter("partner", $partner);
		$queryReq->setParameter("notify_id", $notify_id);
		$httpClient = new TenpayHttpClient();
		$httpClient->setTimeOut(5);
		$httpClient->setReqContent($queryReq->getRequestURL());
	

		if($httpClient->call()) {
			$queryRes = new ClientResponseHandler();
			$queryRes->setContent($httpClient->getResContent());
			$queryRes->setKey($key);

		        if($resHandler->getParameter("trade_mode") == "1"){ //判断签名及结果（即时到帐）,只有签名正确,retcode为0，trade_state为0才是支付成功

		                if($queryRes->isTenpaySign() && $queryRes->getParameter("retcode") == "0" && $resHandler->getParameter("trade_state") == "0") {

				        $out_trade_no = $this->input->get_post('out_trade_no', TRUE);
				        $transaction_id = $resHandler->getParameter("transaction_id");
				        $total_fee = $resHandler->getParameter("total_fee");
				        $discount = $resHandler->getParameter("discount");
				
                    		        //获取数据库定单记录
                    		        $row=$this->db->query("select CS_ID,CS_User,CS_RMB from ".CS_SqlPrefix."pay where CS_Dingdan='".addslashes($out_trade_no)."' and CS_PID=0")->row();
                    		        if($row){ //定单存在则加金币
                          		         //人民币转金币
                           		        $CION=$row->CS_RMB*Cion_RmbToCion;
                           		        $this->db->query("update ".CS_SqlPrefix."user set CS_Cion=CS_Cion+".$CION." where cs_name='".$row->CS_User."'");
                           		        //改变状态
                           		        $this->db->query("update ".CS_SqlPrefix."pay set CS_PID=1 where cs_id='".$row->CS_ID."'");
                           		        //发送消息
                             		        $msg['CS_Name']='金币充值成功消息';
                              		        $msg['CS_Neir']=$row->CS_User.'，您好，您已成功充值《'.$CION.'》个金币，定单号：'.$out_trade_no.'，如有问题，请联系管理员。';
                              		        $msg['CS_Usera']=$row->CS_User;
                              		        $msg['CS_Userb']='管理员';
                              		        $msg['CS_AddTime']=date('Y-m-d h:i:s');
                              		        $this->CsdjDB->get_insert('xiaoxi',$msg);
                        
                    		        }

				        echo "success";
				
			        } else {
			                echo "fail";
			        }
		        }elseif ($resHandler->getParameter("trade_mode") == "2"){ //判断签名及结果（中介担保）只有签名正确,retcode为0，trade_state为0才是支付成功

		               if($queryRes->isTenpaySign() && $queryRes->getParameter("retcode") == "0" ) {
				        $out_trade_no = $resHandler->getParameter("out_trade_no");
				        $transaction_id = $resHandler->getParameter("transaction_id");
				        $total_fee = $resHandler->getParameter("total_fee");
				        $discount = $resHandler->getParameter("discount");
				

				        switch ($resHandler->getParameter("trade_state")) {
						case "0":	//付款成功
						
							break;
						case "1":	//交易创建
						
							break;
						case "2":	//收获地址填写完毕
						
							break;
						case "4":	//卖家发货成功
						
							break;
						case "5":	//买家收货确认，交易成功
						
							break;
						case "6":	//交易关闭，未完成超时关闭
						
							break;
						case "7":	//修改交易价格成功
						
							break;
						case "8":	//买家发起退款
						
							break;
						case "9":	//退款成功
						
							break;
						case "10":	//退款关闭			
							
							break;
						default:
							//nothing to do
							break;
					}
				        echo "success";
			         } else{
			 	        echo "fail";
			         }
		        }
		
		
	
		}else{
	             //通信失败
		      echo "fail";
	        } 
	
	
	} else {
             echo "<br/>" . "认证签名失败" . "<br/>";
             echo $resHandler->getDebugInfo() . "<br>";
	}

    }

    //双接口交易付款
    public function alipay_1() { 

        $id=intval($this->input->get('id', TRUE));
        if($id==0) $this->CsdjSkins->Msg_url('参数错误!','javascript:history.back();'); 

        //获取数据库定单记录
        $row=$this->CsdjDB->get_select('pay','CS_ID','*',''.$id.'');
        if(!$row) $this->CsdjSkins->Msg_url('该定单不存在!','javascript:history.back();'); 

        $partner = $this->CsdjAlipay->partner;
        $security_code = $this->CsdjAlipay->security_code;
        $seller_email = $this->CsdjAlipay->seller_email;
        $_input_charset = $this->CsdjAlipay->_input_charset;
        $transport = $this->CsdjAlipay->transport;
        $notify_url = $this->CsdjAlipay->notify_url2;
        $return_url = $this->CsdjAlipay->return_url2;
        $show_url = $this->CsdjAlipay->show_url;
        $sign_type = $this->CsdjAlipay->sign_type;
        $mainname = $this->CsdjAlipay->mainname;
        $antiphishing = $this->CsdjAlipay->antiphishing;
        $gateway = $this->CsdjAlipay->gateway; 

        $out_trade_no = $row[0]->CS_Dingdan; // 唯一订单号，这里生成了一个 Unix 时间的例子
        $subject = $this->session->userdata('cs_name').'在线购买金币'; // 订单名称，显示在支付宝收银台里的“商品名称”里，显示在支付宝的交易管理的“商品名称”的列表里。
        $body = $subject; // 订单描述、订单详细、订单备注，显示在支付宝收银台里的“商品描述”里。
        $total_fee = $row[0]->CS_RMB; // 订单总金额，显示在支付宝收银台里的“应付总额”里，可以有两位小数。
        $pay_mode = "directPay";
        $paymethod = "directPay"; //默认支付方式，四个值可选：bankPay(网银); cartoon(卡通); directPay(余额); CASH(网点支付)
        $defaultbank = "";
        $encrypt_key = '';     //防钓鱼时间戳，初始值
        $exter_invoke_ip = '';    //客户端的IP地址，初始值
        if ($antiphishing == 1) {
            $encrypt_key = $this->CsdjAlipay->query_timestamp($partner);
            $exter_invoke_ip = '';   //获取客户端的IP地址，建议：编写获取客户端IP地址的程序
        }
        $extra_common_param = '';   //自定义参数，可存放任何内容（除=、&等特殊字符外），不会显示在页面上
        $buyer_email = '';   //默认买家支付宝账号

        $parameter = array(
            "service" => "trade_create_by_buyer", //接口名称，不需要修改
            "partner" => $partner,
            "payment_type" => "1", //交易类型，不需要修改
            "return_url" => $return_url,
            "notify_url" => $notify_url,
            "seller_email" => $seller_email,
            "out_trade_no" => $out_trade_no,
            "subject" => $subject,
	    "price"	=> $total_fee,
	    "quantity"	=> "1",
	    "logistics_fee"	=> "0.00",
	    "logistics_type"	=> "EXPRESS",
	    "logistics_payment"	=> "SELLER_PAY",
            "body" => $body,
            "show_url" => $show_url,
	    "receive_name"	=> "",
	    "receive_address"	=> "",
	    "receive_zip"	=> "",
	    "receive_phone"	=> "",
	    "receive_mobile"	=> "",
            "_input_charset" => $_input_charset,

        );
        // GET 方式传递，默认使用
        $url = $this->CsdjAlipay->create_url($parameter);
        echo "<script>window.location =\"$url\";</script>"; // 输出跳转链接
    }

    //即时倒帐交易付款
    public function alipay_2() {  

        $id=intval($this->input->get('id', TRUE));
        if($id==0) $this->CsdjSkins->Msg_url('参数错误!','javascript:history.back();');   

        //获取数据库定单记录
        $row=$this->CsdjDB->get_select('pay','CS_ID','*',''.$id.'');
        if(!$row) $this->CsdjSkins->Msg_url('该定单不存在!','javascript:history.back();'); 

        $partner = $this->CsdjAlipay->partner;
        $security_code = $this->CsdjAlipay->security_code;
        $seller_email = $this->CsdjAlipay->seller_email;
        $_input_charset = $this->CsdjAlipay->_input_charset;
        $transport = $this->CsdjAlipay->transport;
        $notify_url = $this->CsdjAlipay->notify_url;
        $return_url = $this->CsdjAlipay->return_url;
        $show_url = $this->CsdjAlipay->show_url;
        $sign_type = $this->CsdjAlipay->sign_type;
        $mainname = $this->CsdjAlipay->mainname;
        $antiphishing = $this->CsdjAlipay->antiphishing;
        $gateway = $this->CsdjAlipay->gateway; 

        $out_trade_no = $row[0]->CS_Dingdan; // 唯一订单号，这里生成了一个 Unix 时间的例子
        $subject = $this->session->userdata('cs_name').'在线购买金币'; // 订单名称，显示在支付宝收银台里的“商品名称”里，显示在支付宝的交易管理的“商品名称”的列表里。
        $body = $subject; // 订单描述、订单详细、订单备注，显示在支付宝收银台里的“商品描述”里。
        $total_fee = $row[0]->CS_RMB; // 订单总金额，显示在支付宝收银台里的“应付总额”里，可以有两位小数。
        $pay_mode = "directPay";
        $paymethod = "directPay"; //默认支付方式，四个值可选：bankPay(网银); cartoon(卡通); directPay(余额); CASH(网点支付)
        $defaultbank = "";
        $encrypt_key = '';     //防钓鱼时间戳，初始值
        $exter_invoke_ip = '';    //客户端的IP地址，初始值
        if ($antiphishing == 1) {
            $encrypt_key = $this->CsdjAlipay->query_timestamp($partner);
            $exter_invoke_ip = '';   //获取客户端的IP地址，建议：编写获取客户端IP地址的程序
        }
        $extra_common_param = '';   //自定义参数，可存放任何内容（除=、&等特殊字符外），不会显示在页面上
        $buyer_email = '';   //默认买家支付宝账号

        $parameter = array(
            "service" => "create_direct_pay_by_user", //接口名称，不需要修改
            "payment_type" => "1", //交易类型，不需要修改
            "partner" => $partner,
            "seller_email" => $seller_email,
            "return_url" => $return_url,
            "notify_url" => $notify_url,
            "_input_charset" => $_input_charset,
            "show_url" => $show_url,
            "out_trade_no" => $out_trade_no,
            "subject" => $subject,
            "body" => $body,
            "total_fee" => $total_fee,
            "paymethod" => $paymethod,
            "defaultbank" => $defaultbank,
            "anti_phishing_key" => $encrypt_key,
            "exter_invoke_ip" => $exter_invoke_ip,
            "buyer_email" => $buyer_email,
            "extra_common_param" => $extra_common_param
        );
        // GET 方式传递，默认使用
        $url = $this->CsdjAlipay->create_url($parameter);
        echo "<script>window.location =\"$url\";</script>"; // 输出跳转链接
    }

    /**
     * 双功能异步支付结果接收
     */
    public function notify_page_1() {

        $partner = $this->CsdjAlipay->partner;
        $security_code = $this->CsdjAlipay->security_code;
        $_input_charset = $this->CsdjAlipay->_input_charset;
        $transport = $this->CsdjAlipay->transport;
        $sign_type = $this->CsdjAlipay->sign_type;

        $verify_result = $this->CsdjAlipay->notify_verify();

        if ($verify_result) {
            //验证成功，获取支付宝的反馈参数
            $config['uri_protocol'] = "PATH_INFO";
            parse_str($_SERVER['QUERY_STRING'], $_POST);
            $trade = $this->input->post('out_trade_no', TRUE); //获取支付宝传递过来的订单号
            $total = $this->input->post('total_fee', TRUE);//获取支付宝传递过来的总价格
            $trade_status = $this->input->get_post('trade_status', TRUE); //获取支付宝传递过来交易状态


            if($trade_status == 'TRADE_FINISHED') { //交易完成

                    //获取数据库定单记录
                    $row=$this->db->query("select * from ".CS_SqlPrefix."pay where CS_Dingdan='".addslashes($trade)."' and CS_PID=0")->row();
                    if($row){ //定单存在则加金币
                           //人民币转金币
                           $CION=$row->CS_RMB*Cion_RmbToCion;
                           $this->db->query("update ".CS_SqlPrefix."user set CS_Cion=CS_Cion+".$CION." where cs_name='".$row->CS_User."'");
                           //改变状态
                           $this->db->query("update ".CS_SqlPrefix."pay set CS_PID=1 where cs_id='".$row->CS_ID."'");
                           //发送消息
                              $msg['CS_Name']='金币充值成功消息';
                              $msg['CS_Neir']=$row->CS_User.'，您好，您已成功充值《'.$CION.'》个金币，定单号：'.$trade.'，如有问题，请联系管理员。';
                              $msg['CS_Usera']=$row->CS_User;
                              $msg['CS_Userb']='管理员';
                              $msg['CS_AddTime']=date('Y-m-d h:i:s');
                              $this->CsdjDB->get_insert('xiaoxi',$msg);
                        
                    }

                echo "success";
            } else {
                echo "success";
            }
        } else {
            // 验证失败
            echo "fail";
        }

    }

    /**
     * 双功能同步支付结果接收
     */
    public function return_page_1() {

        $partner = $this->CsdjAlipay->partner;
        $security_code = $this->CsdjAlipay->security_code;
        $_input_charset = $this->CsdjAlipay->_input_charset;
        $transport = $this->CsdjAlipay->transport;
        $sign_type = $this->CsdjAlipay->sign_type;

        $verify_result = $this->CsdjAlipay->return_verify();
        if ($verify_result) {
            //验证成功，获取支付宝的反馈参数
            $config['uri_protocol'] = "PATH_INFO";
            parse_str($_SERVER['QUERY_STRING'], $_GET);
            $trade = $this->input->get_post('out_trade_no', TRUE); //获取支付宝传递过来的订单号
            $trade_status = $this->input->get_post('trade_status', TRUE); //获取支付宝传递过来交易状态

            $row=$this->db->query("select * from ".CS_SqlPrefix."pay where CS_Dingdan='".addslashes($trade)."'")->row();
            if(!$row){
                    $this->CsdjSkins->Msg_url('验证失败,该定单不存在!',site_url('user')); 
            }

            if($trade_status=='TRADE_FINISHED'){ //交易完成

                    if($row->CS_PID==0){ //定单存在则加金币
                           //人民币转金币
                           $CION=$row->CS_RMB*Cion_RmbToCion;
                           $this->db->query("update ".CS_SqlPrefix."user set CS_Cion=CS_Cion+".$CION." where cs_name='".$row->CS_User."'");
                           //改变状态
                           $this->db->query("update ".CS_SqlPrefix."pay set CS_PID=1 where cs_id='".$row->CS_ID."'");
                           //发送消息
                              $msg['CS_Name']='金币充值成功消息';
                              $msg['CS_Neir']=$row->CS_User.'，您好，您已成功充值《'.$CION.'》个金币，定单号：'.$trade.'，如有问题，请联系管理员。';
                              $msg['CS_Usera']=$row->CS_User;
                              $msg['CS_Userb']='管理员';
                              $msg['CS_AddTime']=date('Y-m-d h:i:s');
                              $this->CsdjDB->get_insert('xiaoxi',$msg);
                    }
                    $this->CsdjSkins->Msg_url('恭喜您，成功充值了 '.$CION.' 个金币，若出现问题请尽快联系客服,请牢记您的定单号：'.$trade.'!',site_url('user')); 

            } else if($trade_status=='WAIT_SELLER_SEND_GOODS'){ //付款成功,等带卖家发货
                 $this->CsdjSkins->Msg_url('恭喜您，成功付款 '.$row->CS_RMB.' 元，请联系管理员尽快发货，联系QQ：'.Web_QQ.',请牢记您的定单号：'.$trade.'!',site_url('user')); 
            } 

        }else {
            $this->CsdjSkins->Msg_url('非法交易，验证失败!',site_url('user')); 
        }
    }

    /**
     * 及时倒帐异步支付结果接收
     */
    public function notify_page_2() {

        $partner = $this->CsdjAlipay->partner;
        $security_code = $this->CsdjAlipay->security_code;
        $_input_charset = $this->CsdjAlipay->_input_charset;
        $transport = $this->CsdjAlipay->transport;
        $sign_type = $this->CsdjAlipay->sign_type;

        $verify_result = $this->CsdjAlipay->notify_verify();

        if ($verify_result) {
            //验证成功，获取支付宝的反馈参数
            $config['uri_protocol'] = "PATH_INFO";
            parse_str($_SERVER['QUERY_STRING'], $_POST);
            $trade = $this->input->post('out_trade_no', TRUE); //获取支付宝传递过来的订单号
            $total = $this->input->post('total_fee', TRUE);//获取支付宝传递过来的总价格
            if ($_POST['trade_status'] == 'TRADE_FINISHED' || $_POST['trade_status'] == 'TRADE_SUCCESS') {    //交易成功结束

                    //获取数据库定单记录
                    $row=$this->db->query("select * from ".CS_SqlPrefix."pay where CS_Dingdan='".addslashes($trade)."' and CS_PID=0")->row();
                    if($row){ //定单存在则加金币
                           //人民币转金币
                           $CION=$row->CS_RMB*Cion_RmbToCion;
                           $this->db->query("update ".CS_SqlPrefix."user set CS_Cion=CS_Cion+".$CION." where cs_name='".$row->CS_User."'");
                           //改变状态
                           $this->db->query("update ".CS_SqlPrefix."pay set CS_PID=1 where cs_id='".$row->CS_ID."'");
                           //发送消息
                              $msg['CS_Name']='金币充值成功消息';
                              $msg['CS_Neir']=$row->CS_User.'，您好，您已成功充值《'.$CION.'》个金币，定单号：'.$trade.'，如有问题，请联系管理员。';
                              $msg['CS_Usera']=$row->CS_User;
                              $msg['CS_Userb']='管理员';
                              $msg['CS_AddTime']=date('Y-m-d h:i:s');
                              $this->CsdjDB->get_insert('xiaoxi',$msg);
                        
                    }

                echo "success";
            } else {
                echo "success";
            }
        } else {
            // 验证失败
            echo "fail";
        }

    }

    /**
     * 及时倒帐同步支付结果接收
     */
    public function return_page_2() {

        $partner = $this->CsdjAlipay->partner;
        $security_code = $this->CsdjAlipay->security_code;
        $_input_charset = $this->CsdjAlipay->_input_charset;
        $transport = $this->CsdjAlipay->transport;
        $sign_type = $this->CsdjAlipay->sign_type;

        $verify_result = $this->CsdjAlipay->return_verify();
        if ($verify_result) {
            //验证成功，获取支付宝的反馈参数
            $config['uri_protocol'] = "PATH_INFO";
            parse_str($_SERVER['QUERY_STRING'], $_GET);
            $trade = $this->input->get_post('out_trade_no', TRUE); //获取支付宝传递过来的订单号
            $total = $this->input->get_post('total_fee', TRUE);//获取支付宝传递过来的总价格

                    $row=$this->db->query("select * from ".CS_SqlPrefix."pay where CS_Dingdan='".addslashes($trade)."'")->row();
                    if($row){
                         if($row->CS_PID==0){ //定单存在则加金币
                              //人民币转金币
                              $CION=$row->CS_RMB*Cion_RmbToCion;
                              $this->db->query("update ".CS_SqlPrefix."user set CS_Cion=CS_Cion+".$CION." where cs_name='".$row->CS_User."'");
                              //改变状态
                              $this->db->query("update ".CS_SqlPrefix."pay set CS_PID=1 where cs_id='".$row->CS_ID."'");
                              //发送消息
                              $msg['CS_Name']='金币充值成功消息';
                              $msg['CS_Neir']=$row->CS_User.'，您好，您已成功充值《'.$CION.'》个金币，定单号：'.$trade.'，如有问题，请联系管理员。';
                              $msg['CS_Usera']=$row->CS_User;
                              $msg['CS_Userb']='管理员';
                              $msg['CS_AddTime']=date('Y-m-d h:i:s');
                              $this->CsdjDB->get_insert('xiaoxi',$msg);
                         }
                              $this->CsdjSkins->Msg_url('恭喜您，成功充值了 '.$CION.' 个金币，若出现问题请尽快联系客服,请牢记您的定单号：'.$trade.'!',site_url('user')); 
                    }else{
                            $this->CsdjSkins->Msg_url('验证失败,该定单不存在!',site_url('user')); 
                    }
        }else {
            $this->CsdjSkins->Msg_url('非法交易，验证失败!',site_url('user')); 
        }
    }
}

