1. 程式人生 > >微信支付 微信小程序-C#後端

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

seda enc 發送 sendpost php order pty pan std

  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#後端