<?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');
}


//调用核心类
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;
}
$appid = $wxset['open_appid'];
$apikey = $wxset['open_apikey'];
//APIKEY
$mch_id = $wxset['open_mch_id'];


//获取活动内容和报名内容
$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"] = 'MWEB';
$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);

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

if ($postObj['return_code'] == 'FAIL') {
	if ($_G['charset'] == 'gbk') {
		echo iconv('UTF-8', 'GBK', $postObj['return_msg']);
	} else {
		echo $postObj['return_msg'];
	}
	exit ;
}

$url = $_G['siteurl'].'plugin.php?id=xj_event:wsqcenter&mod=event_view&tid='.$tid;
$url = $postObj['mweb_url'].'&redirect_url='.urlencode(diconv($url, $_G['charset'], 'UTF-8'));;
Header("Location: $url");
exit();





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');
*/

?>