<?php
/**
 *	[超级活动(xj_event.{modulename})] (C)2012-2099 Powered by 逍遥工作室.
 *	Version: 1.0
 *	Date: 2012-9-15 10:27
 */

if(!defined('IN_DISCUZ')) {
	exit('Access Denied');
}



/*
if($_G['cache']['plugin']['xj_event']['weixinpayurl'] && empty($_GET['openid'])){
	Header("Location: ".$_G['cache']['plugin']['xj_event']['weixinpayurl']."?&apptype=xj_event&tid=".$_GET['tid']);
	exit();
}
*/
if($_G['cache']['plugin']['xj_event']['weixinpayurl'] && empty($_GET['code'])){
	//调用微信支付设置
	if(file_exists($xj_event_wxset = DISCUZ_ROOT.'./data/sysdata/cache_xj_event_wxset.php')) {
		@include $xj_event_wxset;
	}
	$appid = $wxset['appid'];
	Header("Location: ".$_G['cache']['plugin']['xj_event']['weixinpayurl']."?appid=".$appid."&scope=snsapi_base&state=".md5(FORMHASH)."&redirect_uri=".urlencode($_G['siteurl']."plugin.php?id=xj_event:wsq_pay&tid=".$_GET['tid']));
	
	//Header("Location: ".$_G['cache']['plugin']['xj_event']['weixinpayurl']."?&apptype=xj_event&tid=".$_GET['tid']);
	exit();
}





//调用核心类
include 'source/plugin/xj_event/include/core.class.php';
$eventcore = new xj_eventcore();



//0元支付处理   
$tid = intval($_GET['tid']);
$youhuiprice = $eventcore->GetYouHui($tid,$_G['uid']);  //优惠计算
$totalprice = $eventcore->GetEventPrice($tid,$_G['uid']); //总价格
if(($totalprice-$youhuiprice)<=0){
	$applyid = DB::result_first("SELECT applyid FROM ".DB::table('xj_eventapply')." WHERE tid = '$tid' and uid=".$_G['uid']);
	DB::update('xj_eventapply',array('verify'=>1,'pay_state'=>1),"applyid=$applyid");
	showmessage(lang('plugin/xj_event','gxnbmcg'),$_G['siteurl']."forum.php?mod=viewthread&tid=$tid");
	exit;
}








//调用微信支付设置
if(file_exists($xj_event_wxset = DISCUZ_ROOT.'./data/sysdata/cache_xj_event_wxset.php')) {
	@include $xj_event_wxset;
}
require_once libfile('function/cache');
$appid = $wxset['appid'];
$appsecret = $wxset['appsecret'];
$apikey = $wxset['apikey'];   //APIKEY
$mch_id = $wxset['mch_id'];  //商户号


$tid = intval($_GET['tid']);
$siteid = $_G['wechat']['setting']['wsq_siteid'];
if(!$_G['uid']) {
	showmessage('not_loggedin', NULL, array(), array('login' => 1));
}
if(!isset($appid) && !isset($appsecret) && !isset($apikey) && !isset($mch_id)){
	showmessage($_G['charset']=='gbk'?iconv('GBK','UTF-8',lang('plugin/xj_event', 'wxzfmysz')):lang('plugin/xj_event', 'wxzfmysz'),'forum.php?mod=viewthread&tid='.$tid);
}




//通过code获得openid
if (!isset($_GET['code']))
{
	//触发微信返回code码
	$url = createOauthUrlForCode($_G['siteurl'].'plugin.php?id=xj_event:wsq_pay&tid='.$tid);
	Header("Location: $url"); 
	exit();
}else
{
	//获取code码，以获取openid
	$code = $_GET['code'];
	$openid = getOpenId();
}




