微信端HTML页面下单事件:
- document.getElementById('btn-wxpay')addEventListener('tap', function (e) {
-
- $.post('/Orders/Create', orderdata, function(result){
-
- if (result.status == 'success') {
-
- WeixinJSBridge.invoke('getBrandWCPayRequest', JSON.parse(result.data), function (res) {
-
- if (res.err_msg == 'get_brand_wcpay_request:ok') {
- window.location.href = '/Orders/CreateSuccess/' + result.orderId;
- } else {
-
- if (res.err_msg == 'get_brand_wcpay_request:cancel') {
- alert('支付过程中用户取消');
- } else if (res.err_msg == 'get_brand_wcpay_request:fail') {
- alert('支付失败');
- } else {
- alert(res.err_msg);
- }
- window.location.href = '/Orders/Details/' + result.orderId;
- }
- });
- }else{
-
- alert(result.error);
- }
- });
- }
document.getElementById('btn-wxpay')addEventListener('tap', function (e) {
//创建订单
$.post('/Orders/Create', orderdata, function(result){
//创建订单成功
if (result.status == 'success') {
//开始调用微信JS API支付接口
WeixinJSBridge.invoke('getBrandWCPayRequest', JSON.parse(result.data), function (res) {
//支付成功,重定向只支付页面
if (res.err_msg == 'get_brand_wcpay_request:ok') {
window.location.href = '/Orders/CreateSuccess/' + result.orderId;
} else {
//支付失败,提示错误原因,重定向至订单详情页面
if (res.err_msg == 'get_brand_wcpay_request:cancel') {
alert('支付过程中用户取消');
} else if (res.err_msg == 'get_brand_wcpay_request:fail') {
alert('支付失败');
} else {
alert(res.err_msg);
}
window.location.href = '/Orders/Details/' + result.orderId;
}
});
}else{
//创建订单失败,提示错误
alert(result.error);
}
});
}
服务端对应处理模块:
-
- public ActionResult Create(OrderCreateViewModel model){
- try{
- using(var db = new MyDbEntities()){
- db.Orders.Add(new Order(){ Name = model.Name, Weight = model.Weight, OrderTotal = model.OrderTotal, OrderStatus = WaitBuyerPay, Gateway = 'wxpay' });
- db.SaveChanges();
- return Json(new { status = "success", orderId = order.OrderId, data = GetJsBrandWCPayRequestApiParameters(order.Name, order.Name, (int)(order.OrderTotal * 100), 'openId')});
- }
- }catch (Exception ex){
- return Json(new { status = "error", error = ex.Message });
- }
- }
-
- public string GetJsBrandWCPayRequestApiParameters(string body, string out_trade_no, int total_fee, string openid){
- var parameters = new Dictionary<string string="">();
- parameters.Add("appId", 'wx0000000000000000');
- parameters.Add("timeStamp", 'timeStamp');
- parameters.Add("nonceStr", 'nonceStr');
-
- parameters.Add("package", string.Format("prepay_id={0}", GetPrepayId('wx0000000000000000', '0000000000', '000000000000000', 'nonceStr', body, out_trade_no, total_fee, openid)));
- parameters.Add("signType", "MD5");
- parameters.Add("paySign", GetPaySign(parameters, '000000000000000'));
- return JsonConvert.SerializeObject(parameters);
- }
-
- public static string GetPrepayId(string appId, string mchId, string mchKey, string nonceStr, string body, string out_trade_no, int total_fee, string openid){
- HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("https://api.mch.weixin.qq.com/pay/unifiedorder");
- myRequest.Method = "POST";
- myRequest.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
- myRequest.Accept = "application/json";
- var formQuery = GetUnifiedOrderApiParameters(appId, mchId, mchKey, nonceStr, body, out_trade_no, total_fee, openid);
- using (var sw = new StreamWriter(myRequest.GetRequestStream())){
- sw.Write(formQuery);
- }
- string responseText = string.Empty;
- using (HttpWebResponse response = (HttpWebResponse)myRequest.GetResponse()){
- using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8)){
- responseText = reader.ReadToEnd().ToString();
- }
- }
- var doc = XDocument.Parse(responseText);
- if (doc.Root.Element("return_code").Value == "FAIL" || doc.Root.Element("result_code").Value == "FAIL"){
- if (doc.Root.Element("err_code") != null)
- throw new WeixinPayException(doc.Root.Element("err_code").Value, doc.Root.Element("err_code_des").Value);
- else
- throw new Exception(doc.Root.Element("return_msg").Value);
- }else{
- return doc.Root.Element("prepay_id").Value;
- }
- }
- </string>
//创建订单,同时对订单进行预支付
public ActionResult Create(OrderCreateViewModel model){
try{
using(var db = new MyDbEntities()){
db.Orders.Add(new Order(){ Name = model.Name, Weight = model.Weight, OrderTotal = model.OrderTotal, OrderStatus = WaitBuyerPay, Gateway = 'wxpay' });
db.SaveChanges();
return Json(new { status = "success", orderId = order.OrderId, data = GetJsBrandWCPayRequestApiParameters(order.Name, order.Name, (int)(order.OrderTotal * 100), 'openId')});
}
}catch (Exception ex){
return Json(new { status = "error", error = ex.Message });
}
}
//生成微信JS API支付接口参数
public string GetJsBrandWCPayRequestApiParameters(string body, string out_trade_no, int total_fee, string openid){
var parameters = new Dictionary<string string="">();
parameters.Add("appId", 'wx0000000000000000');
parameters.Add("timeStamp", 'timeStamp');
parameters.Add("nonceStr", 'nonceStr');
//获取预支付订单号
parameters.Add("package", string.Format("prepay_id={0}", GetPrepayId('wx0000000000000000', '0000000000', '000000000000000', 'nonceStr', body, out_trade_no, total_fee, openid)));
parameters.Add("signType", "MD5");
parameters.Add("paySign", GetPaySign(parameters, '000000000000000'));
return JsonConvert.SerializeObject(parameters);
}
//获取预支付订单号
public static string GetPrepayId(string appId, string mchId, string mchKey, string nonceStr, string body, string out_trade_no, int total_fee, string openid){
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("https://api.mch.weixin.qq.com/pay/unifiedorder");
myRequest.Method = "POST";
myRequest.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
myRequest.Accept = "application/json";
var formQuery = GetUnifiedOrderApiParameters(appId, mchId, mchKey, nonceStr, body, out_trade_no, total_fee, openid);
using (var sw = new StreamWriter(myRequest.GetRequestStream())){
sw.Write(formQuery);
}
string responseText = string.Empty;
using (HttpWebResponse response = (HttpWebResponse)myRequest.GetResponse()){
using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8)){
responseText = reader.ReadToEnd().ToString();
}
}
var doc = XDocument.Parse(responseText);
if (doc.Root.Element("return_code").Value == "FAIL" || doc.Root.Element("result_code").Value == "FAIL"){
if (doc.Root.Element("err_code") != null)
throw new WeixinPayException(doc.Root.Element("err_code").Value, doc.Root.Element("err_code_des").Value);
else
throw new Exception(doc.Root.Element("return_msg").Value);
}else{
return doc.Root.Element("prepay_id").Value;
}
}
</string>
通用通知接口处理模块:
- public ActionResult Notify()
- {
-
- var xml = System.Text.Encoding.UTF8.GetString(Request.BinaryRead(Request.TotalBytes));
- if (!string.IsNullOrEmpty(xml))
- {
-
- var doc = XDocument.Parse(xml);
- var originalSign = doc.Root.Element("sign").Value;
- var parameters = doc.Root.Elements().Where(m => m.Name != "sign").ToDictionary(m => m.Name.LocalName, m => m.Value);
-
- var sign = GetPaySign(parameters, "MchKey");
- var returnDic = new Dictionary<string, string>();
- if (sign != originalSign)
- {
- Log.Error("签名失败:" + String.Join(";", parameters.Select(m => m.Key + ":" + m.Value).ToArray()));
- returnDic.Add("return_code", "FAIL");
- returnDic.Add("return_msg", "签名失败");
- }
- else
- {
- returnDic.Add("return_code", "SUCCESS");
- }
-
- Response.Write(WeixinSDK.DictionaryToXML(returnDic));
-
- if (sign == originalSign)
- {
- if (parameters["return_code"] == "FAIL")
- {
- Log.Error("通信出错:" + String.Join(";", parameters.Select(m => m.Key + ":" + m.Value)));
- }
- else if (parameters["result_code"] == "FAIL")
- {
- Log.Error("业务出错:" + String.Join(";", parameters.Select(m => m.Key + ":" + m.Value)));
- }
- else
- {
- Log.Info("支付成功:" + String.Join(";", parameters.Select(m => m.Key + ":" + m.Value)));
- var request = new WeixinPayNotifyRequest()
- {
- transaction_id = parameters["transaction_id"],
- out_trade_no = parameters["out_trade_no"]
- };
-
- ConfirmPay(request.out_trade_no, request.transaction_id);
- }
- }
- }
- return Content(string.Empty);
- }