<?php
namespace app\pay\controller;
use think\Db;

class Index extends \think\Controller {
	// +----------------------------------------------------------------------
    // | 支付配置 开始
	// | 技术支持：三七云(37yz.com)
    // +----------------------------------------------------------------------
    //商户ID（商户编号）
	private $appid;
	//商户密钥
	private $appkey;
	//异步通知地址
	private $notify_url;
	//页面跳转同步通知页面
	private $return_url;
	//聚合支付POST提交地址
	private $payurl;
	// +----------------------------------------------------------------------
    // | 支付配置 结束 
    // +----------------------------------------------------------------------
    private $sign;
    public function _initialize(){
        //返回数组配置下的某一项属性
        $this->appid = config('yuanbaopay.appid');
        $this->appkey = config('yuanbaopay.appkey');
        $this->payurl = config('yuanbaopay.payurl');
        $this->notify_url='http://'.$_SERVER['HTTP_HOST'].'/pay/Index/notify';
        $this->return_url='http://'.$_SERVER['HTTP_HOST'].'/pay/Success/page';
        $this->sign = md5($_SERVER['HTTP_HOST']."+QQ:79899080");
	}
	public function index() {
	    $serverList = getGameServerList();
    	$this->assign("serverList", $serverList);
			$guid=\think\Session::get("guid");
			if(empty($guid)){
				$this->error(" 获取角色信息失败");
			}
			$serverid=\think\Session::get("serverid");
			if(empty($serverid)){
				$this->error(" 获取游戏区ID失败");
			}
	        //读取物品ID
    		// $json_string = file_get_contents('ItemTable.json');
    		// $line = json_decode($json_string, true);
    		$account=\think\Session::get("account");
    		$user = \think\Db::name("user")->field("Id,account,rmb")->where("account",$account)->find();
    		$taocan = CacheData("taocan",function() {
    			return \think\Db::name("shopconfig")->field(true)->where(["state" => 1])->select();
    		},86400);
    		//查询累计充值
    		$leichong = CacheData("leichong-".$account,function() {
    			return \think\Db::name("leichongconfig")->field(true)->where(["state" => 1])->select();
    		},300);
    		//查询每日累充
    		$meirilc = CacheData("meirilc-".$account,function() {
    			return \think\Db::name("meirilcconfig")->field(true)->where(["state" => 1])->select();
    		},300);
    		//查询每日福利
    		$meirifl = CacheData("meirifl-".$account,function() {
    			return \think\Db::name("shopconfig")->field(true)->where(["state" => 1])->where(["type" => "每日礼包"])->select();
    		},300);
    		$moneyList = pay_kk("", true);
    		$this->assign("moneyList", $moneyList);
			$this->assign("guid", $guid);
			$this->assign("serverid", $serverid);
    		$this->assign("account", $account);
    		$this->assign("accountid", $user["Id"]);
    		$this->assign("rmb",$user["rmb"]);
    		$this->assign("taocan", $taocan);
    		$this->assign("token", "sha1");
    		$this->assign("leichong", $leichong);
    		$this->assign("meirifl", $meirifl);
    		$this->assign("meirilc", $meirilc);
    		return $this->fetch();
	}
	/**
	 * 用于本地接口回调
	 * 解决curl请求本地超时问题（曲线救国之路）
	 */
	public function api(){
	    //接口验证，防止非法访问
	    $request = \think\Request::instance()->post();
	    if(!isset($request["sign"])) {
	        printLog("非法访问");
		    return  json_encode(["code"=>0,"msg"=>"非法访问"]);
		}
		if($request["sign"]!=$this->sign) {
		    return  json_encode(["code"=>0,"msg"=>"签名不正确"]);
		}
		$table = $request["table"];
	    $serverid = $request["serverid"];
	    $playerid = $request["playerid"];
	    $productid = $request["productid"];
	    $tool = new \app\pay\controller\Tool();
		//获取服务器信息
		$gameServer= $tool->getGameServer($serverid);
		//查询商品
		$array = ["table"=>$table,"id"=>$productid];
		$items = CacheData($table."-".$productid,function() use($array){
		    return \think\Db::name($array['table'])->field(true)->where("Id" ,$array['id'])->find();
	    },300);
		$result = $tool->sendItems($gameServer["server"], $playerid, $gameServer["ip"], $gameServer["gmport"], $items);
	    if($result){
	        return  json_encode(["code"=>1,"msg"=>"发送成功"]);
	    }else{
	        return  json_encode(["code"=>0,"msg"=>"发送失败"]);
	    }
	}
	/**
	 * 用于页面提示
	 */
	public function msg($code,$msg) {
	    //页面携带参数跳转
	    $url=url("@pay/Success/msg")."?code={$code}&msg={$msg}";
	    header('Location: '.$url);
	    exit;
	}
	// 特权领取
	public function tequan() {
		$request = \think\Request::instance()->post();
		//获取上游传递的参数
		$accountid = $request["accountid"];//账号库ID
		$serverid = $request["serverid"];//区服ID
		$productid = $request["productid"];//礼包ID
		$tool = new \app\pay\controller\Tool();
		//获取服务器信息
		$gameServer= $tool->getGameServer($serverid);
		//获取角色信息
		$account = $request["account"];//账号
		$playerid = $request["guid"];//角色ID
		$roleid = $tool->getRole($gameServer["surface"],$accountid,$playerid);
		if(empty($roleid )){
		    return  ["code"=>2,"msg"=>"查询角色失败"];
		}
		//查询礼品
		$items = CacheData("shopconfig-".$productid,function() use($productid){
		    return \think\Db::name("shopconfig")->field(true)->where("Id" , $productid)->find();
	    },300);
		try{
			$tequan = \think\Db::name("tequan")->where(["account" => $accountid, "server" => $serverid,"type" => $productid])->find();
			if ($tequan) {
				$timedate =  $tequan["time"]+60*60*24;
				$today = strtotime(date("Y-m-d"),time());
				if ($timedate > time()) {
					return json(["code" => 0, "msg" =>  "今日已经领取完毕"]);
				}
				//调用本地接口发送礼品
    			$apiurl='http://'.$_SERVER['HTTP_HOST'].'/pay/Index/api';
    			$postdata=[
					"table" => "shopconfig",
    				"serverid" => $gameServer["server"],
    				"playerid" => $playerid,
    			    "productid" => $productid,
    			    "sign" => $this->sign
    			];
    			$apiHtml=curl_post($apiurl,$postdata);
    			$apiResult=json_decode($apiHtml,true);
                if($apiResult['code']==1){
    				$data = ["time" => $today];
    				\think\Db::name("tequan")->where(["account" => $accountid, "server" => $serverid,"role" => $playerid,"type" => $productid])->update($data);
    				// 直接返回成功 参数
    				return json(["code" => 0, "msg" =>  "领取成功"]);
    			}else{
    			    return json(["code" => 0, "msg" =>  "领取失败"]);
    			}
			} else {
				return json(["code" => 0, "msg" =>  "没有指定福利权限" ]);
			}
		} catch (\Exception $e) {
            return  ["code"=>2,"msg"=>"特权领取异常，Error：".$e->getMessage()];
		}
	}
	
