<?php 
ini_set('date.timezone','Asia/Shanghai');
//error_reporting(E_ERROR);
require_once "paylib/WxPay.Api.php";
require_once "WxPay.JsApiPay.php";
require_once 'log.php';

//设置统一语言格式
	header("Content-type: text/html; charset=utf8"); 
	
	require_once("db/db.php");	
	require_once("common/common.php");
	
	$price = trim($_REQUEST['price']);	
	$orderno = trim($_REQUEST['orderno']);	

	$price=str_replace(',','',$price);
	
	$pricewx = $price;
	$intIsDubgeModle = WxMainConfig::NowIsDubgeModle;
	if($intIsDubgeModle=='1')
	{
		$pricewx = '0.01';
	}
	
	$sql = sprintf("SELECT Sum(PayFor_Value)AS SumPayFor FROM TR_Consume_List WHERE order_no='%s'",$orderno);
	$result = querySql($sql);
	$row = fetch_array($result);
	$havepayfor = $row['SumPayFor']; //预订房型
	freeResult($result);
	
if($havepayfor>0)
{
	closeDb();
	$strtemp='已支付成功！';
	echo "<script>window.location.href='index.php';</script>";
	exit;
}
$_SESSION["main_wxpayforyd"]='1';
//初始化日志
$logHandler= new CLogFileHandler("logs/".date('Y-m-d').'.log');
$log = Log::Init($logHandler, 15);

//打印输出数组信息
function printf_info($data)
{
    foreach($data as $key=>$value){
        echo "<font color='#00ff55;'>$key</font> : $value <br/>";
    }
}

//生成商户单号唯一
$strMchBillNo=WxPayConfig::MCHID.date("YmdHis");

//①、获取用户openid
$tools = new JsApiPay();

$openId = $tools->GetOpenid();
//exit();
//echo "openid=".$openId;


//②、统一下单
$input = new WxPayUnifiedOrder();
$input->SetBody("客房预付款");
$input->SetAttach("test");
//$input->SetOut_trade_no(WxPayConfig::MCHID.date("YmdHis"));
$input->SetOut_trade_no($strMchBillNo);	//2017-06-13添加商户单号

$input->SetTotal_fee("".($pricewx*100));
$input->SetTime_start(date("YmdHis"));
$input->SetTime_expire(date("YmdHis", time() + 600));
$input->SetGoods_tag("test");
//$input->SetNotify_url("http://paysdk.weixin.qq.com/example/notify.php");
$input->SetNotify_url(WxMainConfig::ServerHttpPath."wxbook/wxpaycallback.php");
$input->SetTrade_type("JSAPI");

//*$input->SetTrade_type("NATIVE");//使用回调页面
//*$input->SetProduct_id($strMchBillNo);

$input->SetOpenid($openId);
;
$order = WxPayApi::unifiedOrder($input);
//echo '<font color="#f00"><b>统一下单支付单信息</b></font><br/>';
//var_dump($order);
$jsApiParameters = $tools->GetJsApiParameters($order);

//获取共享收货地址js函数参数
$editAddress = $tools->GetEditAddressParameters();

