<?php
$dabase = include '../config/database.php';

$dbconfig = array(
             // 服务器地址
            'hostname'        => $dabase['hostname'],
            // 数据库名
            'database'        => $dabase['database'],
            // 用户名
            'username'        => $dabase['username'],
            // 密码
            'password'        => $dabase['password'],
        );
        $link = mysqli_connect($dbconfig['hostname'],$dbconfig['username'],$dbconfig['password'],$dbconfig['database']);
        //var_dump($link);
        if (!$link) {
            printf("Can't connect to MySQL Server. Errorcode: %s ", mysqli_connect_error());
            exit;
        }

//易支付发起接口
if(isset($_GET['pid'])){
	$_REQUEST=$queryArr=$_GET;
}elseif(isset($_POST['pid'])){
	$_REQUEST=$queryArr=$_POST;
}else{
	@header('Content-Type: text/html; charset=UTF-8');
	exit('未接收到有效参数pid！');
}



    
if(!empty($_REQUEST['pid'])){
    $appid = $_REQUEST['pid'];
}else{exit('pid参数不能为空!');}

$result = mysqli_query($link, "SELECT * FROM `box_user` WHERE `mid` = '".$appid."'");
$result = mysqli_fetch_assoc($result);

if($result === null){
    exit('商户号不存在！');
}

//当面付
/*$result_dmf = mysqli_query($link, "SELECT * FROM `box_pay_dmf` WHERE `status`= 1 and `uid` = '".$result['id']."'");
$result_dmf = mysqli_fetch_assoc($result_dmf);*/
//当面付

$appsecret = $result['apikey'];

$actypes = ['alipay','wxpay','dmf','qqpay'];
if(!empty($_REQUEST['type']) && in_array($_REQUEST['type'],$actypes) ){
    $type0 = $_REQUEST['type'];
    $type = $type0 == 'wxpay' ? 1: ($type0 == 'qqpay' ? 4 : 2);
}else{exit('type参数错误！当前支持'.explode(',',$actypes));}

if(!empty($_REQUEST['out_trade_no'])){
    $out_trade_no = $_REQUEST['out_trade_no'];
}else{exit('out_trade_no参数不能为空！');}

if(!empty($_REQUEST['notify_url'])){
    $notify_url = $_REQUEST['notify_url'];
}else{exit('notify_url参数不能为空！');}

if(!empty($_REQUEST['return_url'])){
    $return_url = $_REQUEST['return_url'];
}else{exit('return_url参数不能为空！');}

if(!empty($_REQUEST['name'])){
    $name = $_REQUEST['name'];
}else{exit('name参数不能为空！');}

if(!empty($_REQUEST['money']) && $_REQUEST['money'] > 0){
    $money = $_REQUEST['money'];
}else{exit('money参数错误！');}

//易支付签名校验

$prestr = createLinkstring(argSort(paraFilter($queryArr)));

$sign_error = md5Verify($prestr,$queryArr['sign'],$appsecret);
if(!$sign_error){
    exit('签名校验失败，请返回重试！');
}

$url = 'https://'.$_SERVER['HTTP_HOST'].'/createOrder?gis=1';

$Post['mid'] = $appid;
$Post['type'] = $type;//微信支付传入1 支付宝支付传入2
$Post['payId'] = $out_trade_no;
$Post['price'] = $money;

$Post['notifyUrl'] = $notify_url;
$Post['returnUrl'] = $return_url;
$Post['param'] = $name;
$Post['isHtml'] = '1';
$Post['is_epay'] = '1';
if($type0 == 'dmf'){
    $Post['is_dmf'] = '1';
}



$sign = "{$Post['mid']}{$Post['payId']}{$Post['param']}{$Post['type']}{$Post['price']}{$appsecret}";;
$Post['sign'] = md5($sign);

$zt=curl($url,$Post,1);
if(strpos($zt,"/pay/service/payinfo?orderId=")!==false){
    //print_r($zt);
    header("Location: {$zt}");exit;
}else{
    print_r($zt);die;
}

/*
$str = '<form id="Form1" name="Form1" method="post" action="' . $url . '">';
foreach ($Post as $key => $val) {
    $str .= '<input type="hidden" name="' . $key . '" value="' . $val . '">';
}
$str .= '</form>';
$str .= '<script>';
$str .= 'document.Form1.submit();';
$str .= '</script>';
echo $str;die;*/

function curl($url,$params=false,$ispost=0){
    $httpInfo = array();
    $ch = curl_init();
	$headers = array();
	$headers[] = 'X-Requested-With:XMLHttpRequest';
    curl_setopt( $ch, CURLOPT_HTTP_VERSION , CURL_HTTP_VERSION_1_1 );
    curl_setopt( $ch, CURLOPT_USERAGENT , 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22' );
	curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //不验证证书
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); //不验证证书
    curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT , 3 );
    curl_setopt( $ch, CURLOPT_TIMEOUT , 3);
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER , true );
    if( $ispost )
    {
        curl_setopt( $ch , CURLOPT_POST , true );
        curl_setopt( $ch , CURLOPT_POSTFIELDS , $params );
        curl_setopt( $ch , CURLOPT_URL , $url );
    }
    else
    {
        if($params){
            curl_setopt( $ch , CURLOPT_URL , $url.'?'.$params );
        }else{
            curl_setopt( $ch , CURLOPT_URL , $url);
        }
    }
    $response = curl_exec( $ch );
    if ($response === FALSE) {
        //echo "cURL Error: " . curl_error($ch);
        return false;
    }
    $httpCode = curl_getinfo( $ch , CURLINFO_HTTP_CODE );
    $httpInfo = array_merge( $httpInfo , curl_getinfo( $ch ) );
    curl_close( $ch );
    return $response;
}

function paraFilter($para) {
		$para_filter = array();
		foreach ($para as $key=>$val) {
			if($key == "sign" || $key == "sign_type" || $val == "")continue;
			else $para_filter[$key] = $para[$key];
		}
		return $para_filter;
}
function argSort($para) {
		ksort($para);
		reset($para);
		return $para;
}
function createLinkstring($para) {
		$arg  = "";
		foreach ($para as $key=>$val) {
			$arg.=$key."=".$val."&";
		}
		$arg = substr($arg,0,-1);

		return $arg;
}

function md5Verify($prestr, $sign, $key) {
		$prestr = $prestr . $key;
		$mysgin = md5($prestr);

		if($mysgin == $sign) {
			return true;
		}
		else {
			return false;
		}
}
