<?php
require_once("../../function/conn.php");
require_once("../../function/function.php");


$alipayPublicKey=$C_alipaynewkey2;
$aliPay = new AlipayService($alipayPublicKey);
$_POST['fund_bill_list'] = stripslashes($_POST['fund_bill_list']);
$result = $aliPay->rsaCheck($_POST,$_POST['sign_type']);


$trade_no=$_POST["trade_no"];
$total_fee=$_POST["total_amount"];


if($result==1 && $_POST['trade_status'] == 'TRADE_SUCCESS'){
    echo 'success';

	if (strpos($_POST["body"], "|") !== false) {
	    $body = explode("|", $_POST["body"]);
	} else {
	    $O_ids = $_POST["body"];
	    $subject = $_POST["subject"];
	    $M_id = getrx("select * from ".TABLE."orders where O_id=" . intval(splitx($O_ids, ",", 0)) , "O_member");
	}

	if ($_POST["trade_status"] = "TRADE_SUCCESS") {
	    if (strpos($_POST["body"], "|") !== false) {
	        $sql = "Select * from ".TABLE."list Where L_no='" . t($trade_no) . "'";
	        $result = mysqli_query($conn, $sql);
	        $row = mysqli_fetch_assoc($result);
	        if (mysqli_num_rows($result) <= 0) {
	            mysqli_query($conn, "update ".TABLE."member set M_money=M_money+" . $body[1] . " where M_id=" . intval($body[0]));
	            mysqli_query($conn, "insert into ".TABLE."list(L_mid,L_title,L_change,L_time,L_no,L_type) values(" . $body[0] . ",'用户充值'," . $body[1] . ",'" . date('Y-m-d H:i:s') . "','" . $trade_no . "',0)");
	            sendmail("有用户通过支付宝充值", "用户ID：" . $body[0] . "<br>充值金额：" . $body[1] . "元<br>交易单号：" . $trade_no, $C_email);
	        }
	    } else {
	        $sql = "Select * from ".TABLE."list Where L_no='" . t($trade_no) . "'";
	        $result = mysqli_query($conn, $sql);
	        $row = mysqli_fetch_assoc($result);
	        if (mysqli_num_rows($result) <= 0) {
	            $O_id = explode(",", $O_ids);
	            for ($i = 0; $i < count($O_id); $i++) {
	                mysqli_query($conn, "update ".TABLE."orders set O_state=1,O_tradeno='" . $trade_no . "（支付宝付款）' where O_id=" . intval($O_id[$i]));

	                //虚拟商品发货
	                $O_pid=getrx("select * from ".TABLE."orders where O_id=".$O_id[$i],"O_pid");
	                $P_info=getrs("select * from ".TABLE."product where P_id=".$O_pid);
	                if($P_info["P_sence"]==1){
	                    mysqli_query($conn, "update ".TABLE."orders set O_state=3 where O_id=" . intval($O_id[$i]));
	                    $M_email=getrx("select * from ".TABLE."member where M_id=".$M_id,"M_email");
	                    sendmail("您购买的商品已发货","<p>商品名称：".lang($P_info["P_title"])."</p><p>价格：".$P_info["P_price"]."</p><p>发货内容：".$P_info["P_sell"]."</p>",URLDecode($M_email));
	                }

	            }
	            mysqli_query($conn, "update ".TABLE."member set M_fen=M_fen+" . $total_fee * $C_1yuan . " where M_id=" . intval($M_id));
	            mysqli_query($conn, "insert into ".TABLE."list(L_mid,L_title,L_change,L_time,L_no,L_type) values(" . $M_id . ",'用户充值'," . $total_fee . ",'" . date('Y-m-d H:i:s') . "','" . $trade_no . "',0)");
	            mysqli_query($conn, "insert into ".TABLE."list(L_mid,L_title,L_change,L_time,L_no,L_type) values(" . $M_id . ",'购买商品',-" . $total_fee . ",'" . date('Y-m-d H:i:s') . "','" . $trade_no . "',0)");
	            if ($C_1yuan > 0) {
	                mysqli_query($conn, "insert into ".TABLE."list(L_title,L_mid,L_change,L_time,L_type,L_no) values('购买商品'," . $M_id . "," . $total_fee * $C_1yuan . ",'" . date('Y-m-d H:i:s') . "',1,'" . $trade_no . "')");
	            }
	            if ($C_1yuan2 > 0) {
	                mysqli_query($conn, "insert into ".TABLE."list(L_title,L_mid,L_change,L_time,L_type,L_no) values('好友购买商品'," . getrx("select * from ".TABLE."member where M_id=" . intval($M_id), "M_from") . "," . $total_fee * $C_1yuan2 . ",'" . date('Y-m-d H:i:s') . "',1,'" . $trade_no . "')");
	            }
	            if(strpos($C_smsuse,"4")!==false){
	                sendmobile("【".$C_smssign."】您的网站“".lang($C_webtitle)."”有新的订单已付款，请尽快发货！商品名称：".lang($P_title),$C_sms);
	            }
	            sendmail("有订单已付款，请尽快发货", "<h2>您的网站“" . $C_webtitle2 . "”有订单已付款，请尽快发货</h2><hr>商品名称：" . $subject . "<br>价格：" . $total_fee . "元<br>交易号：" . $trade_no . "（支付宝付款）<br>状态：已付款（等待发货）<hr>请进入“网站后台” - “商城管理” - “订单管理”进行发货操作！", $C_email);
	        }
	    }
	}
    exit();
}
echo 'error';
exit();
class AlipayService
{
    //支付宝公钥
    protected $alipayPublicKey;
    protected $charset;