	// 累充领取开始
	public function leichong() {
		$request = \think\Request::instance()->post();
		//获取上游传递的参数		
		$accountid = $request["accountid"];//账号库ID
		$serverid = $request["serverid"];//区服ID	
		$productid = $request["productid"];//礼包ID
		$tool = new \app\pay\controller\Tool();
		//获取服务器信息
		$gameServer= $tool->getGameServer($serverid);
		//获取角色信息
		$account = $request["account"];//账号
		$playerid = $request["guid"];//角色ID
		$roleid = $tool->getRole($gameServer["surface"],$accountid,$playerid);
		if(empty($roleid )){
		    return  ["code"=>0,"msg"=>"查询角色失败"];
		}
		//查询商品
		$items = CacheData("leichongconfig-".$productid,function() use($productid){
		    return \think\Db::name("leichongconfig")->field(true)->where("Id" , $productid)->find();
	    },300);
		if(empty($items)){
		    return  ["code"=>0,"msg"=>"查询商品失败"];
		}
		if(!isset($items["paynum"])||empty($items["paynum"])){
			return  ["code"=>0,"msg"=>"查询价格失败"];
		}
		try{
			$leichong = \think\Db::name("leichong")->where(["account" => $accountid, "server" => $serverid,"type" => $productid])->find();
			if ($leichong) {
				return json(["code" => 0, "msg" =>  "已经领取过了"]);
			}
			$sumMoney = \think\Db::name("gameorder")->where("account" , $account)->where("payment","rmb")->where("state","1")->sum("money");
			if (\intval($items["paynum"]) > \intval($sumMoney)) {
				return json(["code" => 0, "msg" => "未达到领取要求"]);
			}
			//调用本地接口发送礼品
			$apiurl='http://'.$_SERVER['HTTP_HOST'].'/pay/Index/api';
			$postdata=[
				"table" => "leichongconfig",
				"serverid" => $gameServer["server"],
				"playerid" => $playerid,
			    "productid" => $productid,
			    "sign" => $this->sign
			];
			$apiHtml=curl_post($apiurl,$postdata);
			$apiResult=json_decode($apiHtml,true);
            if($apiResult['code']==1){
    			$today = strtotime(date("Y-m-d"),time());
    			$data = ["account" => $accountid, "name" => $roleid["name"], "server" => $serverid, "role" => $playerid, "type" => $productid, "time" => $today];
    			\think\Db::name("leichong")->insert($data);
    			// 直接返回成功 参数
    			return json(["code" => 0, "msg" =>"领取成功"]);
			}else{
			    return json(["code" => 0, "msg" =>"领取失败"]);
			}
		} catch (\Exception $e) {
            return  ["code"=>2,"msg"=>"累充领取异常，Error：".$e->getMessage()];
		}
	}
	