//③、在支持成功回调通知中处理成功之后的事宜，见 notify.php
/**
 * 注意：
 * 1、当你的回调地址不可访问的时候，回调通知会失败，可以通过查询订单来确认支付是否成功
 * 2、jsapi支付时需要填入用户openid，WxPay.JsApiPay.php中有获取openid流程 （文档可以参考微信公众平台“网页授权接口”，
 * 参考http://mp.weixin.qq.com/wiki/17/c0f37d5704f0b64713d5d2c37b468d75.html）
 */
 
 //开始添加支付记录
 $sql = sprintf("if not exists (select ListNo from WX_Pay_List where OrderNo='%s' And WXOrderNo='%s' And PriceVal=%s)
						INSERT INTO WX_Pay_List(TradeTime,OrderNo,PayType,WXOrderNo,PriceVal,DoFlag) 
						Values(GetDate(),'%s','2','%s',%s,0)",$orderno, $strMchBillNo,$price,$orderno,$strMchBillNo,$price);//wx
$result = querySql($sql);

closeDb();
?>

<html>
<head>
    <meta http-equiv="content-type" content="text/html;charset=utf8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1"/> 
    <title>微信支付</title>
    <script type="text/javascript">
	//调用微信JS api 支付
	function jsApiCall()
	{
		WeixinJSBridge.invoke(
			'getBrandWCPayRequest',
			<?php echo $jsApiParameters; ?>,
			function(res){
				WeixinJSBridge.log(res.err_msg);
				//alert(res.err_code);//+res.err_desc+res.err_msg);
				 if(res.err_msg == "get_brand_wcpay_request:ok") // 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回    ok，但并不保证它绝对可靠。 
				 {
					 //alert("prepaysave.php?preprice=<?php echo $price;?>&orderno=<?php echo $orderno;?>&paytype=2");
					//alert("准备支付");
					window.location = "prepaysave.php?preprice=<?php echo $price;?>&orderno=<?php echo $orderno;?>&paytype=2&wxbill=<?php echo $strMchBillNo;?>";
				 } 
				 else if(res.err_msg == "get_brand_wcpay_request:cancel") 
				 {
					//alert("支付失败2");
					//window.location = "index.php";
					window.location = "wxpaydot.php?dotid=1&wxorderno=<?php echo $strMchBillNo;?>&price=<?php echo $price;?>&orderno=<?php echo $orderno;?>";
				 }  
				 else if(res.err_msg == "get_brand_wcpay_request:fail") 
				 {
					alert("支付失败");
					//window.location = "paysel.php?price=<?php echo $price;?>&orderno=<?php echo $orderno;?>";
					window.location = "wxpaydot.php?dotid=2&wxorderno=<?php echo $strMchBillNo;?>&price=<?php echo $price;?>&orderno=<?php echo $orderno;?>";
				 } 
				 else
				 {
					//alert("支付失败3");
					//window.location = "paysel.php?price=<?php echo $price;?>&orderno=<?php echo $orderno;?>";
					window.location = "wxpaydot.php?dotid=3&wxorderno=<?php echo $strMchBillNo;?>&price=<?php echo $price;?>&orderno=<?php echo $orderno;?>";
				 }
			}
		);
	}

	function callpay()
	{
		if (typeof WeixinJSBridge == "undefined"){
		    if( document.addEventListener ){
		        document.addEventListener('WeixinJSBridgeReady', jsApiCall, false);
		    }else if (document.attachEvent){
		        document.attachEvent('WeixinJSBridgeReady', jsApiCall); 
		        document.attachEvent('onWeixinJSBridgeReady', jsApiCall);
		    }
		}else{
		    jsApiCall();
		}
	}
	</script>
	<script type="text/javascript">
	//获取共享地址
	function editAddress()
	{
		WeixinJSBridge.invoke(
			'editAddress',
			<?php echo $editAddress; ?>,
			function(res){
				var value1 = res.proviceFirstStageName;
				var value2 = res.addressCitySecondStageName;
				var value3 = res.addressCountiesThirdStageName;
				var value4 = res.addressDetailInfo;
				var tel = res.telNumber;
				
				alert(value1 + value2 + value3 + value4 + ":" + tel);
			}
		);
	}
	
	window.onload = function(){
		/*
		if (typeof WeixinJSBridge == "undefined"){
		    if( document.addEventListener ){
		        document.addEventListener('WeixinJSBridgeReady', editAddress, false);
		    }else if (document.attachEvent){
		        document.attachEvent('WeixinJSBridgeReady', editAddress); 
		        document.attachEvent('onWeixinJSBridgeReady', editAddress);
		    }
		}else{
			editAddress();
		}
		*/
		callpay();
	};
	
	</script>
	
	<script language="JavaScript"> 
		//不允许进行后退
		javascript:window.history.forward(0); 
	</script>
</head>
<body leftmargin="0" rightmargin="0" topmargin="0" bottommargin="0">
&nbsp;<br>
<center><span style='color:green;font-size:22px'><b>请勿关闭或退出此页面</b></span></center>
&nbsp;<br>
<center><span style='color:green;font-size:22px'><b>否则付款后将无法入帐</b></span></center>
<p>
</body>
</html>