How to realize Wechat JS-SDK payment by ASP.NET
Editor to share with you how ASP.NET to achieve Wechat JS-SDK payment, I believe that most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to understand it!
The details are as follows
Model layer entity classes:
Public class JsEntities {/ official account id / public string appId {get; set;} / public string timeStamp {get; set;} / Random string / public string nonceStr {get; set;} / order details extension string / public string package {get; set } / public string signType {get; set;} / signature / public string paySign {get; set;}} public class UnifyEntities {/ Public account ID account / public string appid {get; set;} / the merchant number / public string mch_id {get; set assigned by WeChat Pay } / the terminal device number assigned by WeChat Pay / public string device_info {get; set;} / random string, no longer than 32-bit / public string nonce_str {get; set;} / signature / public string sign {get; set;} / the maximum length of the product description is 127 / public string body {get Set;} / additional data, return / public string attach {get; set;} / the order number within the merchant system as is, which can contain letters within 32 characters to ensure that it is unique in the merchant system. Details / public string out_trade_no {get; set Total order amount (in points), not with decimal point / public string total_fee {get; set;} / terminal IP / public string spbill_create_ip {get; set;} / public string time_start {get; set } / transaction end time / public string time_expire {get; set;} Universe / receive WeChat Pay successful notification / public string notify_url {get; set;} / JSAPI, NATIVE, APP / public string trade_type {get; set } / / the unique identity of the user under the merchant's appid. If trade_type is JSAPI, this parameter must be passed / public string openid {get; set;} / only if trade_type is NATIVE. This id is the merchandise ID contained in the QR code, which is maintained by merchants themselves. / public string product_id {get; set;}} public class UnifyReceive {/ SUCCESS/FAIL this field is a communication ID, not a transaction ID. You need to check result_code to determine / public string return_code {get; set;} / return information. If it is not empty, it is the error reason / public string return_msg {get; set. } / the public account assigned by Wechat: ID / public string appid {get; set;} / the merchant number / / public string mch_id {get; set;} / a random string assigned by WeChat Pay, which is not longer than 32-bit / public string nonce_str {get; set;} / signature / public string sign {get; set } / Business result / public string result_code {get; set;} / prepaid ID / public string prepay_id {get; set;} / public string trade_type {get; set;} / QR code link / public string code_url {get; set } public UnifyReceive (string xml) {XElement doc = XElement.Parse (xml); return_code = doc.Element ("return_code"). Value; return_msg = doc.Element ("return_msg"). Value; if (return_code = = "SUCCESS") {appid = doc.Element ("appid"). Value; mch_id = doc.Element ("mch_id"). Value; nonce_str = doc.Element ("nonce_str"). Value Sign = doc.Element ("sign"). Value; result_code = doc.Element ("result_code"). Value; if (result_code = = "SUCCESS") {trade_type = doc.Element ("trade_type"). Value; prepay_id = doc.Element ("prepay_id"). Value; if (trade_type = = "NATIVE") {code_url = doc.Element ("code_url"). Value } trade_type = doc.Element ("trade_type") .Value;}}
TestJs.aspx content:
$(function () {$("# submit") .click (function () {var OID = "; alert (OID)) Get ("WxPay/WxPay.ashx?action=jspayparam", {body: $("# body"). Val (), total_fee: $("# price"). Val (), out_trade_no: $("# order"). Val (), trade_type: "JSAPI", msgid: ""}, function (data) {WxPay.Pay (data.appId, data.timeStamp, data.nonceStr, data.package, data.signType, data.paySign) Function () {alert ("payment successful") });}, "json");});}) Product description: commodity price: order number:
JsPay.aspx.cs Code:
Public partial class JsPay: System.Web.UI.Page {public string openid = ""; protected void Page_Load (object sender, EventArgs e) {string code = Request ["code"]; if (string.IsNullOrEmpty (code)) {/ / if code is not successfully obtained, pull GetAuthUrl ("wxxxxxxxxxxxxxxxxxxxxxxx", "http://www.china101.net/JsPay.aspx");" again) } openid = GetOpenID ("wxxxxxxxxxxxxxxxxxxxxxxx", "dsdssdsdsdsdsdsdsdsdsd", JKRequest.GetQueryString ("code"), () = > {});} public string GetOpenID (string appid, string secret, string code, Action CallBack) {try {string retdata = Utils.HttpGet (string.Format ("https://api.weixin.qq.com/sns/oauth3/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code", appid, secret, code)); .LogHelper.WriteFile (retdata) JObject jobj = (JObject) JsonConvert.DeserializeObject (retdata); string openid = jobj.Value ("openid"); return openid;} catch (Exception) {CallBack (); return ";} / / return GetUserInfo (access_token, openid) } / public void GetAuthUrl (string appid, string redirect_url) {Response.Redirect (string.Format ("https://open.weixin.qq.com/connect/oauth3/authorize?appid={0}&redirect_uri={1}&response_type=code&scope=snsapi_base&state=123#wechat_redirect", appid, Utils.UrlEncode (redirect_url);}}
WxPay.ashx Code:
/ public class WxPay: IHttpHandler {/ Public account ID / private string appid = "wxxxxxxxxxxxxxxxx"; / merchant / private string mch_id = "12333333333"; / notify url / private string notify_url = "http://www.china101.net/Notify2.aspx";" / key / private string key = "chinapagexxxxxxxxxxxxx"; public void ProcessRequest (HttpContext context) {string action = JKRequest.GetQueryString ("action"); switch (action) {case "unifysign": GetUnifySign (context); break; case "jspayparam": GetJsPayParam (context); break; case "nativedynamic": GetPayQr (context); break }} # region get js payment parameters void GetJsPayParam (HttpContext context) {JsEntities jsEntities = new JsEntities () {appId = appid, nonceStr = .Utils.GetRandom (), package = string.Format ("prepay_id= {0}", GetPrepayId (context)), signType = "MD5", timeStamp = .Utils.ConvertDateTimeInt (DateTime.Now). ToString ()}; string url, sign; string xmlStr = .Utils.GetUnifyRequestXml (jsEntities, key, out url, out sign); LogHelper.WriteFile (xmlStr) JsEntities.paySign = sign; context.Response.Write (JsonConvert.SerializeObject (jsEntities));} # endregion # region get prepaid ID / /-string GetPrepayId (HttpContext context) {string xml; GetUnifySign (context, out xml) LogHelper.WriteFile ("GetPrepayId---71--" + xml); UnifyReceive unifyReceive = new UnifyReceive (.Utils.HttpPost ("https://api.mch.weixin.qq.com/pay/unifiedorder", xml)); LogHelper.WriteFile (" unifyReceive---73-- "+ unifyReceive.prepay_id); return unifyReceive.prepay_id;} # endregion # region get a unified signature void GetUnifySign (HttpContext context) {string xml; context.Response.Write (GetUnifySign (context, out xml)) } # endregion # region get unified signature string GetUnifySign (HttpContext context, out string xml) {string url, sign; xml = WxPayHelper.Utils.GetUnifyUrlXml (GetUnifyEntities (context), key, out url, out sign); return sign;} # endregion # region get QR code void GetPayQr (HttpContext context) {string url = GetPayUrl (context); WxPayHelper.Utils.GetQrCode (url);} # endregion # region get QR code link string GetPayUrl (HttpContext context) {string xml; GetUnifySign (context, out xml) WxPayHelper.Utils.WriteTxt (xml); UnifyReceive unifyReceive = new UnifyReceive (WxPayHelper.Utils.HttpPost ("https://api.mch.weixin.qq.com/pay/unifiedorder", xml)); return unifyReceive.code_url;} # endregion # region get the unified payment API parameter object UnifyEntities GetUnifyEntities (HttpContext context) {string msgid = JKRequest.GetQueryString (" msgid "); LogHelper.WriteFile (" 115-"+ msgid) UnifyEntities unify = new UnifyEntities {appid = appid, body = JKRequest.GetQueryString ("body"), mch_id = mch_id, nonce_str = WxPayHelper.Utils.GetRandom (), out_trade_no = JKRequest.GetQueryString ("out_trade_no"), notify_url = notify_url, spbill_create_ip = JKRequest.GetIP (), trade_type = JKRequest.GetQueryString ("trade_type"), total_fee = JKRequest.GetQueryString ("total_fee")} If (unify.trade_type = = NATIVE) {unify.product_id = msgid;} else {unify.openid = msgid;} return unify;} # endregion public bool IsReusable {get {return false;}
Utils.cs Code:
Public class Utils {# region MD5 encryption public static string MD5 (string pwd) {MD5 md5 = new MD5CryptoServiceProvider (); byte [] data = System.Text.Encoding.Default.GetBytes (pwd); byte [] md5data = md5.ComputeHash (data); md5.Clear (); string str = ""; for (int I = 0; I)
< md5data.Length; i++) { str += md5data[i].ToString("x").PadLeft(2, '0'); } return str; } /// /// 获取文件的md5 /// /// 文件路径,url路径 /// md5字符串 string GetMD5HashFromFile(string filepath) { try { WebClient wc = new WebClient(); var file = wc.OpenRead(new Uri(filepath)); System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); byte[] retVal = md5.ComputeHash(file); file.Close(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < retVal.Length; i++) { sb.Append(retVal[i].ToString("x2")); } return sb.ToString(); } catch (Exception ex) { throw new Exception("GetMD5HashFromFile() fail,error:" + ex.Message); } } #endregion #region 对象转换处理 /// /// 判断对象是否为Int32类型的数字 /// /// /// public static bool IsNumeric(object expression) { if (expression != null) return IsNumeric(expression.ToString()); return false; } /// /// 判断对象是否为Int32类型的数字 /// /// /// public static bool IsNumeric(string expression) { if (expression != null) { string str = expression; if (str.Length >0 & & str.Length = 11 | |! Regex.IsMatch (expression.Trim (), @ "^ ([-] | [0-9]) [0-9] * (\.\ w*)? $") return defValue; int rv; if (Int32.TryParse (expression, out rv)) return rv; return Convert.ToInt32 (StrToFloat (expression, defValue)) } / object type converted to decimal type / default value / converted decimal type result public static decimal ObjToDecimal (object expression, decimal defValue) {if (expression! = null) return StrToDecimal (expression.ToString (), defValue); return defValue } / string type converted to decimal type / default value / converted decimal type result public static decimal StrToDecimal (string expression, decimal defValue) {if ((expression = = null) | | (expression.Length > 10) return defValue; decimal intValue = defValue If (expression! = null) {bool IsDecimal = Regex.IsMatch (expression, @ "^ ([-] | [0-9]) [0-9] * (\.\ w*)? $"); if (IsDecimal) decimal.TryParse (expression, out intValue);} return intValue } / object type converted to float type / default value / converted int type result public static float ObjToFloat (object expression, float defValue) {if (expression! = null) return StrToFloat (expression.ToString (), defValue); return defValue } / string converted to float / default value / converted int type result public static float StrToFloat (string expression, float defValue) {if ((expression = = null) | | (expression.Length > 10) return defValue; float intValue = defValue If (expression! = null) {bool IsFloat = Regex.IsMatch (expression, @ "^ ([-] | [0-9]) [0-9] * (\.\ w*)? $"); if (IsFloat) float.TryParse (expression, out intValue);} return intValue } / convert the object to the date-time type / the string to be converted / default / the converted int type result public static DateTime StrToDateTime (string str, DateTime defValue) {if (! string.IsNullOrEmpty (str)) {DateTime dateTime; if (DateTime.TryParse (str, out dateTime)) return dateTime;} return defValue } / / convert the object to the date-time type / the string to be converted / the converted int type result public static DateTime StrToDateTime (string str) {return StrToDateTime (str, DateTime.Now) } / convert objects to date-time types / objects to be converted / converted int types result public static DateTime ObjectToDateTime (object obj) {return StrToDateTime (obj.ToString ()) } / convert objects to date-time types / defaults / converted int types result public static DateTime ObjectToDateTime (object obj, DateTime defValue) {return StrToDateTime (obj.ToString (), defValue) } / convert the object to a string / the object to be converted / the converted string type results public static string ObjectToStr (object obj) {if (obj = = null) return "; return obj.ToString () .Trim () } / determine whether the mailbox / public static bool IsEmail (string expression) {return Regex.IsMatch (expression) @ "^ ([\ w -\.] +) @ ((\ [[0-9] {1Mague 3}\. [0-9] {1Mague 3}\.) | (([\ w -] +\.) ([a-zA-Z] {2pm 4} | [0-9] {1pm 3}) (\]?) $")) / public static bool IsMobile (string expression) {return Regex.IsMatch (expression, @ "^ 1 [3 | 4 | 5 | 6 | 7 | 8 | 9] [0-9] {9} $");} public static bool IsPhone (string telphone) {Regex regex = new Regex (@ "^ (\ d {3pc4} -)?\ d {6pm 8} $"); return regex.IsMatch (telphone) } # endregion # region split string / public static string [] SplitString (string strContent, string strSplit) {if (! string.IsNullOrEmpty (strContent)) {if (strContent.IndexOf (strSplit))
< 0) return new string[] { strContent }; return Regex.Split(strContent, Regex.Escape(strSplit), RegexOptions.IgnoreCase); } else return new string[0] { }; } /// /// 分割字符串 /// /// public static string[] SplitString(string strContent, string strSplit, int count) { string[] result = new string[count]; string[] splited = SplitString(strContent, strSplit); for (int i = 0; i < count; i++) { if (i < splited.Length) result[i] = splited[i]; else result[i] = string.Empty; } return result; } #endregion #region 删除最后结尾的一个逗号 /// /// 删除最后结尾的一个逗号 /// public static string DelLastComma(string str) { if (str.Length < 1) { return ""; } return str.Substring(0, str.LastIndexOf(",")); } #endregion #region 删除最后结尾的指定字符后的字符 /// /// 删除最后结尾的指定字符后的字符 /// public static string DelLastChar(string str, string strchar) { if (string.IsNullOrEmpty(str)) return ""; if (str.LastIndexOf(strchar) >= 0 & & str.LastIndexOf (strchar) = = str.Length-1) {return str.Substring (0, str.LastIndexOf (strchar));} return str } # endregion # region generate string of specified length / generate string of specified length, that is, generate strLong str string / generated length / generate string / public static string StringOfChar (int strLong, string str) {string ReturnStr = "" in str; for (int I = 0; I)
< strLong; i++) { ReturnStr += str; } return ReturnStr; } #endregion #region 生成日期随机码 /// /// 生成日期随机码 /// /// public static string GetRamCode() { #region return DateTime.Now.ToString("yyyyMMddHHmmssffff"); #endregion } #endregion #region 生成随机字母或数字 /// /// 生成随机数字 /// /// 生成长度 /// public static string Number(int Length) { return Number(Length, false); } /// /// 生成随机数字 /// /// 生成长度 /// 是否要在生成前将当前线程阻止以避免重复 /// public static string Number(int Length, bool Sleep) { if (Sleep) System.Threading.Thread.Sleep(3); string result = ""; System.Random random = new Random(); for (int i = 0; i < Length; i++) { result += random.Next(10).ToString(); } return result; } /// /// 生成随机字母字符串(数字字母混和) /// /// 待生成的位数 public static string GetCheckCode(int codeCount) { string str = string.Empty; int rep = 0; long num2 = DateTime.Now.Ticks + rep; rep++; Random random = new Random(((int)(((ulong)num2) & 0xffffffffL)) | ((int)(num2 >> rep)); for (int I = 0; I
< codeCount; i++) { char ch; int num = random.Next(); if ((num % 2) == 0) { ch = (char)(0x30 + ((ushort)(num % 10))); } else { ch = (char)(0x41 + ((ushort)(num % 0x1a))); } str = str + ch.ToString(); } return str; } /// /// 根据日期和随机码生成订单号 /// /// public static string GetOrderNumber() { string num = DateTime.Now.ToString("yyMMddHHmmss");//yyyyMMddHHmmssms return num + Number(2).ToString(); } private static int Next(int numSeeds, int length) { byte[] buffer = new byte[length]; System.Security.Cryptography.RNGCryptoServiceProvider Gen = new System.Security.Cryptography.RNGCryptoServiceProvider(); Gen.GetBytes(buffer); uint randomResult = 0x0;//这里用uint作为生成的随机数 for (int i = 0; i < length; i++) { randomResult |= ((uint)buffer[i] len) break; } //如果截过则加上半个省略号 byte[] mybyte = System.Text.Encoding.Default.GetBytes(inputString); if (mybyte.Length >Len) tempString + = "…" ; return tempString;} # endregion # region clears the HTML tag public static string DropHTML (string Htmlstring) {if (string.IsNullOrEmpty (Htmlstring)) return ""; / / deletes the script Htmlstring = Regex.Replace (Htmlstring, @ "] * >. *", ", RegexOptions.IgnoreCase); / / deletes HTML Htmlstring = Regex.Replace (Htmlstring, @"] *) > ",", RegexOptions.IgnoreCase) Htmlstring = Regex.Replace (Htmlstring, @ "([\ r\ n]) [\ s] +", ", RegexOptions.IgnoreCase); Htmlstring = Regex.Replace (Htmlstring, @"-> ",", RegexOptions.IgnoreCase); Htmlstring = Regex.Replace (Htmlstring, @ ")