	// 每日累充领取开始
	public function meiri() {
		$request = \think\Request::instance()->post();
		//获取上游传递的参数		
		$accountid = $request["accountid"];//账号库ID
		$serverid = $request["serverid"];//区服ID	
		$productid = $request["productid"];//礼包ID
		$tool = new \app\pay\controller\Tool();
		//获取服务器信息
		$gameServer= $tool->getGameServer($serverid);
		//获取角色信息
		$account = $request["account"];//账号
		$playerid = $request["guid"];//角色ID
		$roleid = $tool->getRole($gameServer["surface"],$accountid,$playerid);
		if(empty($roleid )){
		    return  ["code"=>2,"msg"=>"查询角色失败"];
		}
		//读取礼品
		$items = CacheData("meirileichong-".$productid,function() use($productid){
		    return \think\Db::name("meirilcconfig")->field(true)->where("Id" , $productid)->find();
	    },300);
		if(empty($items)){
		    return  ["code"=>0,"msg"=>"查询商品失败"];
		}
		if(!isset($items["paynum"])||empty($items["paynum"])){
			return  ["code"=>0,"msg"=>"查询价格失败"];
		}
	    try{
			$meiri = \think\Db::name("meiri")->field(true)->where(["account" => $accountid,"server" => $serverid,"type" => $productid])->find();
			//判断今日是否领取
			$timedate =  $meiri["time"]+60*60*24;
			if ($timedate > time()) {
				return json(["code" => 0, "msg" =>  "已经领取过了"]);
			}
			$sumMoney = \think\Db::name("gameorder")->where("account" , $account)->where("payment","rmb")->where("state","1")->whereTime("uptime", "today")->sum("money");
			if (\intval($items["paynum"]) > \intval($sumMoney)) {
				return json(["code" => 0, "msg" => "未达到领取要求"]);
			}
			//调用本地接口发送礼品
			$apiurl='http://'.$_SERVER['HTTP_HOST'].'/pay/Index/api';
			$postdata=[
				"table" => "meirilcconfig",
				"serverid" => $gameServer["server"],
				"playerid" => $playerid,
			    "productid" => $productid,
			    "sign" => $this->sign
			];
			$apiHtml=curl_post($apiurl,$postdata);
			$apiResult=json_decode($apiHtml,true);
            if($apiResult['code']==1){
    			$today = strtotime(date("Y-m-d"),time());
    			if ($meiri) {
    				$data = ["time" => $today];
    				$datae = \think\Db::name("meiri")->where(["account" => $accountid, "server" => $serverid,"role" => $playerid,"type" => $productid])->update($data);
    			} else {
    				$data = ["account" => $accountid, "name" => $roleid["name"], "server" => $serverid, "role" => $playerid, "type" => $productid, "time" => $today];
    				$datae = \think\Db::name("meiri")->insert($data);
    			}
    			// 直接返回成功 参数
			    return json(["code" => 0, "msg" =>"领取成功"]);
			}else{
			    return json(["code" => 0, "msg" =>"领取失败"]);
			}
		} catch (\Exception $e) {
            return  ["code"=>2,"msg"=>"每日累充领取异常，Error：".$e->getMessage()];
		}
	}
	//使用余额支付
	public function yuepay() {
	    $request = \think\Request::instance()->get();
	   //获取上游传递的参数		
		$accountid = $request["accountid"];//账号库ID
		$serverid = $request["serverid"];//区服ID	
		$productid = $request["productid"];//礼包ID
		$tool = new \app\pay\controller\Tool();
		//获取服务器信息
		$gameServer= $tool->getGameServer($serverid);
		//获取角色信息
		$account = $request["account"];//账号
		$playerid = $request["guid"];//角色ID
		$roleid = $tool->getRole($gameServer["surface"],$accountid,$playerid);
		if(empty($roleid )){
		    return  ["code"=>2,"msg"=>"查询角色失败"];
		}
		//查询商品
		$items = CacheData("shopconfig-".$productid,function() use($productid){
		    return \think\Db::name("shopconfig")->field(true)->where("Id" , $productid)->find();
	    },300);
		// 书写逻辑
		\think\Db::startTrans();
        try{
			$tequan = \think\Db::name("tequan")->where(["account" => $accountid, "server" => $serverid,"role" => $playerid,"type" => $productid])->find();
			if ($tequan) {
			    $this->msg(0,"请勿重复购买今日礼包");
			}
			$fuli = \think\Db::name("fuli")->where(["account" => $accountid,"server" => $serverid,"type" => $productid])->find();
			if ($fuli) {
			     $this->msg(0,"请勿重复购买福利礼包");
			}
			//查询用户（不能缓存，否则余额不准确）		
			$user = \think\Db::name("user")->where("Id", $accountid)->find();
			
			if ($user["rmb"] < $items["paynum"] ) {
			    $this->msg(0,"平台余额不足，请先充值");
			}
			if ($items["type"] == "终身限购" ) {
				if ($items["paynum"] == "0" ) {
					$data_account = \think\Db::name("user")->field("agent,safety,account,rmb")->where("Id", $accountid)->find();
				} else {
					$data_account = \think\Db::name("user")->where("Id", $accountid)->setDec("rmb", $items["paynum"]);
				}
			} else {
				$data_account = \think\Db::name("user")->where("Id", $accountid)->setDec("rmb", $items["paynum"]);
			}
			if ($data_account) {
				if ($items["type"] == "每日礼包" ) {
					$data = ["name" => $roleid["name"], "account" => $accountid, "server" => $serverid, "role" => $playerid, "type" => $productid, "time" => 0];
					\think\Db::name("tequan")->insert($data);
				}
				else if ($items["type"] == "抽奖次数" ) {
					\think\Db::name("user")->where("Id" , $accountid)->setInc("cishu", $items["item"]);
				}
				//发送物品
				else {
				    //调用本地接口
				    $apiurl='http://'.$_SERVER['HTTP_HOST'].'/pay/Index/api';
				    $postdata=[
						"table" => "shopconfig",
				        "serverid" => $gameServer["server"],
				        "playerid" => $playerid,
				        "productid" => $productid,
				        "sign" => $this->sign
				    ];
				    $apiHtml=curl_post($apiurl,$postdata);
				    $apiResult=json_decode($apiHtml,true);
                	if($apiResult['code']==1){
                	    $time = date("Y-m-d H:i:s", time());
                	    $order_id = $this->generateOrderNumber();
        				$insertdata = [
        				    "sorder" => $order_id, 
        				    "gorder" => $order_id, 
        				    "account" => $user['account'],
        				    "server" => $serverid, 
        				    "role" => $playerid, 
        				    "rolename" => $roleid["name"], 
        				    "agent" => $user['agent'], 
        				    "state" => "1", 
        				    "uptime" => $time,
        				    "payment" => "jifen", 
        				    "money" => $items["paynum"], 
        				    "title" => $accountid, 
        				    "cmda" => $items["paynum"], 
        				    "cmdb" => $items["paynum"],
        				    "merchant" => $items["paynum"],
        				    "servername" => $gameServer['name'], 
        				    "agentall" => $user['safety'],
        				    "itemname" => $items["name"], 
        				    "paytape" => "余额支付"
        				];
        				\think\Db::name("gameorder")->insert($insertdata);
        				if ($items["type"] == "终身限购" ) {
        					$data = ["name" => $roleid["name"], "account" => $accountid, "server" => $serverid, "role" => $playerid, "type" => $productid, "time" => 0];
        					\think\Db::name("fuli")->insert($data);
        				}
        				\think\Db::commit();
        				 $this->msg(1,"支付成功，请返回游戏邮件里领取");
                	}else{
                	    $this->msg(0,"发送物品失败");
                	}
				}
			} else {
			    $this->msg(0,"写入数据库失败");
			}
        } catch (\Exception $e) {
            \think\Db::rollback();
            $this->msg(0,"余额支付异常");
		}
	}
	
