public class WXPayBl
{
WXPayObject WXPayObj = null;
ExpressObject ExpressObj = null;
#region 调用统一下单接口
public string WXPay(BaseObject bobj, string jsonStr) {
try
{
//第二次解析对象
WXPayObj = (WXPayObject)JsonConvert.DeserializeObject(bobj.Content.ToString(), typeof(WXPayObject));
System.Random Random = new System.Random();
var dic = new Dictionary < string, string> {
{“appid”, ConfigurationManager.AppSettings[“AppID”]}, //小程序ID
{“mch_id”, ConfigurationManager.AppSettings[“mch_id”]}, //商户号
{“nonce_str”, GetRandomString(32)}, //随机字符串
{“body”, WXPayObj.body}, //商品描述
{“out_trade_no”, DateTime.Now.ToString(“yyyyMMddHHmmssfff”) + Random.Next(999).ToString()}, //商户订单号
{ “total_fee”, WXPayObj.total_fee}, //标价金额
{“spbill_create_ip”, WXPayObj.spbill_create_ip}, //终端IP
{“notify_url”, WXPayObj.notify_url}, //通知地址
{“trade_type”, “JSAPI”}, //交易类型
{“openid”, WXPayObj.openid}, //OpenID
};
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();
string url = string.Format("https://api.mch.weixin.qq.com/pay/unifiedorder");
string Result = ToolsPost.SendDataPost(url,sb.ToString());
DataSet ds = new DataSet();
StringReader stram = new StringReader(Result);
XmlTextReader reader = new XmlTextReader(stram);
ds.ReadXml(reader);
string return_code = ds.Tables[0].Rows[0]["return_code"].ToString();
//统一下单返回状态码
if (return_code.ToUpper() == "SUCCESS")
{
//业务结果
string result_code = ds.Tables[0].Rows[0]["result_code"].ToString();
if (result_code.ToUpper() == "SUCCESS")
{
var res = new Dictionary<string, string>
{
{"appId", ConfigurationManager.AppSettings["AppID"]},
{"timeStamp", GetTimeStamp()},
{"nonceStr", dic["nonce_str"]},
{"package", "prepay_id="+ds.Tables[0].Rows[0]["prepay_id"].ToString()},
{"signType", "MD5"}
};
//在服务器上签名
res.Add("paySign", GetSignString(res));
string signapp = JsonConvert.SerializeObject(res);
return ErrorSelect.RetObj("0", "成功", (JObject)JsonConvert.DeserializeObject(signapp));
}
else{
return ErrorSelect.RetObj("-1", "通信成功,获取订单失败", null);
}
}
else {
return ErrorSelect.RetObj("-1", "微信统一下单失败", null);
}
//string json = Newtonsoft.Json.JsonConvert.SerializeXmlNode(xml);
//return ErrorSelect.RetObj("0", "成功", (JObject)JsonConvert.DeserializeObject(json));
}
catch (Exception)
{
return ErrorSelect.RetObj("-1", "系统错误", null);
}
}
#endregion
#region 生成随机字符串
public static string GetRandomString(int CodeCount)
{
string allChar = "1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,i,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z";
string[] allCharArray = allChar.Split(',');
string RandomCode = "";
int temp = -1;
Random rand = new Random();
for (int i = 0; i < CodeCount; i++)
{
if (temp != -1)
{
rand = new Random(temp * i * ((int)DateTime.Now.Ticks));
}
int t = rand.Next(allCharArray.Length - 1);
while (temp == t)
{
t = rand.Next(allCharArray.Length - 1);
}
temp = t;
RandomCode += allCharArray[t];
}
return RandomCode;
}
#endregion
#region 签名
public string GetSignString(Dictionary<string, string> dic)
{
string key = ConfigurationManager.AppSettings["key"].ToString(); //商户平台 API安全里面设置的KEY
//排序
dic = dic.OrderBy(d => d.Key).ToDictionary(d => d.Key, d => d.Value);
//连接字段
var sign = dic.Aggregate("", (current, d) => current + (d.Key + "=" + d.Value + "&"));
sign += "key=" + key;
//MD5
// sign = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sign, "MD5").ToUpper();
System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
sign = BitConverter.ToString(md5.ComputeHash(Encoding.UTF8.GetBytes(sign))).Replace("-", null);
return sign;
}
#endregion
#region 时间戳
public static string GetTimeStamp()
{
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
return Convert.ToInt64(ts.TotalSeconds).ToString();
}
#endregion
}