<?php
require_once CONFIG_PATH.'wx.php';//加载配置文件;
class weixinpay {
	function trimString($value){
		$ret = null;
		if (null != $value){
			$ret = $value;
			if (strlen($ret) == 0){
				$ret = null;
			}
		}
		return $ret;
	}
	public function createNoncestr($length = 32){
		$chars = "abcdefghijklmnopqrstuvwxyz0123456789";  
		$str ="";
		for($i = 0;$i < $length;$i++){  
			$str.= substr($chars, mt_rand(0, strlen($chars)-1), 1);  
		}  
		return $str;
	}
	function formatBizQueryParaMap($paraMap, $urlencode){
		$buff = "";
		ksort($paraMap);
		foreach ($paraMap as $k => $v){
		    if($urlencode){
			   $v = urlencode($v);
			}
			//$buff .= strtolower($k) . "=" . $v . "&";
			$buff .= $k . "=" . $v . "&";
		}
		$reqPar;
		if (strlen($buff) > 0){
			$reqPar = substr($buff, 0, strlen($buff)-1);
		}
		return $reqPar;
	}
	public function getSign($Obj){
		foreach ($Obj as $k => $v){
			$Parameters[$k] = $v;
		}
		ksort($Parameters);
		$String = $this->formatBizQueryParaMap($Parameters, false);
		$String = $String."&key=".WxPayConfig::KEY;
		$String = md5($String);
		$result_ = strtoupper($String);
		// print_r($Parameters);
		// print_r($result_);
		return $result_;
	}
	function arrayToXml($arr){
        $xml = "<xml>";
        foreach ($arr as $key=>$val){
        	 if (is_numeric($val)){
        	 	$xml.="<".$key.">".$val."</".$key.">"; 

        	 }else{
        	 	$xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
			 }
        }
        $xml.="</xml>";
        return $xml; 
    }
	public function xmlToArray($xml){		
        //将XML转为array        
        $array_data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);		
		return $array_data;
	}
	public function postXmlCurl($xml,$url,$second=30){		
  
       	$ch = curl_init();
		curl_setopt($ch, CURLOPT_TIMEOUT, $second);
        //这里设置代理，如果有的话
        //curl_setopt($ch,CURLOPT_PROXY, '8.8.8.8');
        //curl_setopt($ch,CURLOPT_PROXYPORT, 8080);
        curl_setopt($ch,CURLOPT_URL, $url);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);
		curl_setopt($ch, CURLOPT_HEADER, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
		curl_setopt($ch, CURLOPT_POST, TRUE);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
        $data = curl_exec($ch);
		//返回结果
		if($data){
			curl_close($ch);
			return $data;
		}else{ 
			$error = curl_errno($ch);
			echo "curl出错，错误码:$error"."<br>"; 
			echo "<a href='http://curl.haxx.se/libcurl/c/libcurl-errors.html'>错误原因查询</a></br>";
			curl_close($ch);
			return false;
		}
	}
}
class Wxpay_client_pub extends weixinpay{
	var $parameters;//请求参数，类型为关联数组
	public $response;//微信返回的响应
	public $result;//返回参数，类型为关联数组
	var $url;//接口链接
	function setParameter($parameter, $parameterValue){
		$this->parameters[$this->trimString($parameter)] = $this->trimString($parameterValue);
	}
	function createXml(){
	   	$this->parameters["appid"] = WxPayConfig::APPID;//公众账号ID
	   	$this->parameters["mch_id"] = WxPayConfig::MCHID;//商户号
	    $this->parameters["nonce_str"] = parent::createNoncestr();//随机字符串
	    $this->parameters["sign"] = parent::getSign($this->parameters);//签名
	    return  parent::arrayToXml($this->parameters);
	}
	function postXml(){
	    $xml = $this->createXml();
		$this->response = $this->postXmlCurl($xml,$this->url,WxPayConfig::CURL_TIMEOUT);
		return $this->response;
	}
	function postXmlSSL(){	
	    $xml = $this->createXml();
		$this->response = $this->postXmlSSLCurl($xml,$this->url,WxPayConfig::CURL_TIMEOUT);
		return $this->response;
	}
	function getResult(){
		$this->postXml();
		$this->result = $this->xmlToArray($this->response);
		return $this->result;
	}
}
/**
 * 统一支付接口类
 */
class UnifiedOrder_pub extends Wxpay_client_pub{
	function __construct(){
		//设置接口链接
		$this->url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
	}
	function createXml(){
		try{
			//检测必填参数
			if($this->parameters["out_trade_no"] == null){
				throw new SDKRuntimeException("缺少统一支付接口必填参数out_trade_no！"."<br>");
			}elseif($this->parameters["body"] == null){
				throw new SDKRuntimeException("缺少统一支付接口必填参数body！"."<br>");
			}elseif ($this->parameters["total_fee"] == null ) {
				throw new SDKRuntimeException("缺少统一支付接口必填参数total_fee！"."<br>");
			}elseif ($this->parameters["notify_url"] == null) {
				throw new SDKRuntimeException("缺少统一支付接口必填参数notify_url！"."<br>");
			}elseif ($this->parameters["trade_type"] == null) {
				throw new SDKRuntimeException("缺少统一支付接口必填参数trade_type！"."<br>");
			}elseif ($this->parameters["trade_type"] == "JSAPI" && $this->parameters["openid"] == NULL){
				throw new SDKRuntimeException("统一支付接口中，缺少必填参数openid！trade_type为JSAPI时，openid为必填参数！"."<br>");
			}
		   	$this->parameters["appid"] = WxPayConfig::APPID;//公众账号ID
		   	$this->parameters["mch_id"] = WxPayConfig::MCHID;//商户号
		   	$this->parameters["spbill_create_ip"] = $_SERVER['REMOTE_ADDR'];//终端ip	    
		    $this->parameters["nonce_str"] = $this->createNoncestr();//随机字符串
		    $this->parameters["sign"] = $this->getSign($this->parameters);//签名
			//print_r($this->parameters);
		    return  $this->arrayToXml($this->parameters);
		}catch (SDKRuntimeException $e){
			die($e->errorMessage());
		}
	}
	function getPrepayId(){
		$this->postXml();
		$this->result = $this->xmlToArray($this->response);
		$prepay_id = $this->result["prepay_id"];
		return $prepay_id;
	}
}
class OrderQuery_pub extends Wxpay_client_pub{
	function __construct(){
		$this->url = "https://api.mch.weixin.qq.com/pay/orderquery";
	}
	/**
	 * 生成接口参数xml
	*/
	function createXml(){
		try{
			//检测必填参数
			if($this->parameters["out_trade_no"] == null && $this->parameters["transaction_id"] == null) 
			{
				throw new SDKRuntimeException("订单查询接口中，out_trade_no、transaction_id至少填一个！"."<br>");
			}
		   	$this->parameters["appid"] = WxPayConfig::APPID;//公众账号ID
		   	$this->parameters["mch_id"] = WxPayConfig::MCHID;//商户号
		    $this->parameters["nonce_str"] = $this->createNoncestr();//随机字符串
		    $this->parameters["sign"] = $this->getSign($this->parameters);//签名
			//print_r($this->parameters);
		    return $this->arrayToXml($this->parameters);
		}catch (SDKRuntimeException $e){
			die($e->errorMessage());
		}
	}
}
?>