<?php
$notify_jg='';
foreach($_POST as $key=>$val){
	if($key=='body_title'){
		$xmlarray['body']=$val; 
	}
	elseif($key=='tongzhiym'){
		$notify_jg = $val;
	}
	elseif($key=='appid'){
		if($notify_jg){
			$xmlarray[$key]=$val;
		}
		else{
			define('APPID', $val);
		}
	}
	elseif($key=='mch_id'){
		if($notify_jg){
			$xmlarray[$key]=$val;
		}
		else{
			define('MCHID', $val); 
		}
	}
	elseif($key=='paykey'){
		define('KEY', $val);
	}
	else{
		$xmlarray[$key]=$val;
	}
}

if($notify_jg!='abc'){
	//$xml=arrayToXml($xmlarray);
	$unifiedOrderResult = getResult($xmlarray);
	if ($unifiedOrderResult["return_code"] == "FAIL"){
		//商户自行增加处理流程
		echo "通信出错：".$unifiedOrderResult['return_msg']."<br>";
	}
	elseif($unifiedOrderResult["result_code"] == "FAIL"){
		//商户自行增加处理流程
		echo "错误代码：".$unifiedOrderResult['err_code']."<br>";
		echo "错误代码描述：".$unifiedOrderResult['err_code_des']."<br>";
	}
	elseif($unifiedOrderResult["code_url"] != NULL){
		$code_url = $unifiedOrderResult["code_url"];
		echo $code_url;
	}
}
else{
	$xml=getSign($xmlarray);
	echo $xml;
}
function postXmlCurl($xml,$url,$second=30){		
        //初始化curl        
       	$ch = curl_init();
		//设置超时
		//curl_setopt($ch, CURLOP_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);
		//设置header
		curl_setopt($ch, CURLOPT_HEADER, FALSE);
		//要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
		//post提交方式
		curl_setopt($ch, CURLOPT_POST, TRUE);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
		//运行curl
        $data = curl_exec($ch);
		curl_close($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;
		}
}
/**
	 * 	作用：post请求xml
	 */
function postXml($parameters){
		$url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
		//设置curl超时时间
		$curl_timeout = 30;
	    $xml = createXml($parameters);
		$response = postXmlCurl($xml,$url,$curl_timeout);
		return $response;
}
function getResult($parameters){		
	$response=postXml($parameters);
	$result = xmlToArray($response);
	return $result;
}
function createXml($parameters)
	{
		try
		{
			//检测必填参数
			if($parameters["out_trade_no"] == null) 
			{
				throw new SDKRuntimeException("缺少统一支付接口必填参数out_trade_no！"."<br>");
			}elseif($parameters["body"] == null){
				throw new SDKRuntimeException("缺少统一支付接口必填参数body！"."<br>");
			}elseif ($parameters["total_fee"] == null ) {
				throw new SDKRuntimeException("缺少统一支付接口必填参数total_fee！"."<br>");
			}elseif ($parameters["notify_url"] == null) {
				throw new SDKRuntimeException("缺少统一支付接口必填参数notify_url！"."<br>");
			}elseif ($parameters["trade_type"] == null) {
				throw new SDKRuntimeException("缺少统一支付接口必填参数trade_type！"."<br>");
			}elseif ($parameters["trade_type"] == "JSAPI" &&
				$parameters["openid"] == NULL){
				throw new SDKRuntimeException("统一支付接口中，缺少必填参数openid！trade_type为JSAPI时，openid为必填参数！"."<br>");
			}
		   	$parameters["appid"] = APPID;//公众账号ID
		   	$parameters["mch_id"] = MCHID;//商户号
		   	$parameters["spbill_create_ip"] = $_SERVER['REMOTE_ADDR'];//终端ip	    
		    $parameters["nonce_str"] = createNoncestr();//随机字符串
		    $parameters["sign"] = getSign($parameters);//签名
		    return  arrayToXml($parameters);
		}catch (SDKRuntimeException $e)
		{
			die($e->errorMessage());
		}
	}
		
	/**
	 * 	作用：将xml转为array
	 */
	function xmlToArray($xml)
	{		
        //将XML转为array        
        $array_data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);		
		return $array_data;
	}
	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; 
    }
/**
* 	作用：生成签名
*/
function getSign($Obj){
	foreach ($Obj as $k => $v){
		$Parameters[$k] = $v;
	}
	//签名步骤一：按字典序排序参数
	ksort($Parameters);
	$String = formatBizQueryParaMap($Parameters, false);
	//echo '【string1】'.$String.'</br>';
	//签名步骤二：在string后加入KEY
	$String = $String."&key=".KEY;
	//echo "【string2】".$String."</br>";
	//签名步骤三：MD5加密
	$String = md5($String);
	//echo "【string3】 ".$String."</br>";
	//签名步骤四：所有字符转为大写
	$result_ = strtoupper($String);
	//echo "【result】 ".$result_."</br>";
	return $result_;
}
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;
}
/**
	* 	作用：产生随机字符串，不长于32位
*/
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;
}
class  SDKRuntimeException extends Exception {
	public function errorMessage()
	{
		return $this->getMessage();
	}

}
class Log_
{
	// 打印log
	function  log_result($file,$word) 
	{
		date_default_timezone_set('PRC');
	    $fp = fopen($file,"a");
	    flock($fp, LOCK_EX) ;
	    fwrite($fp,"执行日期：".date("Y-m-d H:i:s",time())."\n".$word."\n\n");
	    flock($fp, LOCK_UN);
	    fclose($fp);
	}
}
?>