//获取access_token
if(file_exists($token = DISCUZ_ROOT.'./data/sysdata/cache_xj_event_token.php')) {
	@include $token;
}
if($_G['timestamp']-intval($token['timestamp'])>7100){
	$cul = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$appsecret ;
	$cx = get($cul);
	$token = json_decode($cx,true) ;
	$token['timestamp'] = $_G['timestamp'];
	writetocache('xj_event_token',getcachevars(array('token'=>$token)));
}
//获取jsapi_ticket
if(file_exists($jsapiticke = DISCUZ_ROOT.'./data/sysdata/cache_xj_event_jsapiticke.php')) {
	@include $jsapiticke;
}
if($_G['timestamp']-intval($jsapiticke['timestamp'])>7100){
	$cul = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token='.$token['access_token'].'&type=jsapi';
	$cx = get($cul);
	$jsapiticke = json_decode($cx,true) ;
	$jsapiticke['timestamp'] = $_G['timestamp'];
	writetocache('xj_event_jsapiticke',getcachevars(array('jsapiticke'=>$jsapiticke)));
}

$jsapi_ticket = $jsapiticke['ticket'];
$noncestr = getRandChar(12);
$timestamp = $_G['timestamp'];
//$url = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'];
$url = dhtmlspecialchars('http'.($_G['isHTTPS']?'s':'').'://'.$_SERVER['HTTP_HOST']).$_SERVER['REQUEST_URI'];
$string1 = "jsapi_ticket=$jsapi_ticket&noncestr=$noncestr&timestamp=$timestamp&url=$url";
$signature = sha1($string1);




//获取活动内容和报名内容
$items = DB::fetch_first("SELECT A.*,B.subject FROM ".DB::table('xj_event')." A,".DB::table('forum_thread')." B WHERE A.tid = $tid and A.tid=B.tid");
$setting = unserialize($items['setting']);
$pay_subject = $items['subject'];
$pay_price = $items['use_cost'];
$apply = DB::fetch_first("SELECT applyid,applynumber FROM ".DB::table('xj_eventapply')." WHERE tid = $tid and uid=".$_G['uid']);
if($setting['nodaibaoming']){
	$pay_number = $apply['applynumber'];
}else{
	$pay_number = DB::result_first("SELECT count(*) FROM ".DB::table('xj_eventapply')." WHERE tid = '$tid' and uid=".$_G['uid']);
}
//判断报名名额是否够，不够就不让支付
if($items['event_number']>0){
	$applycountnumber = DB::result_first("SELECT SUM(applynumber) FROM ".DB::table('xj_eventapply')." WHERE tid='$tid' and verify=1");
	if($pay_number > ($items['event_number']-$applycountnumber)){
		showmessage(lang('plugin/xj_event','baomrsym'));
		exit();
	}
}
$pay_totalprice = $pay_price * $pay_number;
//如果是多种报名
if($setting['cost']){
	if($setting['nodaibaoming']){
		$capply = DB::fetch_first("SELECT * FROM ".DB::table('xj_eventapply')." WHERE tid = '$tid' and uid=".$_G['uid']);
		$capply['ufielddata'] = unserialize($capply['ufielddata']);
		$price = 0;
		$paytext = '';
		foreach($setting['cost'] as $value){
			$paytext = $paytext.$value['cost_name'].' '.$capply['ufielddata']['cost'.$value['id']].' x &yen;'.$value['cost_price'].'<br>';
			$price = $price+$capply['ufielddata']['cost'.$value['id']]*$value['cost_price'];
		}
	}else{
		$capply = DB::fetch_all("SELECT * FROM ".DB::table('xj_eventapply')." WHERE tid = '$tid' and uid=".$_G['uid']);
		$price = 0;
		$paytext = '';
		foreach($capply as $value){
			$value['ufielddata'] = unserialize($value['ufielddata']);
			$paytext = $paytext.$setting['cost'][$value['ufielddata']['costclass']]['cost_name'].' 1 x &yen;'.$setting['cost'][$value['ufielddata']['costclass']]['cost_price'].'<br>';
			$price = $price + $setting['cost'][$value['ufielddata']['costclass']]['cost_price'];
		}
	}
	if(!$_G['charset']=='gbk'){
		$paytext = iconv('GBK','UTF-8',$paytext);
	}
	$pay_totalprice = $price;
}
if($_G['charset']=='gbk'){
	$pay_subject = iconv('GBK','UTF-8',$pay_subject);
}

