<?php
//====== 支付回调 ======
require "common.php";
header('Access-Control-Allow-Origin: *');
$m=file_get_contents("php://input");//file_put_contents("notify.txt",$m.PHP_EOL);
if(strpos($m,"trade_status")>-1){
	$w=$_POST["sign_type"]=="MD5"?1:0;$j=$w?$_POST["total_fee"]*100:$_POST["total_amount"]*100;
	$n=[];foreach($_POST as $k=>$v){if(!strpos("z".$k,"sign")&&$v!="")$n[]=$k.'='.$v;}sort($n);$n=implode("&",$n);
	if($w){$e=md5($d.$cfg["Ap"]["Zk"])==$_POST["sign"]?1:0;}else{
		$f=openssl_get_publickey($cfg["Ap"]["Zm"]);
		$e=openssl_verify($n,base64_decode($_POST['sign']),$f,OPENSSL_ALGO_SHA256);openssl_free_key($f);
	}
	$c=Cul("https://mapi.alipay.com/gateway.do?service=notify_verify&partner=".$cfg["Ap"]["Zp"]."&notify_id=".$_POST["notify_id"]);
	if($c=="true"&&$e*1==1&&$_POST["trade_status"]=="TRADE_SUCCESS"){
		Qry("Update ".$pre."pay Set Mt=0,Np=".$j.",Nc='".$_POST["trade_no"]."',Nd=Now(),Nt=1 Where Mc='".$_POST["out_trade_no"]."'");
		echo "success";
	}else echo "fail";
}elseif(strpos($m,"<xml>")>-1){
	$s=X2J($m);$n=[];foreach($s as $k=>$v){if($k!="sign"&&$v!="")$n[]=$k."=".$v;}sort($n);$n=implode("&",$n);
	if($s["result_code"]=="SUCCESS"&&$s["return_code"]=="SUCCESS"&&strtoupper(md5($n."&key=".$cfg["Ap"]["Wk"]))==$s["sign"]){
		Qry("Update ".$pre."pay Set Mt=1,Np=".$s["total_fee"].",Nc='".$s["transaction_id"]."',Nd=Now(),Nt=1 Where Mc='".$s["out_trade_no"]."'");
		echo "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
	}else echo "ERROR";
}else{
	$s="gw_mchid=".$cfg["Ap"]["Gi"]."&gw_money=".$_POST["gw_money"]."&gw_order=".$_POST["gw_order"]."&gw_otime=".$_POST["gw_otime"]."&gw_payno=".$_POST["gw_payno"]."&gw_price=".$_POST["gw_price"]."&gw_ptime=".$_POST["gw_ptime"]."&gw_rand=".$_POST["gw_rand"]."&gw_type=".$_POST["gw_type"];
	if(strtolower(md5($s."&key=".$cfg["Ap"]["Gk"]))==$_POST["gw_sign"]){
		Qry("Update ".$pre."pay Set Mt=".$_POST["gw_type"].",Np=".$_POST["gw_money"].",Nc='".$_POST["gw_payno"]."',Nd=Now(),Nt=1 Where Mc='".$_POST["gw_order"]."'");
		echo "ok";
	}else echo "fail";
}
?>