<!--#include virtual="/inc-freehost-function/FreeHostFunctionMain.asp"-->
<%


if DateDiff("s", Application("alioptime"),NOW )<6 and Application("alioplock")=true then
	ef=True
	ec="系统繁忙，前操作尚未处理完。"
end If


Application.lock
Application("alioptime")=now
Application("alioplock")=true
Application.unlock


Function XMII_Md5(md5str,CurKey)
Dim returnstr
Set xml = Server.CreateObject("Msxml2.ServerXMLHTTP.3.0")
xml.setTimeouts 20000, 20000, 20000, 20000
xml.Open "GET", Application("md5serverurl")&"md5end.asp?str="&server.URLEncode(md5str)&"&CurKey="&CurKey&"&type=return", False
xml.setOption(2)=13056
xml.send
returnstr = bytes2BSTR(xml.responsebody)
XMII_Md5 = returnstr
End Function

Function Bytes2bStr(vin)
  Dim BytesStream,StringReturn
  Set BytesStream = Server.CreateObject("ADODB.Stream")
  BytesStream.Type = 2
  BytesStream.Open
  BytesStream.WriteText vin
  BytesStream.Position = 0
  BytesStream.Charset = "gb2312"
  BytesStream.Position = 2
  StringReturn =BytesStream.ReadText
  BytesStream.close
  Set BytesStream = Nothing
  Bytes2bStr = StringReturn
End Function

dim partner
	partner			=	Application("alipayid")
Dim key
	key=Application("NP_ali_Key")	

If Application("alipayid")="2088001779970004" Or Application("alipayid")="2088101700293850" Then partner="2088101700293850"



'ATN 校验地址 
alipayNotifyURL = "https://mapi.alipay.com/cooperate/gateway.do?"
'获取ATN结果,如果您的服务器不支持https访问的话，需要用老的接口查询地址了，论坛上会公布

alipayNotifyURL	= alipayNotifyURL & "service=notify_verify&partner=" & partner & "&notify_id=" & request("notify_id")
'	response.write alipayNotifyURL
	Set Retrieval = Server.CreateObject("Msxml2.ServerXMLHTTP.3.0")
    Retrieval.setOption 2, 13056 
    Retrieval.open "GET", alipayNotifyURL, False, "", "" 
    Retrieval.send()
    ResponseTxt = Retrieval.ResponseText
	Set Retrieval = Nothing




If Application("md5serverurl")="" Then Application("md5serverurl")="http://sys.7i24.com/system/ali/" 

If partner="2088101700293850" And Len(Request.QueryString)>100 Then'GET
For Each varItem in Request.QueryString 
mystr=varItem&"="&Request.QueryString(varItem)&"^"&mystr
Next 
If mystr<>"" Then 
mystr=Left(mystr,Len(mystr)-1)
End If
'*******************************************************************
'对参数排序
mystr = SPLIT(mystr, "^")
Count=ubound(mystr)
For i = Count TO 0 Step -1
    minmax = mystr( 0 )
    minmaxSlot = 0
    For j = 1 To i
            mark = (mystr( j ) > minmax)
        If mark Then 
            minmax = mystr( j )
            minmaxSlot = j
        End If
    Next
    
    If minmaxSlot <> i Then 
        
        temp = mystr( minmaxSlot )
        mystr( minmaxSlot ) = mystr( i )
        mystr( i ) = temp
    End If
 Next
	
 
 '构造md5摘要字符串
  For j = 0 To Count Step 1
  value = SPLIT(mystr( j ), "=")

  If  value(0)<>"sign" And value(0)<>"sign_type"  then
       If j=Count Then
       md5str= md5str&mystr( j )
	   Else 
       md5str= md5str&mystr( j )&"&"
	   End If 
  End If 
  Next

else'获取POST过来的参数
mystr = SPLIT(URLDecode(request.Form), "&")
Count=ubound(mystr)

'对参数排序
For i = Count TO 0 Step -1
    minmax = mystr( 0 )
    minmaxSlot = 0
    For j = 1 To i
            mark = (mystr( j ) > minmax)
        If mark Then 
            minmax = mystr( j )
            minmaxSlot = j
        End If
    Next
    
    If minmaxSlot <> i Then 
        
        temp = mystr( minmaxSlot )
        mystr( minmaxSlot ) = mystr( i )
        mystr( i ) = temp
    End If
 Next
	

 