    public function __construct($alipayPublicKey)
    {
        $this->charset = 'utf8';
        $this->alipayPublicKey=$alipayPublicKey;
    }

    /**
     *  验证签名
     **/
    public function rsaCheck($params) {
        $sign = $params['sign'];
        $signType = $params['sign_type'];
        unset($params['sign_type']);
        unset($params['sign']);
        return $this->verify($this->getSignContent($params), $sign, $signType);
    }

    function verify($data, $sign, $signType = 'RSA') {
        $pubKey= $this->alipayPublicKey;
        $res = "-----BEGIN PUBLIC KEY-----\n" .
            wordwrap($pubKey, 64, "\n", true) .
            "\n-----END PUBLIC KEY-----";
        ($res) or die('支付宝RSA公钥错误。请检查公钥文件格式是否正确');

        //调用openssl内置方法验签，返回bool值
        if ("RSA2" == $signType) {
            $result = (bool)openssl_verify($data, base64_decode($sign), $res, version_compare(PHP_VERSION,'5.4.0', '<') ? SHA256 : OPENSSL_ALGO_SHA256);
        } else {
            $result = (bool)openssl_verify($data, base64_decode($sign), $res);
        }
//        if(!$this->checkEmpty($this->alipayPublicKey)) {
//            //释放资源
//            openssl_free_key($res);
//        }
        return $result;
    }

    /**
     * 校验$value是否非空
     *  if not set ,return true;
     *    if is null , return true;
     **/
    protected function checkEmpty($value) {
        if (!isset($value))
            return true;
        if ($value === null)
            return true;
        if (trim($value) === "")
            return true;
        return false;
    }

    public function getSignContent($params) {
        ksort($params);
        $stringToBeSigned = "";
        $i = 0;
        foreach ($params as $k => $v) {
            if (false === $this->checkEmpty($v) && "@" != substr($v, 0, 1)) {
                // 转换成目标字符集
                $v = $this->characet($v, $this->charset);
                if ($i == 0) {
                    $stringToBeSigned .= "$k" . "=" . "$v";
                } else {
                    $stringToBeSigned .= "&" . "$k" . "=" . "$v";
                }
                $i++;
            }
        }
        unset ($k, $v);
        return $stringToBeSigned;
    }

    /**
     * 转换字符集编码
     * @param $data
     * @param $targetCharset
     * @return string
     */
    function characet($data, $targetCharset) {
        if (!empty($data)) {
            $fileType = $this->charset;
            if (strcasecmp($fileType, $targetCharset) != 0) {
                $data = mb_convert_encoding($data, $targetCharset, $fileType);
                //$data = iconv($fileType, $targetCharset.'//IGNORE', $data);
            }
        }
        return $data;
    }
}
?>