微信小程序支付C#后端源码

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Text;
  5 using System.Web;
  6 using System.Web.Mvc;
  7 using System.IO;
  8 using System.Security.Cryptography;
  9 using System.Text;
 10 using System.Xml;
 11 using Newtonsoft.Json;
 12 using Newtonsoft.Json.Linq;
 13 namespace Mvc_vue.Controllers
 14 {
 15     public class wxController : Controller
 16     {
 17         //
 18         // GET: /wx/
 19 
 20         public ActionResult Index()
 21         {
 22             return View();
 23         }
 24         //所需值
 25         public static string _appid = "wxd930ea5d5a258f4f";
 26         public static string _mch_id = "10000100";
 27         public static string _key = "192006250b4c09247ec02edce69f6a2d";
 28 
 29         //模拟wx统一下单 openid(前台获取)
 30         public string getda(string openid)
 31         {
 32             return Getprepay_id(_appid, "shanghaifendian", "monixiaofei", _mch_id, GetRandomString(30), "http://www.weixin.qq.com/wxpay/pay.php", openid, getRandomTime(), 1);
 33 
 34         }
 35 
 36         
 37 
 38         //微信统一下单获取prepay_id & 再次签名返回数据
 39         private static string Getprepay_id(string appid, string attach, string body, string mch_id, string nonce_str, string notify_url, string openid, string bookingNo, int total_fee)
 40         {
 41             var url = "https://api.mch.weixin.qq.com/pay/unifiedorder";//微信统一下单请求地址
 42             string strA = "appid=" + appid + "&attach=" + attach + "&body=" + body + "&mch_id=" + mch_id + "&nonce_str=" + nonce_str + "&notify_url=" + notify_url + "&openid=" + openid + "&out_trade_no=" + bookingNo + "&spbill_create_ip=61.50.221.43&total_fee=" + total_fee + "&trade_type=JSAPI";
 43             string strk = strA + "&key="+_key;  //key为商户平台设置的密钥key(假)
 44             string strMD5 = MD5(strk).ToUpper();//MD5签名
 45 
 46             //string strHash=HmacSHA256("sha256",strmd5).ToUpper();   //签名方式只需一种(MD5 或 HmacSHA256     【支付文档需仔细看】)
 47 
 48             //签名
 49             var formData = "<xml>";
 50             formData += "<appid>" + appid + "</appid>";//appid  
 51             formData += "<attach>" + attach + "</attach>"; //附加数据(描述)
 52             formData += "<body>" + body + "</body>";//商品描述
 53             formData += "<mch_id>" + mch_id + "</mch_id>";//商户号  
 54             formData += "<nonce_str>" + nonce_str + "</nonce_str>";//随机字符串,不长于32位。  
 55             formData += "<notify_url>" + notify_url + "</notify_url>";//通知地址
 56             formData += "<openid>" + openid + "</openid>";//openid
 57             formData += "<out_trade_no>" + bookingNo + "</out_trade_no>";//商户订单号    --待
 58             formData += "<spbill_create_ip>61.50.221.43</spbill_create_ip>";//终端IP  --用户ip
 59             formData += "<total_fee>" + total_fee + "</total_fee>";//支付金额单位为(分)
 60             formData += "<trade_type>JSAPI</trade_type>";//交易类型(JSAPI--公众号支付)
 61             formData += "<sign>" + strMD5 + "</sign>"; //签名
 62             formData += "</xml>";
 63 
 64 
 65 
 66             //请求数据
 67             var getdata = sendPost(url, formData);
 68 
 69             //获取xml数据
 70             XmlDocument doc = new XmlDocument();
 71             doc.LoadXml(getdata);
 72             //xml格式转json
 73             string json = Newtonsoft.Json.JsonConvert.SerializeXmlNode(doc);
 74 
 75 
 76 
 77             JObject jo = (JObject)JsonConvert.DeserializeObject(json);
 78             string prepay_id = jo["xml"]["prepay_id"]["#cdata-section"].ToString();
 79 
 80             //时间戳
 81             string _time = getTime().ToString();
 82 
 83             //再次签名返回数据至小程序
 84             string strB = "appId=" + appid + "&nonceStr=" + nonce_str + "&package=prepay_id=" + prepay_id + "&signType=MD5&timeStamp=" + _time + "&key="_key;
 85 
 86             //wx自己写的一个类
 87             wx w = new wx();
 88             w.timeStamp = _time;
 89             w.nonceStr = nonce_str;
 90             w.package = "prepay_id=" + prepay_id;
 91             w.paySign = MD5(strB).ToUpper(); ;
 92             w.signType = "MD5";
 93 
 94             //向小程序返回json数据
 95              return JsonConvert.SerializeObject(w);
 96         }
 97 
 98         /// <summary>
 99         /// 生成随机串    
100         /// </summary>
101         /// <param name="length">字符串长度</param>
102         /// <returns></returns>
103         private static string GetRandomString(int length)
104         {
105             const string key = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
106             if (length < 1)
107                 return string.Empty;
108 
109             Random rnd = new Random();
110             byte[] buffer = new byte[8];
111 
112             ulong bit = 31;
113             ulong result = 0;
114             int index = 0;
115             StringBuilder sb = new StringBuilder((length / 5 + 1) * 5);
116 
117             while (sb.Length < length)
118             {
119                 rnd.NextBytes(buffer);
120 
121                 buffer[5] = buffer[6] = buffer[7] = 0x00;
122                 result = BitConverter.ToUInt64(buffer, 0);
123 
124                 while (result > 0 && sb.Length < length)
125                 {
126                     index = (int)(bit & result);
127                     sb.Append(key[index]);
128                     result = result >> 5;
129                 }
130             }
131             return sb.ToString();
132         }
133 
134         /// <summary>
135         /// 获取时间戳
136         /// </summary>
137         /// <returns></returns>
138         private static long getTime()
139         {
140             TimeSpan cha = (DateTime.Now - TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)));
141             long t = (long)cha.TotalSeconds;
142             return t;
143         }
144 
145 
146         /// <summary>
147         /// MD5签名方法  
148         /// </summary>  
149         /// <param name="inputText">加密参数</param>  
150         /// <returns></returns>  
151         private static string MD5(string inputText)
152         {
153             MD5 md5 = new MD5CryptoServiceProvider();
154             byte[] fromData = System.Text.Encoding.UTF8.GetBytes(inputText);
155             byte[] targetData = md5.ComputeHash(fromData);
156             string byte2String = null;
157 
158             for (int i = 0; i < targetData.Length; i++)
159             {
160                 byte2String += targetData[i].ToString("x2");
161             }
162 
163             return byte2String;
164         }
165         /// <summary>
166         /// HMAC-SHA256签名方式
167         /// </summary>
168         /// <param name="message"></param>
169         /// <param name="secret"></param>
170         /// <returns></returns>
171         private static string HmacSHA256(string message, string secret)
172         {
173             secret = secret ?? "";
174             var encoding = new System.Text.UTF8Encoding();
175             byte[] keyByte = encoding.GetBytes(secret);
176             byte[] messageBytes = encoding.GetBytes(message);
177             using (var hmacsha256 = new HMACSHA256(keyByte))
178             {
179                 byte[] hashmessage = hmacsha256.ComputeHash(messageBytes);
180                 return Convert.ToBase64String(hashmessage);
181             }
182         }
183 
184         /// <summary>
185         /// wx统一下单请求数据
186         /// </summary>
187         /// <param name="URL">请求地址</param>
188         /// <param name="urlArgs">参数</param>
189         /// <returns></returns>
190         private static string sendPost(string URL, string urlArgs)
191         {
192             
193             System.Net.WebClient wCient = new System.Net.WebClient();
194             wCient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
195             //byte[] postData = System.Text.Encoding.ASCII.GetBytes(urlArgs);  如果微信签名中有中文会签名失败
196         byte[] postData = System.Text.Encoding.UTF8.GetBytes(urlArgs);     
197             byte[] responseData = wCient.UploadData(URL, "POST", postData);
198         
199             string returnStr = System.Text.Encoding.UTF8.GetString(responseData);//返回接受的数据 
200             return returnStr;
201          }
202 
203         /// <summary>
204         /// 生成订单号
205         /// </summary>
206         /// <returns></returns>
207         private static string getRandomTime()
208         {
209             Random rd = new Random();//用于生成随机数
210             string DateStr = DateTime.Now.ToString("yyyyMMddHHmmssMM");//日期
211             string str = DateStr + rd.Next(10000).ToString().PadLeft(4, '0');//带日期的随机数
212             return str;
213         }
214 
215     }
216 }

 

使用的是MVC .NET Framework4

微信小程序支付 小程序端源码

MVC项目发布前的配置

posted @ 2018-08-28 15:49  oneall  阅读(6801)  评论(8编辑  收藏  举报