<?php
/**
 * JS_API支付demo
 * ====================================================
 * 在微信浏览器里面打开H5网页中执行JS调起支付。接口输入输出数据格式为JSON。
 * 成功调起支付需要三个步骤：
 * 步骤1：网页授权获取用户openid
 * 步骤2：使用统一支付接口，获取prepay_id
 * 步骤3：使用jsapi调起支付
*/
header("Content-type:text/html;charset=utf-8");
    session_start(); 
	include_once("../WxPayPubHelper/WxPayPubHelper.php");
	include_once("../WxPayPubHelper/WxPay.pub.config.php");
	error_reporting(E_ALL || ~E_NOTICE);
     
	
	
	
	
	//使用jsapi接口
	$jsApi = new JsApi_pub();

	//=========步骤1：网页授权获取用户openid============
	//通过code获得openid
	if (!isset($_GET['code']))
	{
	
		//接收到两个参数
		$state=$_GET['order_number'].",".$_GET['oeder_price'].",".$_GET['type'];
		//触发微信返回code码
		$url = $jsApi->createOauthUrlForCode(WxPayConf_pub::JS_API_CALL_URL,$state);
		Header("Location: $url");
		
		
	}else
	{
		//获取code码，以获取openid
	    $code = $_GET['code'];
		$jsApi->setCode($code);
		$openid = $jsApi->getOpenId();
		
	}
		
	    $state=$_GET['state'];
		$states=explode(',',$state);
		$ordernum=$states[0];
		$price=$states[1];
		$type=$states[2];

		  if($type=="good_order"){
			  $sb_url='?c=user&a=w_order';
			  $cg_url='index.php?c=user&a=y_order';
			  $body = '订单支付';
		  }else if($type=="recharge_order"){
			  $sb_url='index.php?c=user&a=recharge';
			  $cg_url='index.php?c=user&a=record&pay_type=1';
			  $body = '用户充值';
		  }	else if($type=="type_order"){
			  $sb_url='index.php?c=user';
			  $cg_url='index.php?c=user';
			  $body = '申请会员类型';
		  }	else if($type=="code_order"){
			  $sb_url='index.php?c=user&a=user_delegated';
			  $cg_url='index.php?c=user&a=user_delegated';
			  $body = '域名授权';
		  }	
	
	$out_trade_no=$ordernum;//商户订单号
	$total_fee=$price*100;//付款金额
	//$total_fee=1;
	//积分和人民币  1:10  除以10转化为人民币
	//除以10转化为人民币
	// $total_fee=round($total_fee/RATIO,0);
	
	//=========步骤2：使用统一支付接口，获取prepay_id============
	//使用统一支付接口
	$unifiedOrder = new UnifiedOrder_pub();
	
	//设置统一支付接口参数
	//设置必填参数
	//appid已填,商户无需重复填写
	//mch_id已填,商户无需重复填写
	//noncestr已填,商户无需重复填写
	//spbill_create_ip已填,商户无需重复填写
	//sign已填,商户无需重复填写
	$unifiedOrder->setParameter("openid",$openid);//商品描述
	
	$unifiedOrder->setParameter("body",$body);//商品描述
	//自定义订单号，此处仅作举例
	$timeStamp = time();
	//$out_trade_no = WxPayConf_pub::APPID."$timeStamp";
	$unifiedOrder->setParameter("out_trade_no",$out_trade_no);//商户订单号
	 
	$unifiedOrder->setParameter("total_fee",$total_fee);//总金额

	if($type=="good_order")
	{
	$unifiedOrder->setParameter("notify_url",WxPayConf_pub::NOTIFY_URL1);//支付通知地址 
    }else if($type=="recharge_order")
    {
	$unifiedOrder->setParameter("notify_url",WxPayConf_pub::NOTIFY_URL);//充值通知地址 
	}else if($type=="type_order")
    {
	$unifiedOrder->setParameter("notify_url",WxPayConf_pub::NOTIFY_URL2);//会员类型通知地址 
	}else if($type=="code_order")
    {
	$unifiedOrder->setParameter("notify_url",WxPayConf_pub::NOTIFY_URL3);//会员类型通知地址 
	}
	$unifiedOrder->setParameter("trade_type","JSAPI");//交易类型
	//非必填参数，商户可根据实际情况选填
	//$unifiedOrder->setParameter("sub_mch_id","XXXX");//子商户号  
	//$unifiedOrder->setParameter("device_info","XXXX");//设备号 
	//$unifiedOrder->setParameter("attach","XXXX");//附加数据 
	//$unifiedOrder->setParameter("time_start","XXXX");//交易起始时间
	//$unifiedOrder->setParameter("time_expire","XXXX");//交易结束时间 
	//$unifiedOrder->setParameter("goods_tag","XXXX");//商品标记 
	//$unifiedOrder->setParameter("openid","XXXX");//用户标识
	//$unifiedOrder->setParameter("product_id","XXXX");//商品ID

	$prepay_id = $unifiedOrder->getPrepayId();
	//=========步骤3：使用jsapi调起支付============	
	
	$jsApi->setPrepayId($prepay_id);

	$jsApiParameters = $jsApi->getParameters();


	/*print_r($jsApiParameters);
	die;*/

	//echo $jsApiParameters;
?>

<html>
<head>
    <meta http-equiv="content-type" content="text/html;charset=utf-8"/>
    <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:cancel"){
					     window.location.href="http://<?php echo $_SERVER["HTTP_HOST"];?>/<?php echo $sb_url;?>";
						 return false;	
						 						 
					}
					
                    //支付成功
					if(res.err_msg=="get_brand_wcpay_request:ok"){
						 window.location.href="http://<?php echo $_SERVER["HTTP_HOST"];?>/<?php echo $cg_url;?>";
                         return false;	
											 
					}	

					   
					   
					   
				}
			);
		}

		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>
</head>
<body  onload="callpay()">
	
</body>
</html>