加签:微信金额的单位是分,一定要注意;
/// <summary>
/// 微信加签
/// </summary>
/// <param name="TotalPrice">传入金额</param>
/// <returns></returns>
public Dictionary<string, object> GetWePaySign(string TotalPrice, int UserId, string OrderNo, int OrderStyle)
{
Dictionary<string, object> myDic = new Dictionary<string, object>();
string trade_no = OrderNo + DateTime.Now.ToString("yyyyMMddHHmmss");
try
{
#region 微信支付 基础配置信息
string wx_appid = WeipayConfig.APPID;//微信开放平台审核通过的应用
string wx_mch_id = WeipayConfig.MCHID; //微信支付分配的商户号
string wx_nonce_str = trade_no;//随机字符串,不长于32位
string aa = "APP名字";////商品描述交易字段格式根据不同的应用场景按照以下格式:APP——需传入应用市场上的APP名字-实际商品名称,天天爱消除-游戏充值。
string strcode = aa;
byte[] buffer = Encoding.UTF8.GetBytes(strcode);
string wx_body = Encoding.UTF8.GetString(buffer, 0, buffer.Length);
string wx_out_trade_no = OrderNo;//订单号
string wx_total_fee = (Convert.ToDecimal(TotalPrice) * 100).ToString();//;//订单总金额,单位为分,详见支付金额
string wx_spbill_create_ip = "用户端实际ip0.0.0.0";//// 用户端实际ip
string wx_notify_url = WeipayConfig.NOTIFY_URL;////接收微信支付异步通知回调地址,通知url必须为直接可访问的url,不能携带参数。
string wx_trade_type = "APP";////支付类型
string wx_time_start = DateTime.Now.ToString("yyyyMMddHHmmss");
string wx_time_expire = DateTime.Now.AddMinutes(1).ToString("yyyyMMddHHmmss");
#endregion
var dic = new Dictionary<string, string> {
{"appid", wx_appid},
{"attach",UserId.ToString()+"-"+ OrderStyle.ToString()},
{"mch_id", wx_mch_id},
{"nonce_str", wx_nonce_str},
{"body", wx_body},
{"out_trade_no", wx_out_trade_no},//商户自己的订单号码
{"total_fee", wx_total_fee},
{"spbill_create_ip",wx_spbill_create_ip},//服务器的IP地址
{"notify_url", wx_notify_url},//异步通知的地址,不能带参数
{"trade_type", wx_trade_type},
{"time_start", wx_time_start},
{"time_expire", wx_time_expire},
};
//加入签名
dic.Add("sign", GetSignString(dic));
var sb = new StringBuilder();
sb.Append("<xml>");
foreach (var d in dic)
{
sb.Append("<" + d.Key + ">" + d.Value + "</" + d.Key + ">");
}
sb.Append("</xml>"); var xml = new XmlDocument();
// xml.LoadXml(GetPostString("https://api.mch.weixin.qq.com/pay/unifiedorder", sb.ToString()));
CookieCollection coo = new CookieCollection();
Encoding en = Encoding.GetEncoding("UTF-8");
HttpWebResponse response = CreatePostHttpResponse("https://api.mch.weixin.qq.com/pay/unifiedorder", sb.ToString(), en);
//打印返回值
Stream stream = response.GetResponseStream(); //获取响应的字符串流
StreamReader sr = new StreamReader(stream); //创建一个stream读取流
string html = sr.ReadToEnd(); //从头读到尾,放到字符串html
//Console.WriteLine(html);
xml.LoadXml(html);
var root = xml.DocumentElement;
if (root.SelectSingleNode("/xml/return_code").InnerText != "SUCCESS")
{
myDic.Add("Flag", 3);
myDic.Add("Message", "加签失败");
}
else
{
if (root.SelectSingleNode("/xml/return_msg").InnerText != "OK")
{
myDic.Add("Flag", 3);
myDic.Add("Message", "加签失败");
}
else
{
var res = new Dictionary<string, string>
{
{"appid", wx_appid},
{"partnerid", wx_mch_id},
{"prepayid", root.SelectSingleNode("/xml/prepay_id").InnerText},
{"package", "Sign=WXPay"},
{"noncestr", dic["nonce_str"]},
{"timestamp", (Convert.ToInt32((DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalSeconds)).ToString()}
};
myDic.Add("Flag", 2);
myDic.Add("Message", "加签成功");
myDic.Add("OpenID", res["appid"]);
myDic.Add("Partnerid", res["partnerid"]);
myDic.Add("Prepayid", res["prepayid"]);
myDic.Add("Noncestr", res["noncestr"]);
myDic.Add("Timestamp", res["timestamp"]);
myDic.Add("Sign", GetSignString(res));
}
}
}
#region 结果输出
catch (Exception)
{
myDic.Add("Flag", 3);
myDic.Add("Message", "加签异常");
}
return myDic;
#endregion
}
验签:
public string WeiPayResultAsync()
{
string xmlData = getPostStr();//获取请求数据
SysLog.Log("", "", "=========微信回调接口返回参数:" + xmlData);
if (xmlData == "")
{
return "false";
}
else
{
var dic = new Dictionary<string, string> { { "return_code", "SUCCESS" }, { "return_msg", "OK" } };
var sb = new StringBuilder();
sb.Append("<xml>");
foreach (var d in dic)
{
sb.Append("<" + d.Key + ">" + d.Value + "</" + d.Key + ">");
}
sb.Append("</xml>");
//把数据重新返回给客户端
DataSet ds = new DataSet();
StringReader stram = new StringReader(xmlData);
XmlTextReader datareader = new XmlTextReader(stram);
ds.ReadXml(datareader);
if (ds.Tables[0].Rows[0]["return_code"].ToString() == "SUCCESS")
{
string wx_appid = "";//微信开放平台审核通过的应用APPID
string wx_mch_id = "";//微信支付分配的商户号
string wx_attach = "";//附加参数
string wx_nonce_str = "";// 随机字符串,不长于32位
string wx_sign = "";//签名,详见签名算法
string wx_result_code = "";//SUCCESS/FAIL
string wx_return_code = "";
string wx_openid = "";//用户在商户appid下的唯一标识
string wx_is_subscribe = "";//用户是否关注公众账号,Y-关注,N-未关注,仅在公众账号类型支付有效
string wx_trade_type = "";// APP
string wx_bank_type = "";// 银行类型,采用字符串类型的银行标识,银行类型见银行列表
string wx_fee_type = "";// 货币类型,符合ISO4217标准的三位字母代码,默认人民币:CNY,其他值列表详见货币类型
string wx_transaction_id = "";//微信支付订单号
string wx_out_trade_no = "";//商户系统的订单号,与请求一致。
string wx_time_end = "";// 支付完成时间,格式为yyyyMMddHHmmss,如2009年12月25日9点10分10秒表示为20091225091010。其他详见时间规则
int wx_total_fee = -1;// 订单总金额,单位为分
int wx_cash_fee = -1;//现金支付金额订单现金支付金额,详见支付金额
#region 数据解析
//列 是否存在
string signstr = "";//需要前面的字符串
//wx_appid
if (ds.Tables[0].Columns.Contains("appid"))
{
wx_appid = ds.Tables[0].Rows[0]["appid"].ToString();
if (!string.IsNullOrEmpty(wx_appid))
{
signstr += "appid=" + wx_appid;
}
}
//wx_attach
if (ds.Tables[0].Columns.Contains("attach"))
{
wx_attach = ds.Tables[0].Rows[0]["attach"].ToString();
if (!string.IsNullOrEmpty(wx_attach))
{
signstr += "&attach=" + wx_attach;
}
}
//wx_bank_type
if (ds.Tables[0].Columns.Contains("bank_type"))
{
wx_bank_type = ds.Tables[0].Rows[0]["bank_type"].ToString();
if (!string.IsNullOrEmpty(wx_bank_type))
{
signstr += "&bank_type=" + wx_bank_type;
}
}
//wx_cash_fee
if (ds.Tables[0].Columns.Contains("cash_fee"))
{
wx_cash_fee = Convert.ToInt32(ds.Tables[0].Rows[0]["cash_fee"].ToString());
signstr += "&cash_fee=" + wx_cash_fee;
}
//wx_fee_type
if (ds.Tables[0].Columns.Contains("fee_type"))
{
wx_fee_type = ds.Tables[0].Rows[0]["fee_type"].ToString();
if (!string.IsNullOrEmpty(wx_fee_type))
{
signstr += "&fee_type=" + wx_fee_type;
}
}
//wx_is_subscribe
if (ds.Tables[0].Columns.Contains("is_subscribe"))
{
wx_is_subscribe = ds.Tables[0].Rows[0]["is_subscribe"].ToString();
if (!string.IsNullOrEmpty(wx_is_subscribe))
{
signstr += "&is_subscribe=" + wx_is_subscribe;
}
}
//wx_mch_id
if (ds.Tables[0].Columns.Contains("mch_id"))
{
wx_mch_id = ds.Tables[0].Rows[0]["mch_id"].ToString();
if (!string.IsNullOrEmpty(wx_mch_id))
{
signstr += "&mch_id=" + wx_mch_id;
}
}
//wx_nonce_str
if (ds.Tables[0].Columns.Contains("nonce_str"))
{
wx_nonce_str = ds.Tables[0].Rows[0]["nonce_str"].ToString();
if (!string.IsNullOrEmpty(wx_nonce_str))
{
signstr += "&nonce_str=" + wx_nonce_str;
}
}
//wx_openid
if (ds.Tables[0].Columns.Contains("openid"))
{
wx_openid = ds.Tables[0].Rows[0]["openid"].ToString();
if (!string.IsNullOrEmpty(wx_openid))
{
signstr += "&openid=" + wx_openid;
}
}
//wx_out_trade_no
if (ds.Tables[0].Columns.Contains("out_trade_no"))
{
wx_out_trade_no = ds.Tables[0].Rows[0]["out_trade_no"].ToString();
if (!string.IsNullOrEmpty(wx_out_trade_no))
{
signstr += "&out_trade_no=" + wx_out_trade_no;
}
}
//wx_result_code
if (ds.Tables[0].Columns.Contains("result_code"))
{
wx_result_code = ds.Tables[0].Rows[0]["result_code"].ToString();
if (!string.IsNullOrEmpty(wx_result_code))
{
signstr += "&result_code=" + wx_result_code;
}
}
//wx_result_code
if (ds.Tables[0].Columns.Contains("return_code"))
{
wx_return_code = ds.Tables[0].Rows[0]["return_code"].ToString();
if (!string.IsNullOrEmpty(wx_return_code))
{
signstr += "&return_code=" + wx_return_code;
}
}
//wx_sign
if (ds.Tables[0].Columns.Contains("sign"))
{
wx_sign = ds.Tables[0].Rows[0]["sign"].ToString();
}
//wx_time_end
if (ds.Tables[0].Columns.Contains("time_end"))
{
wx_time_end = ds.Tables[0].Rows[0]["time_end"].ToString();
if (!string.IsNullOrEmpty(wx_time_end))
{
signstr += "&time_end=" + wx_time_end;
}
}
//wx_total_fee
if (ds.Tables[0].Columns.Contains("total_fee"))
{
wx_total_fee = Convert.ToInt32(ds.Tables[0].Rows[0]["total_fee"].ToString());
signstr += "&total_fee=" + wx_total_fee;
}
//wx_trade_type
if (ds.Tables[0].Columns.Contains("trade_type"))
{
wx_trade_type = ds.Tables[0].Rows[0]["trade_type"].ToString();
if (!string.IsNullOrEmpty(wx_trade_type))
{
signstr += "&trade_type=" + wx_trade_type;
}
}
//wx_transaction_id
if (ds.Tables[0].Columns.Contains("transaction_id"))
{
wx_transaction_id = ds.Tables[0].Rows[0]["transaction_id"].ToString();
if (!string.IsNullOrEmpty(wx_transaction_id))
{
signstr += "&transaction_id=" + wx_transaction_id;
}
}
#endregion
//追加key 密钥
signstr += "&key=" + WeipayConfig.KEY;
//签名正确
if (wx_sign == Config.Md5Hash(signstr))
{
//验签成功
return "true";
}
}
else
{
// 返回信息,如非空,为错误原因 签名失败 参数格式校验错误
return "fail";
}
return "fail";
}
}
本文详细介绍了微信支付的加签过程,包括如何使用微信支付的基础配置信息进行加签,以及加签后的数据处理。同时,文章还讲解了如何对微信支付的回调进行验签,确保交易的安全性和准确性。
699

被折叠的 条评论
为什么被折叠?