'构造md5摘要字符串
  For j = 0 To Count Step 1
  value = SPLIT(mystr( j ), "=")

  If  value(1)<>"" And value(0)<>"sign" And value(0)<>"sign_type"  then
       If j=Count Then
       md5str= md5str&mystr( j )
	   Else 
       md5str= md5str&mystr( j )&"&"
	   End If 
  End If 
  Next
End if


If partner="2088101700293850" Then
If md5str="" Then
	   response.write "不能为空-Null"
Application.lock
Application("alioplock")=false
Application.unlock
  	   response.end
End If
CurKey=Request("sign")
If len(CurKey)<>32  Then
	   response.write "试图入侵，系统已记录你的信息，你的IP是："&Request.ServerVariables("REMOTE_ADDR")
	   FreeHost_oplog "error","信息","实时返回支付宝支付出错A,试图入侵来自IP："&Request.ServerVariables("REMOTE_ADDR")
Application.lock
Application("alioplock")=false
Application.unlock
  	   response.end
End If

'response.write Request.QueryString&"<br>"
'response.write md5str&"<br>"
'response.write "err:trade_status:"&Request("trade_status")&"-mysign-"&mysign&"-qsign-"&Request("sign")&"-txt-"&ResponseTxt


'mysign=FreeHostAliCom.XMII(CStr(md5str),CStr(CurKey))
mysign=XMII_Md5(CStr(md5str),CStr(CurKey))
If InStr(mysign,"出错") or InStr(mysign,"ror:")  or InStr(mysign,"入侵") Or Len(mysign)<>32 Then
	   response.write mysign
FreeHost_oplog "error","信息","实时返回支付宝支付出错B,试图入侵来自IP："&Request.ServerVariables("REMOTE_ADDR")
Application.lock
Application("alioplock")=false
Application.unlock
  	   response.end
End if
Else
 md5str=md5str&key
 '生成md5摘要
 mysign=md5(md5str)
End If


	'验证消息的可靠性，并且处理自己的业务动作，然后反回给支付宝成功消息  
If mysign=request("sign") And ResponseTxt="true" Then 	
'If mysign=request("sign") Then 	

  '可以复制，与网站的状态同步，判断支付状态,返回状态再支付宝账户，商家工具里面可以选择
' If  request.Form("trade_status")="WAIT_SELLER_SEND_GOODS" or request.Form("trade_status")="TRADE_FINISHED" Then 
 If  request("trade_status")="TRADE_FINISHED" Or request("trade_status")="TRADE_SUCCESS" Then

'支付宝收到买家付款，请卖家发货 ,修改订单状态，发货等





Set conn=Server.CreateObject("ADODB.Connection")
	conn.Open Application("FreeHostDBlink")
Set dsNP = Server.CreateObject("ADODB.Recordset")	

seller_email=trim(Request("seller_email"))
buyer_email=trim(Request("buyer_email"))
If Request("bank_seq_no")<>"" Then buyer_email=buyer_email&"(网银公共帐号)"

If partner="2088101700293850" Then
subject=trim(Request("subject"))
'response.write subject
'支付宝号：["&seller_email&"] 收款人：
arysub=Split(subject,"支付宝号：[")
arysub2=Split(arysub(1),"]")
'seller_email=Trim(arysub2(0))
seller_email=Replace(Trim(arysub2(0)),"*",".")
seller_email=Replace(seller_email,"＠","@")
End If
'Sql="Select * from FreeHost.FreeHost_Netpay where ORDERID='"&trim(Request.QueryString("out_trade_no"))&"' and SHOPID='"&seller_email&"' "

	Sql="Select * from FreeHost.FreeHost_Netpay where ORDERID='"&trim(Request("out_trade_no"))&"' and SHOPID='"&seller_email&"' "

if RegExpTest("^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$",seller_email)=False Or RegExpTest("[^A-Za-z0-9]",Request("out_trade_no")) then
	ef=True
	ec="邮箱或out_trade_no不正确！"'&Sql