//VIP折扣
if(file_exists(DISCUZ_ROOT.'./source/plugin/xj_event/module/vip/wsq_pay.php')) {
	@include 'module/vip/wsq_pay.php';
}





//prepay_id 获取，微信支付统一下单
$parameters = array();
$parameters["out_trade_no"] = getRandChar(20); //生成订单号
$parameters["body"] = mb_substr($pay_subject,0,32,'utf-8');//cutstr($pay_subject,32,'');  //商品描述
$parameters["total_fee"] = intval($pay_totalprice*100);   //总金额单位是分，不可以是小数
$parameters["notify_url"] = $_G['siteurl'].'source/plugin/xj_event/event_pay_wx_notify.php';  //异步回调地址
$parameters["trade_type"] = 'JSAPI';
$parameters["openid"] = $openid;
$parameters["appid"] = $appid;
$parameters["mch_id"] = $mch_id; //商户号
$parameters["spbill_create_ip"] = $_G['clientip'];  //客户端的IP地址
$parameters["nonce_str"] = createNoncestr();  //随机字符串
$parameters["sign"] = getSign($parameters);


//数据库生成支付记录
$paylog = array();
$paylog['applyid'] = $apply['applyid'];
$paylog['uid'] = $_G['uid'];
$paylog['tid'] = $tid;
$paylog['tradeno'] = $parameters["out_trade_no"];
$paylog['paytype'] = 'wxpay';
$paylog['subject'] = $items['subject'];
$paylog['price'] = $pay_price;
$paylog['buyer_email'] = $openid;
$paylog['total_fee'] = $pay_totalprice;
$paylog['create_time'] = $_G['timestamp'];
$paylog['paystate'] = 1;
DB::insert("xj_eventpay_log",$paylog);





/*
$mch_id = '1236481002'; //商户号
$nonce_str = getRandChar(15); //随机字符串
$body = '11111';  //商品描述
$out_trade_no = getRandChar(20);  //生成订单号
$total_fee = 1;   //总金额单位是分，不可以是小数
$spbill_create_ip = $_G['clientip'];  //客户端的IP地址
$notify_url = 'http://www.my8888.com/plugin.php?id=xj_event:test&action=notify';  //异步回调地址
$trade_type = 'JSAPI';

$stringA="appid=$appid&body=$body&mch_id=$mch_id&nonce_str=$nonce_str&notify_url=$notify_url&openid=$openid&out_trade_no=$out_trade_no&spbill_create_ip=$spbill_create_ip&total_fee=$total_fee&trade_type=$trade_type";
$stringA = $stringA."&key=qjqwertyuiopasdfghjklzxcvbnm2015";
$sign = strtoupper(md5($stringA));
$xmldata = "<xml>
   <appid>".$appid."</appid>
   <body>".$body."</body>
   <mch_id>".$mch_id."</mch_id>
   <nonce_str>".$nonce_str."</nonce_str>
   <notify_url>".$notify_url."</notify_url>
   <openid>$openid</openid>
   <out_trade_no>$out_trade_no</out_trade_no>
   <spbill_create_ip>$spbill_create_ip</spbill_create_ip>
   <total_fee>$total_fee</total_fee>
   <trade_type>$trade_type</trade_type>
   <sign>$sign</sign>
</xml>";
*/

$xmldata = arrayToXml($parameters);
$prepaystr = postXmlCurl($xmldata,"https://api.mch.weixin.qq.com/pay/unifiedorder");
$postObj = xmlToArray($prepaystr);

if($postObj['return_code'] == 'FAIL'){
	echo iconv('utf-8','gbk',$postObj['return_msg']);
	exit;
}

