<?php
/*
 * 元宝支付 https://pay.zy13.net
 * Date: 2020/12/10
 * Time: 15:38
 * 说明：
 * 以下代码只是为了方便商户测试而提供的样例代码，商户可以根据自己网站的需要，按照技术文档编写,并非一定要使用该代码。
 * 该代码仅供学习和研究接口使用，只是提供一个参考，最终解释权归美奇软件开发工作室所有。
 * 严禁一切钓鱼、色情、赌博、私彩及违反国家法律法规等使用。
 * 注意：
 * UTF-8编码不要在记事本下编辑，否则会出现一些奇葩的问题，正确方法应在开发工具里打开编辑
 */
ini_set("error_reporting","E_ALL & ~E_NOTICE");
header('Content-Type:application/json; charset=utf-8');
require "config.php";
require "Des.php";
///////////////////////////////////////////////
//下面代码基本不需要修改
if (empty($_POST)) $_POST = $_GET;  //如果为GET方式访问
if(version_compare(PHP_VERSION,'5.4.0','<')){
	outputError('PHP版本要求大于5.4.0');
}
if(!isset($_POST['appid'])){
	outputError('参数非法');
}
//验证商户号
if($_POST['appid']!=$appid){
	outputError('商户编号不正确');
}
if (!function_exists('openssl_encrypt')){
	outputError('请开启php.ini的openssl扩展');
}
//解密接口参数
$des = new Des();
$parameter=$_POST['parameter'];
$decode=$des->decrypt($parameter,$deskey);
if(empty($decode)){
	outputError('算法密钥不正确');
}
parse_str($decode, $data);
//验证商户密钥
if($appkey!=$data['appkey']){
	outputError('商户密钥不正确');
}
//开始充值
if (version_compare(PHP_VERSION, '7.0.0') >= 0) {
	//php7.0以上版本
    chongzhi_php7($data);
}else{
	//php5.4~5.6版本
	chongzhi_php5($data);
}

function chongzhi_php5($data){
	//全局变量，函数内调用需要加global声明
	global $db;
	try{
		//游戏充值代码
		$account = $data['account'];
		$accounta = explode("_",$account);
		$gameprops = $accounta[0];
		$serverid = $accounta[1];
		$actorname = $accounta[2];
		$alias = $data['alias'];
		$scale = $data['scale'];
		$money = $data['money'];
		$gold=$money*$scale;//元宝=充值金额*充值比例
		//根据分区ID，自动选择数据库
		if($db[$serverid]){
			$dbgame = $db[$serverid];
		}else{
			$dbgame = $db[1];
		}
		$conn = @mysql_connect(HOST,USER,PASS,PORT) or die("数据库链接失败!");
		mysql_query("set names 'utf8'");		
		mysql_select_db($dbgame,$conn);
		$result=mysql_query("SELECT accountname,actorid FROM actors WHERE accountname = '$actorname' or actorname = '$actorname'");//SQL语句
    	if($result&&mysql_num_rows($result)>0){
    		$row = mysql_fetch_array($result);
    		$accountname=$row[0];
    		$actorid=$row[1];
    		if($gameprops=="元宝"){
        		$sql = sprintf("insert into feecallback(serverid,openid,itemid,actor_id) values ('%s','%s','%s',%s);",$serverid,$accountname,$gold,$actorid);
        		if(mysql_query($sql)){
            		$text = $gold>=10000?($gold/10000).'万':$gold;
            		$msg = sprintf("账号%s成功充值金额%s元，获得%s：%s个",$actorname,$money,$alias,$text);
            		outputSuccess($msg);
        		}else{
        			outputError(sprintf("账号%s充值%s失败",$actorname,$alias));
        		}
    		}else if($gameprops=="元宝月卡"){
    		    $cmd = "buymonthcard";
    		    $sql = sprintf("INSERT INTO gmcmd(serverid,cmd,param1,param2,param3,param4,param5) VALUES ('%s','%s','%s','0','0','0','0');",$serverid,$cmd,$actorid);
    		    if(mysql_query($sql)){
            		outputSuccess(sprintf("账号%s购买[元宝月卡]成功",$actorname));
        		}else{
        		    outputError(sprintf("账号%s购买[元宝月卡]失败",$actorname));
        		}
    		}else if($gameprops=="特权月卡"){
    		    $cmd = "buyprivilegemonthcard";
    		    $sql = sprintf("INSERT INTO gmcmd(serverid,cmd,param1,param2,param3,param4,param5) VALUES ('%s','%s','%s','0','0','0','0');",$serverid,$cmd,$actorid);
    		    if(mysql_query($sql)){
            		outputSuccess(sprintf("账号%s购买[特权月卡]成功",$actorname));
        		}else{
        		    outputError(sprintf("账号%s购买[特权月卡]失败",$actorname));
        		}
    		}
    	}else{
    		outputError("充值失败，帐号".$actorname."还没有角色");
    	}
		mysql_close($conn);	
	} catch (Exception $e) {
		outputError('充值异常，Error：'.$e->getMessage());
	}
}