FreeHost_oplog "error","信息","实时返回支付宝支付出错"&ec
response.write "fail"&ec
Application.lock
Application("alioplock")=false
Application.unlock
response.end
end if
		dsNP.Open Sql,conn,3,2
if dsNP.eof then
		ef=True
		ec="不存在的订单！"
FreeHost_oplog "error","信息","实时返回支付宝支付出错"&ec
response.write "fail"&ec
Application.lock
Application("alioplock")=false
Application.unlock
response.end
end if

if not ef Then
  if dsNP("SucceedFlag") <>99 then
		ef=True
		ec="异步通知状态已更新过了，不能重复操作！"
		response.write "success"
Application.lock
Application("alioplock")=false
Application.unlock
		response.end
  end if
  if Request("total_fee")<dsNP("OrderMoney") then
		ef=True
		ec="支付不成功！实际支付金额小于订单金额！"
   end If
  if DateDiff("s" , dsNP("paytime"),Now)>1800 Then
  		ef=True
		ec="支付不成功！订单处理时间超过30分钟了！"
   end If
'  if dsNP("ORDERMONEY") <>ORDERMONEY then
'		ef=True
'		ec="金额不正确！"
'  end if
end If

'验证会员资格
If not ef then
'Set conn=Server.CreateObject("ADODB.Connection")
'	conn.Open Application("FreeHostDBlink")
agentcannetpay=false
Set dsreg = Server.CreateObject("ADODB.Recordset")	
	Sql="Select * from FreeHost.FreeHost_AGENT where username='"&dsNP("username")&"' and agenttype<>'n'"
		dsreg.Open Sql,conn,1,3
If dsreg.Eof Then
Set dsreg = Server.CreateObject("ADODB.Recordset")	
	Sql="Select * from FreeHost.FreeHost_USER where username='"&dsNP ("username")&"'"
		dsreg.Open Sql,conn,1,3
If dsreg.Eof Then
		ef=True
		ec="会员名不存在！"
Else

If dsreg("agent1")<>"n" then
  Set dsSend2Mailagn = Server.CreateObject("ADODB.Recordset")	
		Sql="Select NP_ali_ShopID,tenpayid,tenpaykey from FreeHost.FreeHost_AGENT where username='"&dsreg("agent1")&"' and (NP_ali_ShopID is not null) and canusenetpay=1"
		dsSend2Mailagn.Open Sql,conn,1,1
If not dsSend2Mailagn.Eof Then
If Application("agentcannetpay")=True Then
sShopID=dsSend2Mailagn("NP_ali_ShopID")
agentcannetpay=True
End if
End If
end If

end If
Else

If dsreg("agent1")<>"n" then
  Set dsSend2Mailagn = Server.CreateObject("ADODB.Recordset")	
		Sql="Select NP_ali_ShopID,tenpayid,tenpaykey from FreeHost.FreeHost_AGENT where username='"&dsreg("agent1")&"' and (NP_ali_ShopID is not null) and canusenetpay=1"
		dsSend2Mailagn.Open Sql,conn,1,1
If not dsSend2Mailagn.Eof Then
If Application("agentcannetpay")=True Then
sShopID=dsSend2Mailagn("NP_ali_ShopID")
agentcannetpay=True
End if
End If
end If

If dsreg("agentdegree")=0 Then
agentcannetpay=false
sShopID = Application("NP_ali_ShopID")
End if

end if
end If

if not ef then
UserName=dsNP("UserName")
OrderMoney=dsNP("OrderMoney")
Set dsreg = Server.CreateObject("ADODB.Recordset")	
	Sql="Select * from FreeHost.FreeHost_AGENT where username='"&UserName&"' and agenttype<>'n'"
		dsreg.Open Sql,conn,3,2
If dsreg.Eof Then
Set dsreg = Server.CreateObject("ADODB.Recordset")	
	Sql="Select * from FreeHost.FreeHost_USER where username='"&UserName&"'"
		dsreg.Open Sql,conn,3,2
If dsreg.Eof Then
		ef=True
		ec="会员名不存在！"
end if
end if
end If

if not ef then
agentcannetpay=dsNP("agentcannetpay")
end if 