//paysign签名生成
$jsApiObj = array();
$jsApiObj['appId'] = $appid;
$jsApiObj['timeStamp'] = $timestamp;
$jsApiObj['nonceStr'] = createNoncestr();
$jsApiObj['package'] = "prepay_id=".$postObj['prepay_id'];
$jsApiObj['signType'] = "MD5";
$jsApiObj["paySign"] = getSign($jsApiObj);




?><!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=device-width; initial-scale=1.0;">
<title><?php echo lang('plugin/xj_event', 'zhifufy'); ?></title>
<script type="text/javascript" src="https://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
<script type="text/javascript">
wx.config({
    debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
    appId: '<?php echo $appid; ?>', // 必填，公众号的唯一标识
    timestamp: <?php echo $timestamp; ?>, // 必填，生成签名的时间戳
    nonceStr: '<?php echo $noncestr; ?>', // 必填，生成签名的随机串
    signature: '<?php echo $signature; ?>',// 必填，签名，见附录1
    jsApiList: ['chooseWXPay'] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
});

wx.ready(function(){
    // config信息验证后会执行ready方法，所有接口调用都必须在config接口获得结果之后，config是一个客户端的异步操作，所以如果需要在页面加载时就调用相关接口，则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口，则可以直接调用，不需要放在ready函数中。
});
wx.error(function(res){
    // config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
});



function wxpay(){

	wx.chooseWXPay({
		timestamp: <?php echo $jsApiObj['timeStamp']; ?>, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
		nonceStr: '<?php echo $jsApiObj['nonceStr']; ?>', // 支付签名随机串，不长于 32 位
		package: '<?php echo $jsApiObj['package'];?>', // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=***）
		signType: '<?php echo $jsApiObj['signType'];?>', // 签名方式，默认为SHA1使用新版支付需传入MD5
		paySign: '<?php echo $jsApiObj['paySign'];?>', // 支付签名
		success: function (res) {
			// 支付成功后的回调函数
			window.location.href="<?php echo $_G['siteurl'].'plugin.php?id=xj_event:wsqcenter&mod=join_success&tid='.$tid; ?>";
		}
	});

}

</script>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
</head>
<body style="background-color:#f0f0f0; margin:0px;">
<div>
    <div style=" padding:25px 20px 10px 20px; background-color:#FFF;line-height:40px;">
			<span style=" font-size:16px;"><?php echo lang('plugin/xj_event','huodongmingcheng'); ?> : <?php 
			if($_G['charset']=='gbk'){
				$pay_subject = iconv('UTF-8','GBK',$pay_subject);
			}
			echo $pay_subject; ?></span><br>
            <?php echo $paytext; ?>
            <?php echo lang('plugin/xj_event', 'renshu'); ?>:<span style="color:#7fad79;"><?php echo $pay_number; ?></span><br>
            <?php echo lang('plugin/xj_event', 'zongjia'); ?>:<span style="color:#7fad79;"><?php echo '&yen;'.$totalprice; ?></span><br>
            <?php echo lang('plugin/xj_event','youhuihou') ?>:<span style="color:#F30;"><?php echo '&yen;'.($totalprice-$youhuiprice); ?></span>
    </div>
	<div style="background:url(source/plugin/xj_event/images/line_pay.png) repeat-x; background-size:auto 20px; height:20px;"></div>
</div>
<div>
	<span style="margin:25px; display:block; line-height:48px; background-color:#00c800;-moz-border-radius: 3px; -webkit-border-radius: 3px; border-radius:3px; color:#FFF; text-align:center; font-size:16px;" onClick="wxpay();"><?php echo lang('plugin/xj_event', 'weixzf'); ?></span>
</div>

</body>
</html>




<?php

