<?php
class notifyAction extends TopAction {    
	public function _initialize() {        
		
    }
     /**
     * 
     * 获取支付结果通知数据
     * return array
     */
    public function getNotifyData(){
        //获取通知的数据
        //$xml = $GLOBALS['HTTP_RAW_POST_DATA'];
		$xml = file_get_contents('php://input');
        $data = array();
        if( empty($xml) ){
            return false;
        }
        $data = $this->xml_to_data( $xml );
        if( !empty($data['return_code']) ){
            if( $data['return_code'] == 'FAIL' ){
                return false;
            }
        }
        return $data;
    }
    /**
     * 接收通知成功后应答输出XML数据
     * @param string $xml
     */
    public function replyNotify(){
        $data['return_code'] = 'SUCCESS';
        $data['return_msg'] = 'OK';
        $xml = $this->data_to_xml( $data );
        echo $xml;
        die();
    }	
	/**
     * 输出xml字符
     * @param   $params     参数名称
     * return   string      返回组装的xml
     **/
    public function data_to_xml( $params ){
        if(!is_array($params)|| count($params) <= 0)
        {
            return false;
        }
        $xml = "<xml>";
        foreach ($params as $key=>$val)
        {
            if (is_numeric($val)){
                $xml.="<".$key.">".$val."</".$key.">";
            }else{
                $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
            }
        }
        $xml.="</xml>";
        return $xml; 
    }
    /**
     * 将xml转为array
     * @param string $xml
     * return array
     */
    public function xml_to_data($xml){  
        if(!$xml){
            return false;
        }
        //将XML转为array
        //禁止引用外部xml实体
        libxml_disable_entity_loader(true);
        $data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);        
        return $data;
    }
	
	
	
	  
      
    public function MakeSign( $params ){	  
        //签名步骤一：按字典序排序数组参数
        ksort($params);
		$key = '微信支付KEY';
        $string = $this->ToUrlParams($params);
        //签名步骤二：在string后加入KEY
        $string = $string . "&key=" . $key;
        //签名步骤三：MD5加密
        $string = md5($string);
        //签名步骤四：所有字符转为大写
        $result = strtoupper($string);
        return $result;
    }

    /**
     * 将参数拼接为url: key=value&key=value
     * @param   $params
     * @return  string
     */
	 public function ToUrlParams($params)
	{
		$buff = "";
		foreach ($params as $k => $v)
		{
			if($k != "sign" && $v != "" && !is_array($v)){
				$buff .= $k . "=" . $v . "&";
			}
		}
		
		$buff = trim($buff, "&");
		return $buff;
	}
    	
   public function paycopy(){
        $data = $this->getNotifyData();
			if($data['result_code'] == 'SUCCESS'){			    
			    $sign = $this->MakeSign($data); 				
			    if($data['sign'] === $sign){//签名正确	
			        //$item['openid'] = $data['openid'];//用户标识
			        //$item['is_subscribe'] = $data['is_subscribe'];//是否关注公众帐号
			        //$item['trade_type'] = $data['trade_type'];//交易类型，JSAPI,NATIVE,APP
			        //$item['bank_type'] = $data['bank_type'];//付款银行，银行类型采用字符串类型的银行标识。
			        //$item['total_fee'] = $data['total_fee'];//订单总金额，单位为分
			        //$item['fee_type'] = $data['fee_type'];//货币类型，符合ISO4217的标准三位字母代码，默认为人民币：CNY。
			        //$item['transaction_id'] = $data['transaction_id'];//微信支付订单号
			        //$item['out_trade_no'] = $data['out_trade_no'];//商户订单号
			        //$item['attach'] = $data['attach'];//商家数据包，原样返回
			        //$item['time_end'] = $data['time_end'];//支付完成时间
			        //$item['cash_fee'] = $data['cash_fee'];//现金支付金额	
			        $out_trade_no = $data['out_trade_no'];		
					$plog = D('wpay_log')->where(array('order'=>$out_trade_no))->find();					
					$url = urldecode($plog['row']);
					//file_put_contents(FTX_DATA_PATH."pay_copy_row.txt","\n\r".json_encode($plog,320),FILE_APPEND|LOCK_EX);
					if($plog['row']){						
					$datas['info'] = $url;	
					$datas['mod'] = 'copypay';
					$datas['out_trade_no'] = $out_trade_no;				        
			        $datas['total_amount'] = $data['total_fee']/100;
			        $datas['trade_no'] = $data['transaction_id'];
					$datas['openid'] = $data['openid'];
			        $datas['add_time'] = time();
					$datas['add_date'] = strtotime(date('Y-m-d',time()));	
					$ido = D('ipay_log')->add($datas);
					if($ido){
					//file_put_contents(FTX_DATA_PATH."pay_copy_add.txt","\n\r".json_encode($datas,320).'---'.$ido,FILE_APPEND|LOCK_EX);
					D('wpay_log')->where(array('order'=>$out_trade_no))->delete();
					$where['add_time'] = array('lt',(time()-86400));
					D('wpay_log')->where($where)->delete();					
					//$sql = "OPTIMIZE TABLE `ytt_wpay_log`;";
					//$voList = M()->query($sql);					
					//$sql = "REPAIR TABLE `ytt_wpay_log`;";
					//M()->query($sql);			
					}
					}	
					//file_put_contents(FTX_DATA_PATH."pay_copy.txt","\n\r".json_encode($data,320),FILE_APPEND|LOCK_EX);
					$this->replyNotify();										
			    }			    
		    }		
	}	
	public function paydown(){
        $data = $this->getNotifyData();
			if($data['result_code'] == 'SUCCESS'){			    
			    $sign = $this->MakeSign($data); 				
			    if($data['sign'] === $sign){//签名正确	
			        //$item['openid'] = $data['openid'];//用户标识
			        //$item['is_subscribe'] = $data['is_subscribe'];//是否关注公众帐号
			        //$item['trade_type'] = $data['trade_type'];//交易类型，JSAPI,NATIVE,APP
			        //$item['bank_type'] = $data['bank_type'];//付款银行，银行类型采用字符串类型的银行标识。
			        //$item['total_fee'] = $data['total_fee'];//订单总金额，单位为分
			        //$item['fee_type'] = $data['fee_type'];//货币类型，符合ISO4217的标准三位字母代码，默认为人民币：CNY。
			        //$item['transaction_id'] = $data['transaction_id'];//微信支付订单号
			        //$item['out_trade_no'] = $data['out_trade_no'];//商户订单号
			        //$item['attach'] = $data['attach'];//商家数据包，原样返回
			        //$item['time_end'] = $data['time_end'];//支付完成时间
			        //$item['cash_fee'] = $data['cash_fee'];//现金支付金额	
			        $out_trade_no = $data['out_trade_no'];		
					$plog = D('wpay_log')->where(array('order'=>$out_trade_no))->find();					
					$url = $plog['row'];
					if($plog['row']){					
					$datas['info'] = $url;
					$datas['mod'] = 'downpay';
					$datas['out_trade_no'] = $out_trade_no;				        
			        $datas['total_amount'] = $data['total_fee']/100;
			        $datas['trade_no'] = $data['transaction_id'];
					$datas['openid'] = $data['openid'];
			        $datas['add_time'] = time();
					$datas['add_date'] = strtotime(date('Y-m-d',time()));						
					$ido = D('ipay_log')->add($datas);					
					if($ido){
					D('wpay_log')->where(array('order'=>$out_trade_no))->delete();
					$where['add_time'] = array('lt',(time()-86400));
					D('wpay_log')->where($where)->delete();	
					//$sql = "OPTIMIZE TABLE `ytt_wpay_log`;";
					//$voList = M()->query($sql);					
					//$sql = "REPAIR TABLE `ytt_wpay_log`;";
					//M()->query($sql);	
					}
					}													
					$this->replyNotify();
										
			    }			    
		    }		
	}
	
	public function payqm(){
        $data = $this->getNotifyData();
        //file_put_contents(FTX_DATA_PATH."pay_qm.txt","\n\r".json_encode($data,320),FILE_APPEND|LOCK_EX);
			if($data['result_code'] == 'SUCCESS'){			    
			    $sign = $this->MakeSign($data); 				
			    if($data['sign'] === $sign){//签名正确	
			        //$item['openid'] = $data['openid'];//用户标识
			        //$item['is_subscribe'] = $data['is_subscribe'];//是否关注公众帐号
			        //$item['trade_type'] = $data['trade_type'];//交易类型，JSAPI,NATIVE,APP
			        //$item['bank_type'] = $data['bank_type'];//付款银行，银行类型采用字符串类型的银行标识。
			        //$item['total_fee'] = $data['total_fee'];//订单总金额，单位为分
			        //$item['fee_type'] = $data['fee_type'];//货币类型，符合ISO4217的标准三位字母代码，默认为人民币：CNY。
			        //$item['transaction_id'] = $data['transaction_id'];//微信支付订单号
			        //$item['out_trade_no'] = $data['out_trade_no'];//商户订单号
			        //$item['attach'] = $data['attach'];//商家数据包，原样返回
			        //$item['time_end'] = $data['time_end'];//支付完成时间
			        //$item['cash_fee'] = $data['cash_fee'];//现金支付金额	
			        $out_trade_no = $data['out_trade_no'];
					$datas['info'] = $data['attach'];
					$datas['mod'] = 'qmpay';
					$datas['out_trade_no'] = $out_trade_no;
			        $datas['total_amount'] = $data['total_fee']/100;
			        $datas['trade_no'] = $data['transaction_id'];
					$datas['openid'] = $data['openid'];
			        $datas['add_time'] = time();
					$datas['pass'] = 1;
					$datas['isalipay'] = 0;
					$datas['add_date'] = strtotime(date('Y-m-d',time()));
					$ido = D('qm_log')->add($datas);
					$this->replyNotify();
			    }			    
		    }		
	}
		
		
}
?>	