function chongzhi_php7($data){
	global $db;
	try{
		$account = $data['account'];
		$accounta = explode("_",$account);
		$gameprops = $accounta[0];
		$serverid = $accounta[1];
		$actorname = $accounta[2];
		$alias = $data['alias'];
		$scale = $data['scale'];
		$money = $data['money'];
		$gold=$money*$scale;	
		if($db[$serverid]){
			$dbgame = $db[$serverid];
		}else{
			$dbgame = $db[1];
		}
		
		$mysqli = new mysqli(HOST,USER,PASS,$dbgame,PORT);
		if(!$mysqli){
			outputError("数据库连接失败");	
		}
		$mysqli->set_charset('utf8');
		$query = $mysqli->prepare("SELECT accountname,actorid FROM actors WHERE accountname = ? or actorname = ?");
		$query->bind_param('ss', $actorname, $actorname);
		$query->execute();			
		$result = $query->get_result();	
		if(mysqli_num_rows($result)>0){
			$row = mysqli_fetch_array($result);			
			$accountname=$row["accountname"];
    		$actorid=$row["actorid"];
    		if($gameprops=="元宝"){
				$query1 = $mysqli->prepare("insert into `feecallback` (`serverid`,`openid`,`itemid`,`actor_id`) values (?,?,?,?)");
				$query1->bind_param('ssss', $serverid,$accountname,$gold,$actorid);
				if($query1->execute()==true){
            		$text = $gold>=10000?($gold/10000).'万':$gold;
            		$msg = sprintf("账号%s成功充值金额%s元，获得%s：%s个",$actorname,$money,$alias,$text);
            		outputSuccess($msg);
        		}else{
        			outputError(sprintf("账号%s充值%s失败",$actorname,$alias));
        		}
    		}else if($gameprops=="元宝月卡"){
    		    $cmd = "buymonthcard";
				$query1 = $mysqli->prepare("INSERT INTO gmcmd(serverid,cmd,param1,param2,param3,param4,param5) VALUES (?,?,?,'0','0','0','0');");
				$query1->bind_param('sss', $serverid,$cmd,$actorid);
    		    if($query1->execute()==true){
            		outputSuccess(sprintf("账号%s购买[元宝月卡]成功",$actorname));
        		}else{
        		    outputError(sprintf("账号%s购买[元宝月卡]失败",$actorname));
        		}
    		}else if($gameprops=="特权月卡"){
    		    $cmd = "buyprivilegemonthcard";
				$query1 = $mysqli->prepare("INSERT INTO gmcmd(serverid,cmd,param1,param2,param3,param4,param5) VALUES (?,?,?,'0','0','0','0');");
				$query1->bind_param('sss', $serverid,$cmd,$actorid);
				if($query1->execute()==true){
            		outputSuccess(sprintf("账号%s购买[特权月卡]成功",$actorname));
        		}else{
        		    outputError(sprintf("账号%s购买[特权月卡]失败",$actorname));
        		}
    		}
    	}else{
    		outputError("充值失败，帐号".$actorname."还没有角色");
    	}
		$mysqli->close();
	} catch (Exception $e) {
		outputError('充值异常，Error：'.$e->getMessage());
	}
}

function outputError($msg){
	$arr=array('code'=>0,'msg'=>$msg);
	echo json_encode($arr, JSON_UNESCAPED_UNICODE);
	exit;
}

function outputSuccess($msg){
	$arr=array('code'=>1,'msg'=>$msg);
	echo json_encode($arr, JSON_UNESCAPED_UNICODE);
	exit;
}

/** 
 * 打印日志
 * $msg 日志内容
 */
function printLog($msg) {
	if (!is_dir('log')){
		mkdir('log',0777,true);
	}
	$path="log/".date('Y-m-d').".log";
	file_put_contents($path, "【" . date('Y-m-d H:i:s') . "】" . $msg . "\r\n\r\n", FILE_APPEND);
}