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

//开始充值
chongzhi($data);
function chongzhi($data){
	//全局变量，函数内调用需要加global声明
	global $config;
	global $libaoconfig;
	try{
		$account = $data['account'];
		$money = $data['money'];
		$scale = $data['scale'];
		//拆分账号
		$list = explode("-",$account);
		$username = $list[0];
		$quid =  $list[1]; 
		$postdata = array();
		$postdata['account'] = $username;
		$postdata['serverid'] = $quid;
		$postdata['rmb'] = $money*$scale;
		//默认获取数组对象的第一个key键值
		$rid=key($libaoconfig);
		//根据充值金额算出购买的哪个礼包
		foreach ($libaoconfig as $key=>$value) {
			if($value[0]==$money){
				$rid = $key;
			}
		}
		$postdata['goodsid'] =  $rid;
		$postdata['agent'] = $config['agent'];
		$postdata['webid'] = $config['webid'];
		$postdata['key'] = $config['key'];
		$postdata['ip'] = $config['ip'];
		$postdata['pw'] = $config['pw'];

		//给url发送
		$url = "http://".$postdata['ip'].":8080/recharge?";
		$curl = curl_init();
		curl_setopt ( $curl, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt ( $curl, CURLOPT_HEADER, 0);
		curl_setopt ( $curl, CURLOPT_URL, $url.http_build_query($postdata));
		$output = curl_exec($curl);
		//关闭URL请求		
		curl_close($curl);
		//成功后返回
		$arr['code']=1;
		$msg = sprintf("账号[%s]成功充值金额%s元",$username,$money);
		outputSuccess($msg);		
	} 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);
}