function std_class_object_to_array($stdclassobject)
{
    $_array = is_object($stdclassobject) ? get_object_vars($stdclassobject) : $stdclassobject;

    foreach ($_array as $key => $value) {
        $value = (is_array($value) || is_object($value)) ? std_class_object_to_array($value) : $value;
        $array[$key] = $value;
    }

    return $array;
}
function postxml($url,$data){
	$ch = curl_init($url); 
	curl_setopt($ch, CURLOPT_MUTE, 1); 
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); 
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); 
	curl_setopt($ch, CURLOPT_POST, 1); 
	curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml')); 
	curl_setopt($ch, CURLOPT_POSTFIELDS, "$data"); 
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
	$output = curl_exec($ch); 
	curl_close($ch); 
	return $output;
}
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 "curlError, error code:$error"."<br>"; 
		echo "<a href='http://curl.haxx.se/libcurl/c/libcurl-errors.html'>The reason for the error query</a></br>";
		curl_close($ch);
		return false;
	}
}

function get($url) {
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	# curl_setopt($ch, CURLOPT_HEADER, 1);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

	if (!curl_exec($ch)) {
		error_log(curl_error($ch));
		$data = '';
	} else {
		$data = curl_multi_getcontent($ch);
	}
	curl_close($ch);
	return $data;
}

function getRandChar($length){
   $str = null;
   $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
   $max = strlen($strPol)-1;
   for($i=0;$i<$length;$i++){
    $str.=$strPol[rand(0,$max)];//rand($min,$max)生成介于min和max两个数之间的一个随机整数
   }
  return $str;
}
//生成指定大小的字符串
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;
}
//生成签名
function getSign($Obj){
	global $apikey;
	foreach ($Obj as $k => $v)
	{
		$Parameters[$k] = $v;
	}
	//签名步骤一：按字典序排序参数
	ksort($Parameters);
	$String = formatBizQueryParaMap($Parameters, false);
	//echo '【string1】'.$String.'</br>';
	//签名步骤二：在string后加入KEY
	$String = $String."&key=$apikey";
	//echo "【string2】".$String."</br>";
	//签名步骤三：MD5加密
	$String = md5($String);
	//echo "【string3】 ".$String."</br>";
	//签名步骤四：所有字符转为大写
	$result_ = strtoupper($String);
	//echo "【result】 ".$result_."</br>";
	return $result_;
}

/**
 * 	作用：array转xml
 */
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; 
}

/**
 * 	作用：将xml转为array
 */
function xmlToArray($xml)
{		
	//将XML转为array        
	$array_data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);		
	return $array_data;
}

/**
 * 	作用：生成可以获得code的url
 */
function createOauthUrlForCode($redirectUrl)
{
	global $appid;
	$urlObj["appid"] = $appid;
	$urlObj["redirect_uri"] = urlencode($redirectUrl);
	$urlObj["response_type"] = "code";
	$urlObj["scope"] = "snsapi_base";
	$urlObj["state"] = "STATE"."#wechat_redirect";
	$bizString = formatBizQueryParaMap($urlObj, false);
	return "https://open.weixin.qq.com/connect/oauth2/authorize?".$bizString;
}

/**
 * 	作用：生成可以获得openid的url
 */
function createOauthUrlForOpenid()
{
	global $appid,$appsecret,$code;
	$urlObj["appid"] = $appid;
	$urlObj["secret"] = $appsecret;
	$urlObj["code"] = $code;
	$urlObj["grant_type"] = "authorization_code";
	$bizString = formatBizQueryParaMap($urlObj, false);
	return "https://api.weixin.qq.com/sns/oauth2/access_token?".$bizString;
}

/**
 * 	作用：通过curl向微信提交code，以获取openid
 */
function getOpenid()
{
	$url = createOauthUrlForOpenid();
	//初始化curl
	$ch = curl_init();
	//设置超时
	curl_setopt($ch, CURLOP_TIMEOUT, 30);   //超时时间
	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，结果以jason形式返回
	$res = curl_exec($ch);
	curl_close($ch);
	//取出openid
	$data = json_decode($res,true);
	$return = $data['openid'];
	return $return;
}

//删除微社区嵌入点
/*
$pluginid = 'xj_event';
require_once DISCUZ_ROOT.'./source/plugin/wechat/wechat.lib.class.php';
WeChatHook::delAPIHook($pluginid);
exit('fff');
*/

?>