    //充值账户余额
    public function recharge() {
    	$request = \think\Request::instance()->get();
    	//获取上游传递的参数
    	$paytype = $request["paytype"];//支付方式
    	$money = $request["money"];//充值金额
    	//最低充值金额
    	if(empty($money) || $money<=0) {
    	    $this->msg(0,"充值金额必须大于0");
    	}
    	//账号
    	$account=\think\Session::get("account");
    	/*------------------------------------ 提交到三七云平台 -------------------------------------*/
    	try {
    		//计算签名
    		$postData=array(
    		    "appid" => $this->appid,
    		    "payid" => $this->generateOrderNumber(),//生成订单号
    		    "money" => $money,//提交金额
    		    "type" => $paytype,//支付方式 1：支付宝  2：微信支付
    		    "notify_url" => 'http://'.$_SERVER['HTTP_HOST'].'/pay/Index/rechargeNotify',
    		    "return_url" => $this->return_url,
    		    "subject" => $account, 
    		    "param" => $account,//账号放自定义参数
    		    "hidetitle" => true,
				"codesize" => 150,
    		);
    		$stringTemp = $this->ASCII($postData);
    		$postData["sign"] =	$this->md5Sign($stringTemp,$this->appkey);
    		//4.跳转到支付页面
    		$res = $this->buildRequestForm($this->payurl,$postData);
    		echo $res;
    		exit;
    	}catch (\Exception $e) {
    	    $this->msg(0,"充值异常");
    	}
    	/*------------------------------------ 提交到三七云平台 -------------------------------------*/
    }
    //充值回调（异步通知）
	public function rechargeNotify() {
	    if (empty($_POST)) $_POST = $_GET;//如果为GET方式访问
		$sign = $this->ASCII($_POST);
		$flag = $this->md5Verify($sign,$_POST['sign'],$this->appkey);
		if($flag){
			$pay_id = $_POST['pay_id'];           //需要充值的ID 或订单号 或用户名
			$pay_no = $_POST['pay_no'];
			$pay_money = (float)$_POST['pay_money']; //实际付款金额	
			$pay_type = $_POST['pay_type']; 
			$pay_time = date("Y-m-d H:i:s",$_POST['pay_time']);
			$account = isset($_POST['param'])?$_POST['param']:'';//自定义参数
			if(empty($account)){
			    exit('自定义参数为空'); 
			}
			if ($pay_type == 1) {
				$paytapename = "支付宝";
			} else {
				$paytapename = "微信支付";
			}
			//查询订单
			$orderinfo = \think\Db::name('gameorder')->where("sorder", $pay_id)->find();
			if($orderinfo){
			    exit('success'); //订单已存在
			}
			//查询用户
    	    $user = CacheData("user-".$account,function() use($account){
        		return  \think\Db::name("user")->where("account", $account)->find();
        	},300);
			\think\Db::startTrans();
			try{
			    $bili = config('yuanbaopay.bili');//充值比例
			    $rmb = intval($bili) * $pay_money;
			    \think\Db::name("user")->where("account", $account)->setInc('rmb',$rmb);
			    //添加账单
        		$insertdata = [
				    "sorder" => $pay_id, 
				    "gorder" => $pay_no, 
				    "account" => $user['account'],
				    "server" => '', 
				    "role" => '', 
				    "rolename" => '', 
				    "agent" => $user['agent'], 
				    "state" => "1", 
				    "uptime" => $pay_time,
				    "payment" => "rmb", 
				    "money" => $pay_money, 
				    "title" => $user['Id'], 
				    "cmda" => 0, 
				    "cmdb" => 0,
				    "merchant" => 0,
				    "servername" => "", 
				    "agentall" => $user['safety'],
				    "itemname" => "余额充值", 
				    "paytape" => $paytapename
				];
				\think\Db::name("gameorder")->insert($insertdata);
			    //代理反水
			    $this->agentPoint( $user['agent'],$account, \intval($pay_money),$pay_no,$pay_id);
			    \think\Db::commit();
				exit('success'); //返回成功，业务处理完成，下面不再执行了
			} catch (\Exception $e) {
			    \think\Db::rollback();
				exit('充值失败');
			}
		}else{
			exit('fail');//返回失败 继续补单
		}
	}
	//代理反水
	protected function agentPoint($agent,$account, $money,$order_id, $pay_id){
    	//查询代理
    	$datae = CacheData("agent-".$agent,function() use($agent){
    		return  \think\Db::name("agent")->field("id,branch,agent")->where("account", $agent)->find();
    	},300);
		if($datae){
			$branch=$datae["branch"];
			$rmb=$money * ($branch / 100);
			\think\Db::name("agent")->where("account", $agent)->setInc("rmb", $rmb);
			/*
			$Testdata["agent"] = $agent;
			$Testdata["order_id"] = $order_id;
			$Testdata["pay_id"] = $pay_id;
			$Testdata["account"] = $account;
			$Testdata["money"] = $money;
			$Testdata["point"] = $rmb;
			$Testdata["time"] = date("Y-m-d H:i:s", time());
			\think\Db::name("agent_log")->data($Testdata)->insert();
			*/
		}
	}
	//购买
	public function goumai() {
		$request = \think\Request::instance()->get();
		//获取上游传递的参数
		$accountid = $request["accountid"];//账号库ID
		$serverid = $request["serverid"];//区服ID
		$productid = $request["productid"];//礼包ID
		$paytype = $request["paytype"];//支付方式
		$tool = new \app\pay\controller\Tool();
		//获取服务器信息
		$gameServer= $tool->getGameServer($serverid);
		//获取角色信息
		$account = $request["account"];//账号
		$playerid = $request["guid"];//角色ID
		$roleid = $tool->getRole($gameServer["surface"],$accountid,$playerid);
		if(empty($roleid )){
		    return  ["code"=>2,"msg"=>"查询角色失败"];
		}
	    try {
	        //查询商品
            $items = CacheData("shopconfig-".$productid,function() use($productid){
            	return  \think\Db::name("shopconfig")->field(true)->where("Id",$productid)->find();
            },300);
			$tequan = \think\Db::name("tequan")->where(["account" => $accountid,"server" => $serverid,"role" => $playerid,"type" => $productid])->find();
			if ($tequan) {
			    $this->msg(0,"请勿重复购买今日礼包");
			}
			$fuli = \think\Db::name("fuli")->where(["account" => $accountid,"server" => $serverid,"type" => $productid])->find();
			if ($fuli) {
			     $this->msg(0,"请勿重复购买福利礼包");
			}
			/*------------------------------------ 提交到三七云平台 -------------------------------------*/
			
			$param = $roleid["name"]."_".$playerid."_".$serverid."_".$accountid."_". $productid;
			//1.计算签名
			$postData=array(
				"appid" => $this->appid,
				"payid" => $this->generateOrderNumber(),//生成订单号
				"money" => $items["paynum"],//提交金额
				"type" => $paytype,//支付方式 1：支付宝  2：微信支付 3：QQ钱包
				"notify_url" => $this->notify_url,
				"return_url" => $this->return_url,
				"param"=>$param,//自定义参数
				"hidetitle" => true,
			);
			$stringTemp = $this->ASCII($postData);
			$postData["sign"] =	$this->md5Sign($stringTemp,$this->appkey);
			//4.跳转到支付页面
			$res = $this->buildRequestForm($this->payurl,$postData);
			echo $res;
			exit;
			/*------------------------------------ 提交到三七云平台 -------------------------------------*/
	    }catch (\Exception $e) {
	        printLog($e);
	        $this->msg(0,"购买异常");
    	}
	}
	//购买回调调（异步通知）
	public function notify() {
		if (empty($_POST)) $_POST = $_GET;//如果为GET方式访问
		$sign = $this->ASCII($_POST);
		$flag = $this->md5Verify($sign,$_POST['sign'],$this->appkey);
		if($flag){
			$sdorderno = $_POST['pay_id'];           //需要充值的ID 或订单号 或用户名
			$total_fee = (float)$_POST['pay_money']; //实际付款金额	
			$pay_type = (int)$_POST['pay_type']; 	 //支付方式 1：支付宝 2：微信支付
			$pay_time = date("Y-m-d H:i:s",$_POST['pay_time']);
			$sdpayno = $_POST['pay_no'];             //交易流水号
			$param = isset($_POST['param']) ? $_POST['param'] : '';//自定义参数
			if(empty($param)){
			    exit('自定义参数为空'); 
			}
			if ($pay_type == 1) {
				$paytapename = "支付宝";
			} else {
				$paytapename = "微信支付";
			}
			//$param = $roleid["name"]."_".$playerid."_".$serverid."_".$accountid."_". $productid;
			$accounta = explode("_", $param);
			$rolename = $accounta[0];
			$playerid = $accounta[1];
			$serverid =  $accounta[2];
			$accountid =  $accounta[3];
			$productid = $accounta[4];
			$orderinfo = \think\Db::name('gameorder')->where("sorder", $sdorderno)->find();
			if($orderinfo){
			    exit('success'); //订单已存在
			}
			//游戏充值业务开始
			\think\Db::startTrans();
			try{
			    //查询用户
        	    $user = CacheData("userid-".$accountid,function() use($accountid){
            		return  \think\Db::name("user")->where("Id", $accountid)->find();
            	},300);
				//获取服务器信息
				$tool = new \app\pay\controller\Tool();
            	$gameServer= $tool->getGameServer($serverid);
            	//查询商品
            	$items = CacheData("shopconfig-".$productid,function() use($productid){
            		return  \think\Db::name("shopconfig")->field(true)->where("Id",$productid)->find();
            	},300);
				//每日礼包
				if ($items["type"] == "每日礼包") {
					$data = ["name" => $rolename, "account" => $accountid, "server" => $serverid, "role" => $playerid, "type" => $productid, "time" => 0];
					\think\Db::name("tequan")->insert($data);
				}
				//抽奖次数
				else if ($items["type"] == "抽奖次数") {
					\think\Db::name("user")->where("Id", $accountid)->setInc("cishu", $items["item"]);
				}
				//发送物品
				else  {
                	$resultSendItem = $tool->sendItems($gameServer["server"], $playerid, $gameServer["ip"], $gameServer["gmport"], $items);
                	if($resultSendItem){
        				if ($items["type"] == "终身限购"){
					        $data = ["name" => $rolename, "account" => $accountid, "server" => $serverid, "role" => $playerid, "type" => $productid, "time" => 0];
					        \think\Db::name("fuli")->insert($data);
				        }
                	}else{
                	    exit('发送物品失败');
                	}
				}
				//添加账单
				$insertdata = [
				    "sorder" => $sdorderno, 
				    "gorder" => $sdpayno, 
				    "account" => $user['account'],
				    "server" => $serverid, 
				    "role" => $playerid, 
				    "rolename" => $rolename, 
				    "agent" => $user['agent'], 
				    "state" => "1", 
				    "uptime" => $pay_time,
				    "payment" => "rmb", 
				    "money" => $items["paynum"], 
				    "title" => $user['Id'], 
				    "cmda" => $items["paynum"], 
				    "cmdb" => $items["paynum"],
				    "merchant" => $items["paynum"],
				    "servername" => "", 
				    "agentall" => $user['safety'],
				    "itemname" => $items["name"], 
				    "paytape" => $paytapename
				];
				\think\Db::name("gameorder")->insert($insertdata);
				//代理反水
			    $this->agentPoint($user['agent'],$user['account'], \intval($total_fee),$sdpayno,$sdorderno);
				\think\Db::commit();
				exit('success'); //返回成功，业务处理完成，下面不再执行了
			} catch (\Exception $e) {
				\think\Db::rollback();
				exit('充值失败'.$e);
			}
		}else{
			exit('fail');//返回失败 继续补单
		}
	}
	/**
     * 签名字符串
     * @param $prestr 需要签名的字符串
     * @param $key 私钥
     * return 签名结果
     */
	function md5Sign($prestr, $key) {
		$prestr = $prestr . $key;
		return md5($prestr);
	}
	/**
     * 验证签名
     * @param $prestr 需要签名的字符串
     * @param $sign 签名结果
     * @param $key 私钥
     * return 签名结果
     */
	function md5Verify($prestr, $sign, $key) {
		$prestr = $prestr . $key;
		$mysgin = md5($prestr);
		if($mysgin == $sign) {
			return true;
		} else {
			return false;
		}
	}
	/**
	 * 生成订单号
	 */
	 protected function generateOrderNumber($length=4){
		$date=trim(date('Ymdhis ',time()));
		$number=trim($this->getRandNumber($length));
		return $date.$number;
	 }
	/**
	*生成不重复的随机数字
	*@paramint$start需要生成的数字开始范围
	*@paramint$end结束范围
	*@paramint$length需要生成的随机数个数
	*@returnnumber生成的随机数
	*/
	protected function getRandNumber($length=4){
		//初始化变量为0
		$connt = 0;
		//建一个新数组
		$temp = array();
		while($connt < $length){
		//在一定范围内随机生成一个数放入数组中
		$temp[] = mt_rand(0, 9);
		//$data = array_unique($temp);
		//去除数组中的重复值用了“翻翻法”，就是用array_flip()把数组的key和value交换两次。这种做法比用 array_unique() 快得多。	
		$data = array_flip(array_flip($temp));
		//将数组的数量存入变量count中	
		$connt = count($data);
		}
		//为数组赋予新的键名
		shuffle($data);
		//数组转字符串
		$str=implode(",", $data);
		//替换掉逗号
		$number=str_replace(',', '', $str);
		return $number;
	}
	/* 1.将数组内非空参数值的参数按照参数名从小到大排序（ASCII码字典序）
	 * 2.然后使URL键值对的格式（即key1=value1&key2=value2…）拼接成字符串
	 */
	function ASCII($params = array()){
		//ksort()对数组按照键名进行升序排序
		ksort($params);
		//reset()内部指针指向数组中的第一个元素
		reset($params);
		//$sign = http_build_query($params, '', '&amp');
		$sign = '';//初始化
		foreach ($params AS $key => $val) { //遍历POST参数
			if ($val == ''||$key == 'sign') continue; //跳过这些不签名
			if ($sign) $sign .= '&'; //第一个字符串签名不加& 其他加&连接起来参数
			$sign .= "$key=$val"; //拼接为url参数形式
		}		
		return $sign;
	}
	/**
	 * 建立跳转请求表单
	 * @param string $url 数据提交跳转到的URL
	 * @param array $data 请求参数数组
	 * @param string $method 提交方式：post或get 默认post
	 * @return string 提交表单的HTML文本
	 */
	function buildRequestForm($url, $data, $method = 'post')
	{
		$sHtml = "<form id='requestForm' name='requestForm' action='".$url."' method='".$method."'>";
		while (list ($key, $val) = each ($data))
		{
			$sHtml.= "<input type='hidden' name='".$key."' value='".$val."' />";
		}
		$sHtml = $sHtml."<input type='submit' value='正在跳转到支付'></form>";
		$sHtml = $sHtml."<script>document.forms['requestForm'].submit();</script>";
		return $sHtml;
	}
}