<?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(strpos($_SERVER["HTTP_USER_AGENT"],'Appbyme')>0){
	$Appbyme = true;
}
if(strpos($_SERVER["HTTP_USER_AGENT"],'MAGAPP')>0){
	$magapp = true;
}
if(strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger')>0){
	$isWeiXin = true;
}
if(strpos($_SERVER['HTTP_USER_AGENT'], 'QianFan')>0){
	$QianFan = true;	
}




if(!$_G['uid']) {
	showmessage('not_loggedin', NULL, array(), array('login' => 1));
}


//调用核心类
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']); //总价格
//判断APP优惠
if($Appbyme || $magapp){
	$items = DB::fetch_first("SELECT * FROM ".DB::table('xj_event')." WHERE tid = $tid");
	$setting = unserialize($items['setting']);
	if($setting['app_benefit']>0){
		$youhuiprice = $youhuiprice + $setting['app_benefit'];
	}
}
if(($totalprice-$youhuiprice)<=0 && $tid>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','baomingchenggong'),$_G['siteurl']."plugin.php?id=xj_event:wsqcenter&mod=event_view&tid=$tid");
}
	






if($_GET['action'] == 'paysucceed'){
	showmessage(lang('plugin/xj_event', 'hdfyzfwc'),'plugin.php?id=xj_event:event_center');
}
//如果是微信支付跳转
if($_GET['bank_type'] == 'wxpay'){
	header('Location: plugin.php?id=xj_event:wxpay&applyid='.intval($_GET['applyid']));
	exit();
}
//如果是积分支付跳转
if($_GET['bank_type'] == 'jfpay'){
	header('Location: plugin.php?id=xj_event:jfpay&applyid='.intval($_GET['applyid']));
	exit();
}
//如果是马甲支付跳转
/*
if($magapp){
	$tid = intval($_GET['tid']);
	$item = DB::fetch_first("SELECT applyid,applynumber FROM ".DB::table('xj_eventapply')." WHERE tid = '$tid' and uid=".$_G['uid']);
	header('Location: plugin.php?id=xj_event:magapp_pay&applyid='.$item['applyid']);
	exit();
}
*/



//微信支付的配置
if(file_exists($xj_event_wxset = DISCUZ_ROOT.'./data/sysdata/cache_xj_event_wxset.php')) {
	@include $xj_event_wxset;
}




if($_GET['bank_type'] === '0'){
	$_GET['bank_type'] = 'tenpay';
}