if not ef Then
SERVER_NAME=Request.ServerVariables("SERVER_NAME")
If Request.ServerVariables("HTTP_FreeHostAPISITE")<>"" Then SERVER_NAME=Request.ServerVariables("HTTP_FreeHostAPISITE")

dsNP("SucceedFlag") = 88
dsNP.update
If agentcannetpay=True Then
agnusername=dsreg("agent1")
'使用代理自己的接口
olduser_money=dsreg("waitmoney")
If Application("NetPaypercent")>0 Then OrderMoney=OrderMoney/(1+Application("NetPaypercent"))
OrderMoney=Round(OrderMoney,2)
moneych=OrderMoney
dsreg("waitmoney")=dsreg("waitmoney")+OrderMoney
newuser_money=dsreg("waitmoney")
UserName=dsreg("username")
dsreg.update

canautoenter=false
  Set dsSend2Mailagn = Server.CreateObject("ADODB.Recordset")	
		Sql="Select usermoney from FreeHost.FreeHost_AGENT where username='"&dsreg("agent1")&"'"
		dsSend2Mailagn.Open Sql,conn,3,2
If not dsSend2Mailagn.Eof Then
If dsSend2Mailagn("usermoney")>OrderMoney Or dsSend2Mailagn("usermoney")=OrderMoney Then
canautoenter=True
oldagn_money=dsSend2Mailagn("usermoney")
dsSend2Mailagn("usermoney")=dsSend2Mailagn("usermoney")-OrderMoney
dsSend2Mailagn.update
newagn_money=dsSend2Mailagn("usermoney")
dsreg("waitmoney")=dsreg("waitmoney")-OrderMoney'取消用户帐的的等候入帐钱.
dsreg("usermoney")=dsreg("usermoney")+OrderMoney'给用户帐上加钱
dsreg.update

FreeHost_moneyNewlog conn,"y","n","n","n","y",isAgnHostSer,moneych,UserName,UserName,UserName,olduser_money,newuser_money,agnusername,agnStmoney,agnEndmoney,supusername,"(独立)(自动入帐成功)网上支付支付宝接口订单"&trim(Request("out_trade_no"))&"网站："&SERVER_NAME&"付款人："&buyer_email,"(自动入帐成功)网上支付支付宝接口订单"&trim(Request("out_trade_no"))&"(AG)网站："&SERVER_NAME&"付款人："&buyer_email,whichProduct,pdid,"ali_"&dsNP("ORDERID"),type1,"独立支付",haveget,havecheck
FreeHost_moneyNewlog conn,"n","y","y","n","n",isAgnHostSer,moneych,dsreg("agent1"),dsreg("agent1"),dsreg("agent1"),norStmoney,norEndmoney,dsreg("agent1"),oldagn_money,newagn_money,supusername,"(独立支付接口)(自动入帐成功)(金额转移给名下用户"&UserName&")网上支付支付宝接口订单"&trim(Request("out_trade_no"))&"(AG)网站："&SERVER_NAME&"付款人："&buyer_email,"(独立支付接口)(自动入帐成功)(金额转移给名下用户"&UserName&")网上支付支付宝接口订单"&trim(Request("out_trade_no"))&"(AG)网站："&SERVER_NAME&"付款人："&buyer_email,whichProduct,pdid,"ali_"&dsNP("ORDERID"),type1,"独立支付",haveget,havecheck
End if
End If


If canautoenter=False Then FreeHost_moneyNewlog conn,"y","n","n","n","y",isAgnHostSer,moneych,UserName,UserName,UserName,olduser_money,newuser_money,agnusername,agnStmoney,agnEndmoney,supusername,"(独立)(等待入帐)(用户"&UserName&")网上支付支付宝接口订单"&trim(Request("out_trade_no"))&"网站："&SERVER_NAME&"付款人："&buyer_email,"(独立支付接口)(等待入帐)(名下用户"&UserName&")网上支付支付宝接口订单"&trim(Request("out_trade_no"))&"(AG)网站："&SERVER_NAME&"付款人："&buyer_email,whichProduct,pdid,"ali_"&dsNP("ORDERID"),type1,"独立支付",haveget,havecheck


