You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

499 lines
22 KiB
C#

using HuizhongLibrary.Common.Configuration;
using HuizhongLibrary.Data;
using HuizhongLibrary.Log;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.IO;
using System.Net;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WxPayAPI
{
/// <summary>
/// 扫码支付模式一回调处理类
/// 接收微信支付后台发送的扫码结果,调用统一下单接口并将下单结果返回给微信支付后台
/// </summary>
public class NativeNotify:Notify
{
public NativeNotify(Page page):base(page)
{
}
public override void ProcessNotify()
{
WxPayData notifyData = GetNotifyData();
ErrorFollow.TraceWrite("notifyData", "", notifyData.ToPrintStr());
//检查openid和product_id是否返回
//appid=wx0a895a6721484fb0<br>attach=test<br>bank_type=CFT<br>cash_fee=1<br>fee_type=CNY<br>is_subscribe=Y<br>mch_id=1438351202<br>nonce_str=0047c34002ef4ac597939d84984e8e9a<br>openid=o6CUIwKBdgyCy9B1xJMxNK8vdWeU<br>out_trade_no=14383512022018012310014931<br>result_code=SUCCESS<br>return_code=SUCCESS<br>sign=2E4C394C780D0C7BFAF2EDF54A73E927<br>time_end=20180123100323<br>total_fee=1<br>trade_type=JSAPI<br>transaction_id=4200000065201801239112746930<br>
int PayState = 0;
string out_trade_no = "";
if (!notifyData.IsSet("openid")|| !notifyData.IsSet("out_trade_no"))
{
PayState = 1;
WxPayData res = new WxPayData();
res.SetValue("return_code", "FAIL");
res.SetValue("return_msg", "回调数据异常");
ErrorFollow.TraceWrite("ProcessNotify", this.GetType().ToString(), "The data WeChat post is error : " + res.ToXml());
// Log.Info(this.GetType().ToString(), "The data WeChat post is error : " + res.ToXml());
try
{
Update_PayLog(out_trade_no, "The data WeChat post is error : " + res.ToXml(), PayState);
}
catch (Exception ex)
{
ErrorFollow.TraceWrite("ProcessNotify", "错误", ex.Message);
}
page.Response.Write(res.ToXml());
page.Response.End();
}
out_trade_no = notifyData.GetValue("out_trade_no").ToString();
//调统一下单接口,获得下单结果
//string openid = notifyData.GetValue("openid").ToString();
//string product_id = notifyData.GetValue("product_id").ToString();
//WxPayData unifiedOrderResult = new WxPayData();
//try
//{
// unifiedOrderResult = UnifiedOrder(openid, product_id);
//}
//catch(Exception ex)//若在调统一下单接口时抛异常,立即返回结果给微信支付后台
//{
// PayState = 1;
// WxPayData res = new WxPayData();
// res.SetValue("return_code", "FAIL");
// res.SetValue("return_msg", "统一下单失败");
// Log.Error(this.GetType().ToString(), "UnifiedOrder failure : " + res.ToXml());
// page.Response.Write(res.ToXml());
// page.Response.End();
//}
////若下单失败,则立即返回结果给微信支付后台
//if (!notifyData.IsSet("appid") || !notifyData.IsSet("mch_id") || !unifiedOrderResult.IsSet("prepay_id"))
//{
// WxPayData res = new WxPayData();
// res.SetValue("return_code", "FAIL");
// res.SetValue("return_msg", "统一下单失败");
// Log.Error(this.GetType().ToString(), "UnifiedOrder failure : " + res.ToXml());
// page.Response.Write(res.ToXml());
// page.Response.End();
//}
// ErrorFollow.TraceWrite("ProcessNotify", "", notifyData.GetValue("result_code").ToString());
if (notifyData.GetValue("result_code").ToString() == "SUCCESS")
{
// ErrorFollow.TraceWrite("ProcessNotify", "支付成功", PayState.ToString());
PayState = 2;//支付成功
try
{
int AppType = Update_PayLog(out_trade_no, "支付成功" + notifyData.ToPrintStr(), PayState);
if (AppType == 1)
{
SendSync(out_trade_no);
}
else if (AppType == 4)
{
SendZZQPYSync(out_trade_no);
}
else if (AppType == 9)
{
SendYTGPay(out_trade_no);
}
else
{
SendTYSync(out_trade_no);
}
}
catch (Exception ex)
{
ErrorFollow.TraceWrite("ProcessNotify", "错误", ex.Message);
}
}
//统一下单成功,则返回成功结果给微信支付后台
WxPayData data = new WxPayData();
data.SetValue("return_code", "SUCCESS");
data.SetValue("return_msg", "OK");
data.SetValue("appid", WxPayConfig.APPID);
data.SetValue("mch_id", WxPayConfig.MCHID);
data.SetValue("nonce_str", WxPayApi.GenerateNonceStr());
//data.SetValue("prepay_id", notifyData.GetValue("prepay_id"));
data.SetValue("result_code", "SUCCESS");
data.SetValue("err_code_des", "OK");
ErrorFollow.TraceWrite("ProcessNotify0", this.GetType().ToString(), "UnifiedOrder send data: " + data.ToXml());
data.SetValue("sign", data.MakeSign());
ErrorFollow.TraceWrite("ProcessNotify", this.GetType().ToString(), "UnifiedOrder success , send data to WeChat : " + data.ToXml());
//out_trade_no
//Log.Info(this.GetType().ToString(), "UnifiedOrder success , send data to WeChat : " + data.ToXml());
page.Response.Write(data.ToXml());
page.Response.End();
}
private WxPayData UnifiedOrder(string openId,string productId)
{
//统一下单
WxPayData req = new WxPayData();
req.SetValue("body", "test");
req.SetValue("attach", "test");
req.SetValue("out_trade_no", WxPayApi.GenerateOutTradeNo());
req.SetValue("total_fee", 1);
req.SetValue("time_start", DateTime.Now.ToString("yyyyMMddHHmmss"));
req.SetValue("time_expire", DateTime.Now.AddMinutes(10).ToString("yyyyMMddHHmmss"));
req.SetValue("goods_tag", "test");
req.SetValue("trade_type", "NATIVE");
req.SetValue("openid", openId);
req.SetValue("product_id", productId);
WxPayData result = WxPayApi.UnifiedOrder(req);
return result;
}
private static DataSet GetPayInfo(string out_trade_no)
{
string tsql = @"
select top 1 a.*,b.Url,c.AppCode,e.OutId from ZZQ_Pay a
inner join JC_Company b on a.CompanyId=b.CompanyId
inner join DL_AppConfing c on a.CompanyId=c.CompanyId
inner join JC_UserInfo e on e.UserId=a.UserId
where a.out_trade_no=@out_trade_no";
Database db = DatabaseFactory.CreateDatabase();
DbCommand cmd = db.GetSqlStringCommand(tsql);
db.AddInParameter(cmd, "@out_trade_no", DbType.String, out_trade_no);
return db.ExecuteDataSet(cmd);
}
private static DataSet GetPayInfoTY(string out_trade_no)
{
string tsql = @"
select top 1 a.*,b.Url,c.AppCode from ZZQ_Pay a
inner join JC_Company b on a.CompanyId=b.CompanyId
inner join DL_AppConfing c on a.CompanyId=c.CompanyId
where a.out_trade_no=@out_trade_no";
Database db = DatabaseFactory.CreateDatabase();
DbCommand cmd = db.GetSqlStringCommand(tsql);
db.AddInParameter(cmd, "@out_trade_no", DbType.String, out_trade_no);
return db.ExecuteDataSet(cmd);
}
public static void SendSms(int UserID, string Title, string SmsContent)
{
if (string.IsNullOrEmpty(SmsContent) == true) return;
string tsql = @"
INSERT INTO [T_MESSAGE]([MESSAGEID],[TITLE],[CONTENT],[MOBILELIST],[ANNOUNCETYPE],[OBJECTTYPE],[IFREGULAR],[REGULARTIME],[SENDTIME],[SIGNNAME],[TEACHERID],[MESSAGETYPE],[IFSEND],MsgID,UserName,PassWord)
select '',@Title,@SmsContent,Mobile,'00','00','N',null,getdate(),'管理员','1','04','N','','',''
from JC_UserMobile
where UserID=@UserID and IsUse=1
";
Database db = DatabaseFactory.CreateDatabase();
DbCommand cmd = db.GetSqlStringCommand(tsql);
db.AddInParameter(cmd, "@UserID", DbType.Int32, UserID);
db.AddInParameter(cmd, "@Title", DbType.String, Title);
db.AddInParameter(cmd, "@SmsContent", DbType.String, SmsContent);
db.ExecuteNonQuery(cmd);
}
#region 返回支付结果
public static int Update_PayLog(string out_trade_no, string PayResult, int PayState)
{
// string SetupPath = AppDomain.CurrentDomain.BaseDirectory + "Web.config";
// string PayApp = ConfigurationSourceSection.LoadXml_Attribute(SetupPath, "PayApp");
string tsql = "";
//if (PayApp == "1")
//{
tsql = @"
declare @PayMonth int ,@UserId int,@CompanyId int,@PayApp int,@UserName nvarchar(50),@LastPayState int
set @PayApp=0
select @PayMonth=Num,@UserId=UserId,@CompanyId=CompanyId,@PayApp=AppType,@UserName=UserName,@LastPayState=PayState from ZZQ_Pay
where out_trade_no=@out_trade_no
if (@PayApp = 1) --数字校园
begin
if @PayState=2 --支付成功
begin
if(@LastPayState!=2 or @LastPayState is NULL)
begin
if (select count(0) from JC_UserWeiXin where UserId=@UserId and UserName=@UserName and VipState=1 and VipEndDate>getdate())>0
Update JC_UserWeiXin set VipState=1,[VipEndDate]=(select DATEADD(MONTH,@PayMonth,VipEndDate)) where UserId=@UserId and CompanyId=@CompanyId and UserName=@UserName
else
Update JC_UserWeiXin set VipState=1,[VipEndDate]=(select DATEADD(MONTH,@PayMonth,GETDATE())) where UserId=@UserId and CompanyId=@CompanyId and UserName=@UserName
end
end
Update ZZQ_Pay set PayState=@PayState,FeeBack=@PayResult,PayDate=getdate() where out_trade_no=@out_trade_no
--Update [BF_Log] set [Remark]=@PayResult,ReturnDate=getdate() where out_trade_no=@out_trade_no
end
else if (@PayApp = 4) --周周清培优
begin
if @PayState=2 --支付成功
begin
if (select count(0) from JC_UserInfo where UserId=@UserId and VipState=1 and VipEndDate>getdate())>0
Update JC_UserInfo set VipState=1,[VipEndDate]=(select DATEADD(MONTH,@PayMonth,VipEndDate)) where UserId=@UserId and CompanyId=@CompanyId
else
Update JC_UserInfo set VipState=1,[VipEndDate]=(select DATEADD(MONTH,@PayMonth,GETDATE())) where UserId=@UserId and CompanyId=@CompanyId
end
Update ZZQ_Pay set PayState=@PayState,FeeBack=@PayResult,PayDate=getdate() where out_trade_no=@out_trade_no
--Update [BF_Log] set [Remark]=@PayResult,ReturnDate=getdate() where out_trade_no=@out_trade_no
end
else if (@PayApp = 2) --班费
begin
if @PayState=2 --支付成功
begin
Update BF_BuyUser set FeeState=2,FeeBack=@PayResult,PayDate=getdate() where out_trade_no=@out_trade_no
end
else --支付失败
begin
Update BF_BuyUser set FeeState=@PayState,FeeBack=@PayResult,PayDate=getdate() where out_trade_no=@out_trade_no
end
Update [BF_Log] set [Remark]=@PayResult,ReturnDate=getdate() where out_trade_no=@out_trade_no
end
else if (@PayApp = 3) --周周清
begin
if @PayState=2 --支付成功
begin
Update ZZQ_Pay set PayState=2,FeeBack=@PayResult,PayDate=getdate() where out_trade_no=@out_trade_no
end
else --支付失败
begin
Update ZZQ_Pay set PayState=@PayState,FeeBack=@PayResult,PayDate=getdate() where out_trade_no=@out_trade_no
end
end
else if (@PayApp = 9) --芸台购
begin
if @PayState=2 --支付成功
begin
Update ZZQ_Pay set PayState=2,FeeBack=@PayResult,PayDate=getdate() where out_trade_no=@out_trade_no
INSERT INTO [YTG_Order]
(
[paycode]
,[state]
,[paydate],remark
)
VALUES (@out_trade_no,@PayState,getdate(),@PayResult)
end
else --支付失败
begin
Update ZZQ_Pay set PayState=@PayState,FeeBack=@PayResult,PayDate=getdate() where out_trade_no=@out_trade_no
INSERT INTO [YTG_Order]
(
[paycode]
,[state]
,[paydate],remark
)
VALUES (@out_trade_no,@PayState,getdate(),@PayResult)
end
end
else
begin
Update ZZQ_Pay set PayState=@PayState,FeeBack=@PayResult,PayDate=getdate() where out_trade_no=@out_trade_no
end
select PayApp=@PayApp
";
// }
// if (PayApp != "1")
// {
// tsql = @"if @PayState=2 --支付成功
//begin
//Update XSBD_StudentInfo set IsPay=@PayState where out_trade_no=@out_trade_no
//end
//else --支付失败
//begin
//Update XSBD_StudentInfo set IsPay=@PayState where out_trade_no=@out_trade_no
//end
//Update [XSBD_PayLog] set [PayResult]=@PayResult,ReturnDate=getdate(),PayState=@PayState where out_trade_no=@out_trade_no
//select 0
//";
// }
// if (PayApp == "8")
// {
// tsql = @"
//if @PayState=2 --支付成功
//begin
//Update ZZQ_Pay set PayState=2,FeeBack=@PayResult,PayDate=getdate() where out_trade_no=@out_trade_no
//update YX_UserPay set State=2,PayDate=getdate() where out_trade_no=@out_trade_no
//declare @PayMonth int ,@UserId int
//select @PayMonth=[Month],@UserId=UserId from YX_UserPay
//where out_trade_no=@out_trade_no
//Update[ZZQ_Student] set
//[VipState]=1 ,
//[VipEndDate]=(select DATEADD(MONTH,@PayMonth,GETDATE()))
//where UserId=@UserId
//end
//else --支付失败
//begin
//Update ZZQ_Pay set PayState=@PayState,FeeBack=@PayResult,PayDate=getdate() where out_trade_no=@out_trade_no
//update YX_UserPay set State=@PayState,PayDate=getdate() where out_trade_no=@out_trade_no
//end
////--[VipEndDate]=(select DATEADD(MONTH,@PayMonth,ISNULL(
////--(select top 1 VipEndDate from ZZQ_Student
////--where VipEndDate>GETDATE() and UserId=@UserId and VipState=1)
////--,GETDATE())))
//select 8
//";
// }
Database db = DatabaseFactory.CreateDatabase();
DbCommand cmd = db.GetSqlStringCommand(tsql);
db.AddInParameter(cmd, "@out_trade_no", DbType.String, out_trade_no);
db.AddInParameter(cmd, "@PayResult", DbType.String, PayResult);
db.AddInParameter(cmd, "@PayState", DbType.Int32, PayState);
//db.ExecuteNonQuery(cmd);
return Convert.ToInt32(db.ExecuteScalar(cmd));
//if (PayApp == "1"||PayApp == "3")
//{
// SendNotice(out_trade_no);
//}
}
#endregion
public static void SendSync(string out_trade_no)
{
try
{
DataTable dtPay = GetPayInfo(out_trade_no).Tables[0];
if (dtPay.Rows.Count > 0)
{
string SetupPath = AppDomain.CurrentDomain.BaseDirectory + "Web.config";
//string Mess = HuizhongLibrary.Common.Configuration.ConfigurationSourceSection.LoadXml_Attribute(SetupPath, "PayMess");
//SendSms(Convert.ToInt32(dtPay.Rows[0]["UserId"]), "支付成功通知", Mess);
string _url = dtPay.Rows[0]["Url"] + "/OuterService/GetInfo.ashx?Ver=1.0&UserCode=" + dtPay.Rows[0]["AppCode"] + "&Method=UpdatePay&UserId=" + dtPay.Rows[0]["OutId"] + "&PayNum=" + dtPay.Rows[0]["Num"] + "&PayMoney=" + dtPay.Rows[0]["PayMoney"] + "&UserName=" + dtPay.Rows[0]["UserName"];
//var request = (HttpWebRequest)WebRequest.Create(_url);
//request.Method = "GET";
//request.ContentType = "text/html;charset=UTF-8";
//HttpWebResponse response = (HttpWebResponse)request.GetResponse();
//Stream myResponseStream = response.GetResponseStream();
//StreamReader myStreamReader = new StreamReader(myResponseStream, System.Text.Encoding.UTF8);
//string retString = myStreamReader.ReadToEnd();
//System.Web.Script.Serialization.JavaScriptSerializer json = new System.Web.Script.Serialization.JavaScriptSerializer();
string error = "";
string str2 = HuizhongLibrary.CustomIO.HttpRequest(_url, "Get", "text/html;charset=UTF-8", null, null, null, out error);
//RuBianInfo model = json.Deserialize<RuBianInfo>(retString);
//return model;
}
}
catch (Exception ex)
{
ErrorFollow.TraceWrite("SendSync", out_trade_no, ex.Message);
}
}
public static void SendTYSync(string out_trade_no)
{
try
{
DataTable dtPay = GetPayInfoTY(out_trade_no).Tables[0];
if (dtPay.Rows.Count > 0)
{
string SetupPath = AppDomain.CurrentDomain.BaseDirectory + "Web.config";
//string Mess = HuizhongLibrary.Common.Configuration.ConfigurationSourceSection.LoadXml_Attribute(SetupPath, "PayMess");
//SendSms(Convert.ToInt32(dtPay.Rows[0]["UserId"]), "支付成功通知", Mess);
string _url = dtPay.Rows[0]["Url"] + "/OuterService/GetInfo.ashx?Ver=1.0&UserCode=" + dtPay.Rows[0]["AppCode"] + "&Method=UpdateTYPay&out_trade_no=" + dtPay.Rows[0]["out_trade_no"] + "&AppType=" + dtPay.Rows[0]["AppType"] + "&PayType=" + dtPay.Rows[0]["PayType"] + "&Amount=" + dtPay.Rows[0]["PayMoney"];
ErrorFollow.TraceWrite("SendTYSync", out_trade_no, _url);
var request = (HttpWebRequest)WebRequest.Create(_url);
request.Method = "GET";
request.ContentType = "text/html;charset=UTF-8";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream myResponseStream = response.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myResponseStream, System.Text.Encoding.UTF8);
string retString = myStreamReader.ReadToEnd();
System.Web.Script.Serialization.JavaScriptSerializer json = new System.Web.Script.Serialization.JavaScriptSerializer();
//RuBianInfo model = json.Deserialize<RuBianInfo>(retString);
//return model;
}
}
catch (Exception ex)
{
ErrorFollow.TraceWrite("SendTYSync", out_trade_no, ex.Message);
}
}
public static void SendZZQPYSync(string out_trade_no)
{
try
{
DataTable dtPay = GetPayInfo(out_trade_no).Tables[0];
if (dtPay.Rows.Count > 0)
{
string SetupPath = AppDomain.CurrentDomain.BaseDirectory + "Web.config";
string Mess = HuizhongLibrary.Common.Configuration.ConfigurationSourceSection.LoadXml_Attribute(SetupPath, "PayMess");
SendSms(Convert.ToInt32(dtPay.Rows[0]["UserId"]), "支付成功通知", Mess);
string _url = dtPay.Rows[0]["Url"] + "/OuterService/GetInfo.ashx?Ver=1.0&UserCode=" + dtPay.Rows[0]["AppCode"] + "&Method=UpdatePay&UserId=" + dtPay.Rows[0]["OutId"] + "&PayNum=" + dtPay.Rows[0]["Num"] + "&PayMoney=" + dtPay.Rows[0]["PayMoney"];
var request = (HttpWebRequest)WebRequest.Create(_url);
request.Method = "GET";
request.ContentType = "text/html;charset=UTF-8";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream myResponseStream = response.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myResponseStream, System.Text.Encoding.UTF8);
string retString = myStreamReader.ReadToEnd();
System.Web.Script.Serialization.JavaScriptSerializer json = new System.Web.Script.Serialization.JavaScriptSerializer();
//RuBianInfo model = json.Deserialize<RuBianInfo>(retString);
//return model;
}
}
catch (Exception ex)
{
ErrorFollow.TraceWrite("SendZZQPYSync", out_trade_no, ex.Message);
}
}
public static void SendYTGPay(string out_trade_no)
{
try
{
string SetupPath = AppDomain.CurrentDomain.BaseDirectory + "Web.config";
string _url ="http://book.huizsoft.com/OuterService/GetInfo.ashx?Ver=1.0&UserCode=test&Method=UpdateYTGPay&PayCode=" + out_trade_no;
var request = (HttpWebRequest)WebRequest.Create(_url);
request.Method = "GET";
request.ContentType = "text/html;charset=UTF-8";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream myResponseStream = response.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myResponseStream, System.Text.Encoding.UTF8);
string retString = myStreamReader.ReadToEnd();
}
catch (Exception ex)
{
ErrorFollow.TraceWrite("SendYTGPay", out_trade_no, ex.Message);
}
}
}
}