if(!$_GET['bank_type']){
	$tid = intval($_GET['tid']);
	$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");
	$eventnumber = $items['event_number'];
	$setting = unserialize($items['setting']);
	$subject = $items['subject'];
	$use_cost = $items['use_cost'];
	$item = DB::fetch_first("SELECT applyid,applynumber FROM ".DB::table('xj_eventapply')." WHERE tid = '$tid' and uid=".$_G['uid']);
	//报名方式不同，计算人数
	if($setting['nodaibaoming']){
		$applynumber = $item['applynumber'];
	}else{
		$applynumber = DB::result_first("SELECT count(*) FROM ".DB::table('xj_eventapply')." WHERE tid = '$tid' and uid=".$_G['uid']);
	}
	//判断报名名额是否够，不够就不让支付
	if($eventnumber>0){
		$applycountnumber = DB::result_first("SELECT SUM(applynumber) FROM ".DB::table('xj_eventapply')." WHERE tid='$tid' and verify=1");
		if($applynumber > ($eventnumber-$applycountnumber)){
			showmessage(lang('plugin/xj_event','baomrsym'));
			exit();
		}
	}	
	$totalprice = $use_cost*$applynumber;
	$applyid = $item['applyid'];
	
	$apply = DB::fetch_first("SELECT * FROM ".DB::table('xj_eventapply')." WHERE first=1 AND tid = '$tid' AND uid=".$_G['uid']);
	$apply['ufielddata'] = unserialize($apply['ufielddata']);
	//VIP折扣
	$vipgroup = unserialize($_G['cache']['plugin']['xj_event']['vipgroupid']);
	
	//优惠计算
	$youhuiprice = $eventcore->GetYouHui($tid,$_G['uid']);
	

	
	
	include template('xj_event:event_pay');
}else{
	if(!submitcheck('paysubmit')){
		showmessage('submit_invalid');	
	}
	$applyid = intval($_GET['applyid']);
	$uid = intval($_G['uid']);
	$item = DB::fetch_first("SELECT tid,applyid,applynumber FROM ".DB::table('xj_eventapply')." WHERE applyid = $applyid and uid=".$_G['uid']);
	$tid = $item['tid'];
	$applyid = $item['applyid'];
	$applynumber = $item['applynumber'];
	
	$item = DB::fetch_first("SELECT A.use_cost,A.setting,B.subject FROM ".DB::table('xj_event')." A,".DB::table('forum_thread')." B WHERE A.tid = '$tid' and A.tid=B.tid");
	$setting = unserialize($item['setting']);
	//报名方式不同，计算人数
	if($setting['nodaibaoming']){

	}else{
		$applynumber = DB::result_first("SELECT count(*) FROM ".DB::table('xj_eventapply')." WHERE tid = '$tid' and uid=".$_G['uid']);
	}
	$subject = $item['subject'];
	$use_cost = $item['use_cost'];
	$price = number_format($use_cost*$applynumber,2,'.','');
	//$paytype = addslashes($_GET['bank_type']);
	$paytype = is_numeric($_GET['bank_type']) ? 'tenpay' : $_GET['bank_type'];
	$create_time = $_G['timestamp'];
	if(empty($uid) || empty($tid) || empty($price)){
		exit('Access Denied');
	}
	
	//如果是多种报名
	if($setting['cost']){
		if($setting['nodaibaoming']){
			$apply = DB::fetch_first("SELECT * FROM ".DB::table('xj_eventapply')." WHERE tid = '$tid' and uid=".$_G['uid']);
			$apply['ufielddata'] = unserialize($apply['ufielddata']);
			$price = 0;
			foreach($setting['cost'] as $value){
				$price = $price+$apply['ufielddata']['cost'.$value['id']]*$value['cost_price'];
			}
		}else{
			$apply = DB::fetch_all("SELECT * FROM ".DB::table('xj_eventapply')." WHERE tid = '$tid' and uid=".$_G['uid']);
			$price = 0;
			foreach($apply as $value){
				$value['ufielddata'] = unserialize($value['ufielddata']);
				$price = $price + $setting['cost'][$value['ufielddata']['costclass']]['cost_price'];
			}
		}
	}
	//VIP折扣
	if(file_exists(DISCUZ_ROOT.'./source/plugin/xj_event/module/vip/event_pay.php')) {
		@include 'module/vip/event_pay.php';
	}

	if($setting['app_benefit']>0 && $Appbyme){
		$price = $price - $setting['app_benefit'];
	}


	
	$item = DB::fetch_first("SELECT orderid FROM ".DB::table('xj_eventpay_log')." WHERE applyid = $applyid");
	$orderid = dgmdate(TIMESTAMP, 'YmdHis').random(18);  //创建支付订单号
	DB::query("INSERT INTO ".DB::table('xj_eventpay_log')." 
	(applyid, uid, tid, orderid, paytype, subject, price, total_fee, create_time) 
	VALUES 
	('$applyid', '$uid', '$tid', '$orderid', '$paytype', '$subject', '$use_cost', '$price', '$create_time')");
}


if($paytype=='alipay'){
	if($_G['mobile'] && $_G['cache']['plugin']['xj_event']['alipaywap']){
		list($ec_contract, $ec_securitycode, $ec_partner, $ec_creditdirectpay) = explode("\t", authcode($_G['setting']['ec_contract'], 'DECODE', $_G['config']['security']['authkey']));
		$alipay_config['partner']		= $ec_partner;
		$alipay_config['seller_id']	= $alipay_config['partner'];
		$alipay_config['key']			= $ec_securitycode;
		$alipay_config['notify_url'] = $_G['siteurl'].'source/plugin/xj_event/event_pay_notify.php';
		$alipay_config['return_url'] = $_G['siteurl'].'source/plugin/xj_event/event_pay_notify.php';
		$alipay_config['sign_type']    = strtoupper('MD5');
		//字符编码格式 目前支持utf-8
		$alipay_config['input_charset']= strtolower('utf-8');
		//ca证书路径地址，用于curl中ssl校验
		//请保证cacert.pem文件在当前文件夹目录中
		$alipay_config['cacert']    = getcwd().'\\cacert.pem';
		//访问模式,根据自己的服务器是否支持ssl访问，若支持请选择https；若不支持请选择http
		$alipay_config['transport']    = 'http';
		$alipay_config['payment_type'] = "1";
		$alipay_config['service'] = "alipay.wap.create.direct.pay.by.user";
		require_once("source/plugin/xj_event/include/alipay_submit.class.php");
		
        //商户订单号，商户网站订单系统中唯一订单号，必填
        $out_trade_no = $orderid;

        //订单名称，必填
		//$subject = $_G['setting']['bbname'].' '.$_G['member']['username'].' '.$subject.' '.lang('plugin/xj_event', 'huodongbm');
		if($_G['charset']=='gbk'){
			if(mb_strlen($subject,'gbk')>10){
				$subject = mb_substr($subject,0,10,'gbk');
			}
        	$subject = iconv('gbk','utf-8',$subject);
		}else{
			if(mb_strlen($subject,'utf-8')>10){
				$subject = mb_substr($subject,0,10,'utf-8');
			}
		}
		
		

        //付款金额，必填
        $total_fee = $price;

        //收银台页面上，商品展示的超链接，必填
        $show_url = $_G['siteurl'].'forum.php?mod=viewthread&tid=$tid';

        //商品描述，可空
        $body = '';
		$parameter = array(
				"service"       => $alipay_config['service'],
				"partner"       => $alipay_config['partner'],
				"seller_id"  => $alipay_config['seller_id'],
				"payment_type"	=> $alipay_config['payment_type'],
				"notify_url"	=> $alipay_config['notify_url'],
				"return_url"	=> $alipay_config['return_url'],
				"_input_charset"	=> trim(strtolower($alipay_config['input_charset'])),
				"out_trade_no"	=> $out_trade_no,
				"subject"	=> $subject,
				"total_fee"	=> $total_fee,
				"show_url"	=> $show_url,
				"body"	=> $body,
				//其他业务参数根据在线开发文档，添加参数.文档地址:https://doc.open.alipay.com/doc2/detail.htm?spm=a219a.7629140.0.0.2Z6TSk&treeId=60&articleId=103693&docType=1
				
		);
		//print_r($alipay_config);
		//exit();
		$alipaySubmit = new AlipaySubmit($alipay_config);
		$html_text = $alipaySubmit->buildRequestForm($parameter,"get", lang('plugin/xj_event', 'queren'));
		echo $html_text;
		exit();
	}else{
		list($ec_contract, $ec_securitycode, $ec_partner, $ec_creditdirectpay) = explode("\t", authcode($_G['setting']['ec_contract'], 'DECODE', $_G['config']['security']['authkey']));
		define('DISCUZ_PARTNER', $ec_partner);
		define('DISCUZ_SECURITYCODE', $ec_securitycode);
		define('DISCUZ_DIRECTPAY', $ec_creditdirectpay);
		define('STATUS_SELLER_SEND', 4);
		define('STATUS_WAIT_BUYER', 5);
		define('STATUS_TRADE_SUCCESS', 7);
		define('STATUS_REFUND_CLOSE', 17);
		
		$args = array(
		  'subject'     => $_G['setting']['bbname'].' '.$_G['member']['username'].' '.$subject.' '.lang('plugin/xj_event', 'huodongbm'),
		  'body'      => lang('plugin/xj_event', 'hdbmfk').' '.$price.lang('plugin/xj_event', 'yuan').$_G['clientip'],
		  'service'     => 'trade_create_by_buyer',
		  'partner'     => DISCUZ_PARTNER,
		  'notify_url'    => $_G['siteurl'].'source/plugin/xj_event/event_pay_notify.php',
		  'return_url'    => $_G['siteurl'].'source/plugin/xj_event/event_pay_notify.php',
		  'show_url'    => $_G['siteurl'],
		  '_input_charset'  => CHARSET,
		  'out_trade_no'    => $orderid,
		  'price'     => $price,
		  'quantity'    => 1,
		  'seller_email'    => $_G['setting']['ec_account'],
		);
		if(DISCUZ_DIRECTPAY) {
		  $args['service'] = 'create_direct_pay_by_user';
		  $args['payment_type'] = '1';
		} else {
		  $args['logistics_type'] = 'EXPRESS';
		  $args['logistics_fee'] = 0;
		  $args['logistics_payment'] = 'SELLER_PAY';
		  $args['payment_type'] = 1;
		}
		ksort($args);
		$urlstr = $sign = '';
		foreach($args as $key => $val) {
			$sign .= '&'.$key.'='.$val;
			$urlstr .= $key.'='.rawurlencode($val).'&';
		}
		$sign = substr($sign, 1);
		$sign = md5($sign.DISCUZ_SECURITYCODE);
		header('Location: https://www.alipay.com/cooperate/gateway.do?'.$urlstr.'sign='.$sign.'&sign_type=MD5');
	}
}elseif($paytype=='tenpay'){
	if($_GET['bank_type'] == 'tenpay'){
		$_GET['bank_type'] = '0';
	}
	$bank = $_GET['bank_type'];

	define('DISCUZ_PARTNER', $_G['setting']['ec_tenpay_bargainor']);
	define('DISCUZ_SECURITYCODE', $_G['setting']['ec_tenpay_key']);
	define('DISCUZ_AGENTID', '1204737401');
	
	define('DISCUZ_TENPAY_OPENTRANS_CHNID', $_G['setting']['ec_tenpay_opentrans_chnid']);
	define('DISCUZ_TENPAY_OPENTRANS_KEY', $_G['setting']['ec_tenpay_opentrans_key']);
	
	define('STATUS_SELLER_SEND', 3);
	define('STATUS_WAIT_BUYER', 4);
	define('STATUS_TRADE_SUCCESS', 5);
	define('STATUS_REFUND_CLOSE', 9);
	include_once DISCUZ_ROOT . './source/class/class_chinese.php';
	include_once DISCUZ_ROOT . './api/trade/api_tenpay.php';
	$date = dgmdate(TIMESTAMP, 'YmdHis');
	$suffix = dgmdate(TIMESTAMP, 'His').rand(1000, 9999);
	$transaction_id = DISCUZ_PARTNER.$date.$suffix;
	$chinese = new Chinese(strtoupper(CHARSET), 'GBK');
	
	$subject = $chinese->Convert($_G['setting']['bbname'].' - '.$_G['member']['username'].' - '.$subject.' - '.lang('plugin/xj_event', 'huodongbm'));
	$subject = cutstr($subject,32,'');
	
	$reqHandler = new RequestHandler();
	$reqHandler->setGateURL("https://gw.tenpay.com/gateway/pay.htm");
	
	$reqHandler->init();
	$reqHandler->setKey(DISCUZ_SECURITYCODE);
	
	$reqHandler->setParameter("partner", DISCUZ_PARTNER);
	$reqHandler->setParameter("out_trade_no", $orderid);
	$reqHandler->setParameter("total_fee", $price * 100);
	$reqHandler->setParameter("return_url", $_G['siteurl'].'plugin.php?id=xj_event:event_pay&action=paysucceed');
	$reqHandler->setParameter("notify_url", $_G['siteurl'].'source/plugin/xj_event/event_pay_notify.php');
	$reqHandler->setParameter("body", $subject);
	$reqHandler->setParameter("bank_type", $bank);

	$reqHandler->setParameter("spbill_create_ip", $_G['clientip']);
	$reqHandler->setParameter("fee_type", "1");
	$reqHandler->setParameter("subject", $subject);

	$reqHandler->setParameter("sign_type", "MD5");
	$reqHandler->setParameter("service_version", "1.0");
	$reqHandler->setParameter("input_charset", "GBK");
	$reqHandler->setParameter("sign_key_index", "1");

	$reqHandler->setParameter("attach", "tenpay");
	$reqHandler->setParameter("time_start", $date);
	$reqHandler->setParameter("trade_mode","1");
	$reqHandler->setParameter("trans_type","1");
	$reqHandler->setParameter("agentid", DISCUZ_AGENTID);
	$reqHandler->setParameter("agent_type","2");

	$reqUrl = $reqHandler->getRequestURL();
	
	header('Location: '.$reqUrl);
}




?>