Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Net how to realize the 5.0WeChat Pay function developed by Wechat official account

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly shows you ".NET how to achieve the Wechat official account development of the 5.0WeChat Pay function", the content is easy to understand, well-organized, hope to help you solve your doubts, the following let the editor lead you to study and learn ".NET how to achieve the Wechat official account development of 5.0 WeChat Pay function" this article.

one。 Preface

Before we start to do this function, the first thing we need to do is to think about how to do this WeChat Pay, where to start, where to start, what the official sdk says, whether there is any official demo, and whether there are some complete materials given to me by my boss, and whether there are any interfaces to apply for.

two。 Prepare before development.

WeChat Pay official developer documentation

2.0 official demo download We use c #, so we choose the. Net version, but this official demo starts running at all.

3. 0 official demo running solution

4.0 WeChat Pay official. Net version of the pit you did not discuss.

Before the development of Wechat public platform, please check the configuration carefully.

three。 Coding

After making these preparations, we know that there are two kinds of WeChat Pay. Original, called directly by 2.jsapi, the second one is used in my project.

After some business logic processing, we come to our order details page. Now we need to click our payment button to pay. The pay.aspx code of the payment page is as follows.

Foreground page:

/ / call Wechat JS api to pay function jsApiCall () {WeixinJSBridge.invoke ('getBrandWCPayRequest', / / josn string function (res) {if (res.err_msg = = "get_brand_wcpay_request:ok") {var OrderId=$ ("# OrderId") .val () Var orderProductName=$ ("# orderProductName"). Val (); var orderMoneySum=$ ("# orderMoneySum"). Val (); _ window.location.href= "http://www.baidu.aspx?OrderId="+OrderId+"&orderMoneySum="+orderMoneySum+"&orderProductName="+orderProductName; / / Jump page after successful payment} else {WeixinJSBridge.call ('closeWindow');}}) } function callpay () {if (typeof WeixinJSBridge = = "undefined") {if (document.addEventListener) {document.addEventListener ('WeixinJSBridgeReady', jsApiCall, false) } else if (document.attachEvent) {document.attachEvent ('WeixinJSBridgeReady', jsApiCall); document.attachEvent (' onWeixinJSBridgeReady', jsApiCall) Else {jsApiCall ();}}

You confirm the payment of yuan.

";} else// cannot contain other data types except string and int types {Log.Error (this.GetType (). ToString ()," WxPayData field data type error! "); throw new WxPayException (" WxPayData field data type error! ") }} xml + = ""; return xml } / * @ convert xml to WxPayData object and return data inside the object * @ param string xml string to be converted * @ return converted Dictionary * @ throws WxPayException * / public SortedDictionary FromXml (string xml) {if (string.IsNullOrEmpty (xml)) { Log.Error (this.GetType (). ToString () "it is illegal to convert an empty xml string to WxPayData!" Throw new WxPayException ("it is illegal to convert an empty xml string to WxPayData!");} XmlDocument xmlDoc = new XmlDocument (); xmlDoc.LoadXml (xml); XmlNode xmlNode = xmlDoc.FirstChild;// to get the root node XmlNodeList nodes = xmlNode.ChildNodes Foreach (XmlNode xn in nodes) {XmlElement xe = (XmlElement) xn; m _ values [xe.Name] = xe.InnerText / / get the key-value pair of xml to the data inside WxPayData} try {/ / 2015-06-29 error is unsigned if (m_values ["return_code"]! = "SUCCESS") {return m_values } CheckSign (); / / verify the signature without throwing an exception} catch (WxPayException ex) {throw new WxPayException (ex.Message);} return m_values } / * @ Dictionary format is converted to url parameter format * @ return url format string, which does not contain the sign field value * / public string ToUrl () {string buff = "" Foreach (KeyValuePair pair in m_values) {if (pair.Value = = null) {Log.Error (this.GetType (). ToString (), "WxPayData contains fields with values of null!"); throw new WxPayException ("fields with values of null inside WxPayData!") } if (pair.Key! = "sign" & & pair.Value.ToString ()! = ") {buff + = pair.Key +" = "+ pair.Value +" & ";}} buff = buff.Trim ('&'); return buff } / * * @ Dictionary formatted into Json * @ return json string data * / public string ToJson () {string jsonStr = JsonMapper.ToJson (m_values); return jsonStr } / * * @ values is formatted into a result that can be displayed on a Web page (because a string in xml format cannot be directly output on a web page) * / public string ToPrintStr () {string str = "" Foreach (KeyValuePair pair in m_values) {if (pair.Value = = null) {Log.Error (this.GetType (). ToString (), "WxPayData contains fields with values of null!"); throw new WxPayException ("fields with values of null inside WxPayData!") } str + = string.Format ("{0} = {1})

", pair.Key, pair.Value.ToString ();} Log.Debug (this.GetType (). ToString ()," Print in Web Page: "+ str); return str } / * @ generate signature. For more information, please see signature generation algorithm * @ return signature. Sign field does not participate in signature * / public string MakeSign () {/ / convert url format string str = ToUrl (); / / add API KEY str + = "& key=" + WxPayConfig.KEY after string / / MD5 encryption var md5 = MD5.Create (); var bs = md5.ComputeHash (Encoding.UTF8.GetBytes (str)); var sb = new StringBuilder (); foreach (byte b in bs) {sb.Append (b.ToString ("x2")) } / / all characters are converted to uppercase return sb.ToString () .ToUpper () } / * * check whether the signature is correct * correctly return true, error throw exception * / public bool CheckSign () {/ / if the signature is not set Skip detection of if (! IsSet ("sign")) {Log.Error (this.GetType () .ToString (), "WxPayData signature exists but invalid!") Throw new WxPayException ("WxPayData signature exists but not legal!") } / / if the signature is set but the signature is empty, throw an exception else if (GetValue ("sign") = = null | | GetValue ("sign"). ToString () = "") {Log.Error (this.GetType (). ToString (), "WxPayData signature exists but invalid!") Throw new WxPayException ("WxPayData signature exists but invalid!");} / / get the received signature string return_sign = GetValue ("sign"). ToString (); / / calculate the new signature locally string cal_sign = MakeSign () If (cal_sign = = return_sign) {return true;} Log.Error (this.GetType () .ToString (), "WxPayData signature verification error!"); throw new WxPayException ("WxPayData signature verification error!") } / * * @ get Dictionary * / public SortedDictionary GetValues () {return masks values;}}

WxPayData

Profile Information

/ * configure account information * / public class WxPayConfig {/ / = [basic information setting] = / * Wechat official account information configuration * APPID: APPID for binding payment (must be configured) * MCHID: merchant number (must be configured) * KEY: merchant payment key Refer to account opening email settings (must be configured) * APPSECRET: public account secert (required for JSAPI payment only) * / public const string APPID = "wx14e3e56f3" Public const string MCHID = "12352"; public const string KEY = "BB6BE71D7CED49A79409C9"; public const string APPSECRET = "76eb33f66129692da1624f1"; / / = [Certificate path setting] = / * Certificate path. Note that you should enter the absolute path (required for refund or cancellation of orders only) * / public const string SSLCERT_PATH = "cert/apiclient_cert.p12"; public const string SSLCERT_PASSWORD = "123502" / / = [payment result notification url] = / * callback url of payment result notification for merchants to receive payment results * / public const string NOTIFY_URL = "http://www.baidu.com/ResultPay.aspx"; / / = [merchant system backend machine IP] = / * this parameter can be manually configured or automatically obtained in the program * / public const string IP = "150.24.91.151" / / = [proxy server settings] = / * default IP and port number are 0.0.0.0 and 0, respectively. Do not enable the proxy (set it if necessary) * / public const string PROXY_URL = "http://10.152.18.220:8080"; / / = [reporting information configuration] = / * speed reporting level, 0. Close the reporting; 1. Report only errors; 2. Fully report * / public const int REPORT_LEVENL = 1; / / = [log level] = / * log level, 0. Do not output log; 1. Only output error messages; 2. Output error and normal information; 3. Output error message, normal message and debug information * / public const int LOG_LEVENL = 3;}

WxPayConfig

Then we look at two key lines of code:

WxPayData unifiedOrderResult = = jsApiPay.GetJsApiParameters ()

At this point, if the wxJsApiParam variable can get the value smoothly, then the parameters we want to pass can be obtained from: Z on the foreground page. At this time, you can call WeChat Pay's API to open our payment page as shown in the figure:

/ / call Wechat JS api to pay function jsApiCall () {WeixinJSBridge.invoke ('getBrandWCPayRequest', / / josn string function (res) {if (res.err_msg = = "get_brand_wcpay_request:ok") {var OrderId=$ ("# OrderId") .val () Var orderProductName=$ ("# orderProductName"). Val (); var orderMoneySum=$ ("# orderMoneySum"). Val (); _ window.location.href= "http://www.baodu.com/PaySkip.aspx?OrderId="+OrderId+"&orderMoneySum="+orderMoneySum+"&orderProductName="+orderProductName; } else {WeixinJSBridge.call ('closeWindow');}});}

(JsApiPay.cs) get the result of placing the order:

Public WxPayData GetUnifiedOrderResult (string body) {/ / Unified order WxPayData data = new WxPayData (); data.SetValue ("body", body); data.SetValue ("out_trade_no", WxPayApi.GenerateOutTradeNo ()); data.SetValue ("total_fee", total_fee); data.SetValue ("trade_type", "JSAPI") Data.SetValue ("openid", openid); WxPayData result = WxPayApi.UnifiedOrder (data); if (! result.IsSet ("appid") | |! result.IsSet ("prepay_id") | | result.GetValue ("prepay_id"). ToString () = "") {Log.Error (this.GetType (). ToString (), "UnifiedOrder response error!") Throw new WxPayException ("UnifiedOrder response error!");} unifiedOrderResult = result; return result;}

(WxPayApi.cs) Unified API for placing orders:

/ * * Unified order issuing * @ param WxPaydata inputObj the parameter * @ param int timeOut timeout * @ throws WxPayException * @ return submitted to Unified order issuing API is returned when it succeeds. Other exceptions thrown * / public static WxPayData UnifiedOrder (WxPayData inputObj, int timeOut = 6) {string url = "https://api.mch.weixin.qq.com/pay/unifiedorder"; / / detect the required parameter if (! inputObj.IsSet ("out_trade_no")) {throw new WxPayException ("missing required parameter out_trade_no!" for unified payment interface) ;} else if (! inputObj.IsSet ("body")) {throw new WxPayException ("missing required parameter body!" for unified payment interface) ;} else if (! inputObj.IsSet ("total_fee")) {throw new WxPayException ("missing required parameter total_fee!" for unified payment interface) ;} else if (! inputObj.IsSet ("trade_type")) {throw new WxPayException ("missing required parameter trade_type!" for unified payment interface) ;} / / the associated parameter if (inputObj.GetValue ("trade_type"). ToString () = "JSAPI" & &! inputObj.IsSet ("openid") {throw new WxPayException ("in the unified payment API, missing the required parameter openid! when trade_type is JSAPI, openid is required!") ;} if (inputObj.GetValue ("trade_type"). ToString () = = "NATIVE" & &! inputObj.IsSet ("product_id") {throw new WxPayException ("in the unified payment API, the required parameter product_id! product_id is required when trade_type is JSAPI!") ;} / / Asynchronous Notification url is not set, then use url if (! inputObj.IsSet ("notify_url")) {inputObj.SetValue ("notify_url", WxPayConfig.NOTIFY_URL) in the configuration file; / / Asynchronous Notification url} inputObj.SetValue ("appid", WxPayConfig.APPID) / / Public account ID inputObj.SetValue ("mch_id", WxPayConfig.MCHID); / / merchant number inputObj.SetValue ("spbill_create_ip", WxPayConfig.IP); / / Terminal ip inputObj.SetValue ("nonce_str", GenerateNonceStr ()); / / Random string / / signature inputObj.SetValue ("sign", inputObj.MakeSign ()) String xml = inputObj.ToXml (); var start = DateTime.Now; string response = HttpService.Post (xml, url, false, timeOut); var end = DateTime.Now; int timeCost = (int) ((end-start) .TotalMilliseconds); WxPayData result = new WxPayData (); result.FromXml (response); ReportCostTime (url, timeCost, result) / / report the speed to return result;} 4. The effect of the final development

These are all the contents of this article entitled "how .NET implements the 5.0WeChat Pay function developed by Wechat official account". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report