微信支付 微信小程序-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 w = new wx();
 87             w.timeStamp = _time;
 88             w.nonceStr = nonce_str;
 89             w.package = "prepay_id=" + prepay_id;
 90             w.paySign = MD5(strB).ToUpper(); ;
 91             w.signType = "MD5";
 92 
 93             //向小程序发送json数据
 94              return JsonConvert.SerializeObject(w);
 95         }
 96 
 97         /// <summary>
 98         /// 生成随机串    
 99         /// </summary>
100         /// <param name="length">字符串长度</param>
101         /// <returns></returns>
102         private static string GetRandomString(int length)
103         {
104             const string key = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
105             if (length < 1)
106                 return string.Empty;
107 
108             Random rnd = new Random();
109             byte[] buffer = new byte[8];
110 
111             ulong bit = 31;
112             ulong result = 0;
113             int index = 0;
114             StringBuilder sb = new StringBuilder((length / 5 + 1) * 5);
115 
116             while (sb.Length < length)
117             {
118                 rnd.NextBytes(buffer);
119 
120                 buffer[5] = buffer[6] = buffer[7] = 0x00;
121                 result = BitConverter.ToUInt64(buffer, 0);
122 
123                 while (result > 0 && sb.Length < length)
124                 {
125                     index = (int)(bit & result);
126                     sb.Append(key[index]);
127                     result = result >> 5;
128                 }
129             }
130             return sb.ToString();
131         }
132 
133         /// <summary>
134         /// 获取时间戳
135         /// </summary>
136         /// <returns></returns>
137         private static long getTime()
138         {
139             TimeSpan cha = (DateTime.Now - TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)));
140             long t = (long)cha.TotalSeconds;
141             return t;
142         }
143 
144 
145         /// <summary>
146         /// MD5签名方法  
147         /// </summary>  
148         /// <param name="inputText">加密参数</param>  
149         /// <returns></returns>  
150         private static string MD5(string inputText)
151         {
152             MD5 md5 = new MD5CryptoServiceProvider();
153             byte[] fromData = System.Text.Encoding.UTF8.GetBytes(inputText);
154             byte[] targetData = md5.ComputeHash(fromData);
155             string byte2String = null;
156 
157             for (int i = 0; i < targetData.Length; i++)
158             {
159                 byte2String += targetData[i].ToString("x2");
160             }
161 
162             return byte2String;
163         }
164         /// <summary>
165         /// HMAC-SHA256签名方式
166         /// </summary>
167         /// <param name="message"></param>
168         /// <param name="secret"></param>
169         /// <returns></returns>
170         private static string HmacSHA256(string message, string secret)
171         {
172             secret = secret ?? "";
173             var encoding = new System.Text.UTF8Encoding();
174             byte[] keyByte = encoding.GetBytes(secret);
175             byte[] messageBytes = encoding.GetBytes(message);
176             using (var hmacsha256 = new HMACSHA256(keyByte))
177             {
178                 byte[] hashmessage = hmacsha256.ComputeHash(messageBytes);
179                 return Convert.ToBase64String(hashmessage);
180             }
181         }
182 
183         /// <summary>
184         /// wx统一下单请求数据
185         /// </summary>
186         /// <param name="URL">请求地址</param>
187         /// <param name="urlArgs">参数</param>
188         /// <returns></returns>
189         private static string sendPost(string URL, string urlArgs)
190         {
191             //context.Request["args"]
192             System.Net.WebClient wCient = new System.Net.WebClient();
193             wCient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
194             byte[] postData = System.Text.Encoding.ASCII.GetBytes("body=" + urlArgs);
195 
196             byte[] responseData = wCient.UploadData(URL, "POST", postData);
197 
198             string returnStr = System.Text.Encoding.UTF8.GetString(responseData);//返回接受的数据 
199             return returnStr;
200             //<xml><return_code><![CDATA[FAIL]]></return_code>\n<return_msg><![CDATA[商户号mch_id与appid不匹配]]></return_msg>\n</xml>
201             //
202         }
203 
204         /// <summary>
205         /// 生成订单号
206         /// </summary>
207         /// <returns></returns>
208         private static string getRandomTime()
209         {
210             Random rd = new Random();//用于生成随机数
211             string DateStr = DateTime.Now.ToString("yyyyMMddHHmmssMM");//日期
212             string str = DateStr + rd.Next(10000).ToString().PadLeft(4, 0);//带日期的随机数
213             return str;
214         }
215 
216     }
217 }

使用的是MVC .NET Framework4

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

MVC项目发布前的配置

微信支付 微信小程序-C#后端

上一篇:首次编译Java小程序


下一篇:C++数组名的思考