else
olduser_money=dsreg("usermoney")
If Application("NetPaypercent")>0 Then OrderMoney=OrderMoney/(1+Application("NetPaypercent"))
OrderMoney=Round(OrderMoney,2)
moneych=OrderMoney
dsreg("usermoney")=dsreg("usermoney")+OrderMoney
newuser_money=dsreg("usermoney")
UserName=dsreg("username")
dsreg.update

if not isnull(dsreg("kefunow")) then
Set dskefu = Server.CreateObject("ADODB.Recordset")	
	Sql="Select finishmoney from FreeHost.FreeHost_KeFu where kefumd5='"&md5(trim(dsreg("kefunow")))&"'"
	dskefu.Open Sql,conn,1,3
if not dskefu.Eof then
dskefu("finishmoney")=dskefu("finishmoney")+OrderMoney
dim kefu
kefu=dsreg("kefunow")
dskefu.update
end if
dskefu.close
end if

FreeHost_moneyNewlog conn,"y","n","n","n","y",isAgnHostSer,moneych,UserName,UserName,UserName,olduser_money,newuser_money,agnusername,agnStmoney,agnEndmoney,supusername,"网上支付支付宝接口订单"&trim(Request("out_trade_no"))&"网站："&SERVER_NAME&"(N)付款人："&buyer_email,"网上支付支付宝接口订单"&trim(Request("out_trade_no"))&"网站："&SERVER_NAME&"(N)付款人："&buyer_email,whichProduct,pdid,"ali_"&dsNP("ORDERID"),type1,"在线支付",haveget,havecheck
End if
end if


if ef then
FreeHost_oplog dsNP("username"),"信息","支付宝支付出错"&ec
response.write "fail"
Application.lock
Application("alioplock")=false
Application.unlock
response.end
Else

Application.lock
Application("alioplock")=false
Application.unlock

response.write "success"
response.end
end if


















Application.lock
Application("alioplock")=false
Application.unlock

response.write "success"
 End if


'Else
'response.write "fail"
'End If 


 '写文本，方便测试（看网站需求，也可以改成存入数据库）
TOEXCELLR=TOEXCELLR&md5str&"MD5 非同步 结果:"&mysign&"="&request("sign")&"--ResponseTxt:"&ResponseTxt&" "&alipayNotifyURL&" "&key
'set fs= createobject("scripting.filesystemobject") 
'set ts=fs.createtextfile(server.MapPath("Notify_DATA/"&replace(now(),":","")&".txt"),true)

' ts.writeline(TOEXCELLR)
' ts.close
' set ts=Nothing
' set fs=Nothing

Else

Application.lock
Application("alioplock")=false
Application.unlock
response.write "fail,系统已记录你所有信息，110感谢你的入侵尝试。"

End if

'对post传递过来的参数作urldecode编码处理(请不要修改)
Function URLDecode(enStr)
  dim deStr
  dim c,i,v
  deStr=""
  for i=1 to len(enStr)
  c=Mid(enStr,i,1)
  if c="%" then
  v=eval("&h"+Mid(enStr,i+1,2))
  if v<128 then
  deStr=deStr&chr(v)
  i=i+2
  else
  if isvalidhex(mid(enstr,i,3)) then
  if isvalidhex(mid(enstr,i+3,3)) then
  v=eval("&h"+Mid(enStr,i+1,2)+Mid(enStr,i+4,2))
  deStr=deStr&chr(v)
  i=i+5
  else
  v=eval("&h"+Mid(enStr,i+1,2)+cstr(hex(asc(Mid(enStr,i+3,1)))))
  deStr=deStr&chr(v)
  i=i+3 
  end if 
  else 
  destr=destr&c
  end if
  end if
  else
  if c="+" then
  deStr=deStr&" "
  else
  deStr=deStr&c
  end if
  end if
  next
  URLDecode=deStr
  end function

  function isvalidhex(str)
  isvalidhex=true
  str=ucase(str)
  if len(str)<>3 then isvalidhex=false:exit function
  if left(str,1)<>"%" then isvalidhex=false:exit function
  c=mid(str,2,1)
  if not (((c>="0") and (c<="9")) or ((c>="A") and (c<="Z"))) then isvalidhex=false:exit function
  c=mid(str,3,1)
  if not (((c>="0") and (c<="9")) or ((c>="A") and (c<="Z"))) then isvalidhex=false:exit function
  end function

%>