<?php 

defined('G_IN_SYSTEM')or exit('No permission resources.');
ini_set("display_errors","OFF");
class shoukuanla extends SystemAction {
	public function __construct(){
		$this->db=System::load_sys_class('model');		
	} 	
	

	public function houtai(){
    //收款啦配置,官网pay.chonty.com		
		if(isset($_POST['title']) && isset($_POST['sign']) && isset($_POST['order'])){
		$pay_type =$this->db->GetOne("SELECT * from `@#_pay` where `pay_class` = 'shoukuanlaAli'");
		$pay_type_key = unserialize($pay_type['pay_key']);
		$key =  $pay_type_key['key']['val'];		//支付KEY

		$sign        =trim($_POST['sign']);//回调签名
		$total_fee   =trim($_POST['money']);//收款金额
		$out_trade_no =trim($_POST['title']);//商户订单号
		$trade_no =trim($_POST['order']); //支付宝交易号

		function Check($cuid){
          if(!empty($cuid)){
            if(preg_match("/^[0-9a-zA-Z]{1,50}$|^([0-9]){1,20}\.([0-9])+$/",$cuid)){          
               return true;
            }else{return false;}
                  }else{return false;}
		 }
	  if(!Check($out_trade_no) || !Check($total_fee) ){
		 exit('error'); //商户订单号如果不是数字和字母组成停止脚本
		}

		if($key==null){  $key='pay.chonty.com'; }
		if($sign!=$key){exit('error');}

		//开始处理及时到账和担保交易订单
			$this->db->Autocommit_start();
			$dingdaninfo = $this->db->GetOne("select * from `@#_member_addmoney_record` where `code` = '$out_trade_no' and `status` = '未付款' for update");
			if(!$dingdaninfo){	echo "fail";exit;}	//没有该订单,失败
			$c_money =$total_fee;		//var_dump($c_money);	exit;
			$uid = $dingdaninfo['uid'];
			$time = time();			
			$up_q1 = $this->db->Query("UPDATE `@#_member_addmoney_record` SET `status` = '已付款' where `id` = '$dingdaninfo[id]' and `code` = '$dingdaninfo[code]'");
			$up_q2 = $this->db->Query("UPDATE `@#_member` SET `money` = `money` + $c_money where (`uid` = '$uid')");				
			$up_q3 = $this->db->Query("INSERT INTO `@#_member_account` (`uid`, `type`, `pay`, `content`, `money`, `time`) VALUES ('$uid', '1', '账户', '充值', '$c_money', '$time')");
				
			if($up_q1 && $up_q2 && $up_q3){
				$this->db->Autocommit_commit();			
			}else{
				$this->db->Autocommit_rollback();
				echo "fail";exit;
			}			
			if(empty($dingdaninfo['scookies'])){					
					echo "success";exit;	//充值完成			
			}			
			$scookies = unserialize($dingdaninfo['scookies']);			
			$pay = System::load_app_class('pay','pay');			
			$pay->scookie = $scookies;	

			$ok = $pay->init($uid,$pay_type['pay_id'],'go_record');	//云购商品	
			if($ok != 'ok'){
				_setcookie('Cartlist',NULL);
				echo "fail";exit;	//商品购买失败			
			}			
			$check = $pay->go_pay(1);
			if($check){
				$this->db->Query("UPDATE `@#_member_addmoney_record` SET `scookies` = '1' where `code` = '$out_trade_no' and `status` = '已付款'");
				_setcookie('Cartlist',NULL);
				echo "success";exit;			
			}else{
				echo "fail";exit;
			}

		}

}//开始处理订单结束				
	
}

?>