<?php
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('商户密钥不正确');
}

try {
    $account = $data['account'];
    $money = $data['money'];
	$alias = $data['alias'];
	$scale = $data['scale'];
    $ordernumber = $data['ordernumber'];
    //连接数据库
    $conn = @mysql_pconnect($db[0],$db[1],$db[2]);
    mysql_query("set names latin1");//如果角色名为中文，可能会出现中文乱码，导致充值失败，可尝试设置数据库编码为latin1、gb2312、gbk、ASCII、UTF8MB4或者utf8
    mysql_select_db($db[3], $conn);
    //拆分参数
    if(isset($data['param'])){
        $param = $data['param'];
        $array = explode("_",$param);
        $roleid = $array[1];//角色ID
        $gold = $array[2];//元宝数量
    }else{
        //模拟充值（根据账号查询角色ID）
		$gold = $money*$scale;//元宝=充值金额*充值比例
        $sql="SELECT `RoleID` FROM player WHERE `UserID`='$account'";
        $result = mysql_query($sql,$conn);
        if($result&&mysql_num_rows($result)>0){
            $row = mysql_fetch_array($result,MYSQL_NUM);
            $roleid = $row[0];
        }
    }
    //元宝的ID是222222
	$realmoney='222222-'.$gold.'-0;';
    $it0=explode(';',rtrim($realmoney,';'));
    $it='';
    foreach($it0 as $it1){
        $it2=explode('-',$it1);
        $t=$roleid.'｜充值｜元宝｜'.$ordernumber;
        //检测是否存在
        $sql1="SELECT `a1` FROM paylog WHERE `a2`='$t'";
        $result1 = mysql_query($sql1,$conn);
        if($result1&&mysql_num_rows($result1)>0){
            echo '订单已存在';
            exit;
        }
        $it1=item($it2[0]);
        $it3=str_pad(itemnum($it2[1],$it2[2]),2,'0',STR_PAD_LEFT);
        $it2=item($it2[1]);
        mysql_query("INSERT INTO `paylog` (`order_id`,`role_id`,`title`, `description`, `num`) VALUES ('$ordernumber','$roleid','Recharge Gold','$realmoney','$gold')");
        $it='52'.$it3.'08'.$it1.'10'.$it2.'2801'.$it;
    }
    $it1='3018'.$it;
    $result = mysql_query("INSERT INTO `email` (`roleID`, `emailIndex`, `datas`) VALUES ('$roleid',CONCAT('00',HEX(UNIX_TIMESTAMP()),'43820C'), CAST(UNHEX('$it1') AS CHAR))");
    if($result){
		$text = $gold>=10000?($gold/10000).'万':$gold;
        $msg = sprintf("账号[%s]成功充值金额%s元，获得%s：%s个",$account,$money,$alias,$text);
		outputSuccess($msg);
    }else{
        outputError("账号[".$account."]不存在角色");
    }
    mysql_close($conn);
} 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);
}

function so8($a,$b,$c,$d){
    $so8 = @mysql_pconnect($a,$b,$c);
    mysql_query("set names utf8"); 
    mysql_select_db($d, $so8);
    return $so8;
}
function c86($a){return intval(floor($a/128));}
function b86($a,$b){return $a%128+$b;}
function item($a){
	if($a>=128){
        $a1=c86($a);
        $a0=b86($a,128);
        if($a1>=128){$a2=c86($a1);$a1=b86($a1,128);}else{$a2='';}
        if($a2>=128){$a3=c86($a2);$a2=b86($a2,128);}else{$a3='';}
        if($a3>=128){$a4=c86($a3);$a3=b86($a3,128);}else{$a4='';}
	}else{
        $a3='';$a4='';$a2='';$a1=$a%128;$a0='';
    }
	$b='';
	if($a4!=''){$b=pack('c', $a4);}
	if($a3!=''){$b=pack('c', $a3).$b;}
	if($a2!=''){$b=pack('c', $a2).$b;}
	if($a1!=''){$b=pack('c', $a1).$b;}
	if($a0!=''){$b=pack('c', $a0).$b;}
	return bin2hex($b);
}
function itemnum($a,$b){
	if($a>=128){
        $aa=7+$b;
        $a1=c86($a);
        $a0=b86($a,128);
        if($a1>=128){$a2=c86($a1);$a1=b86($a1,128);$aa=8+$b;}else{$a2='';}
        if($a2>=128){$a3=c86($a2);$a2=b86($a2,128);$aa=9+$b;}else{$a3='';}
        if($a3>=128){$a4=c86($a3);$a3=b86($a3,128);$aa=10+$b;}else{$a4='';}
	}else{
        $aa=6+$b;
    }
	return dechex($aa);
}
?>