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

An example Analysis of WeChat Pay developed by the official account of Wechat

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

Share

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

This article will explain in detail the example analysis of WeChat Pay in the development of Wechat official account. The editor thinks it is very practical, so I share it with you for reference. I hope you can get something after reading this article.

First of all, your official account must be a certification service number, to open the authority of WeChat Pay Before developing and writing the code, we need to set up some payment-related information to facilitate subsequent operations. After opening, Wechat will send you an email, which contains some information related to the backstage login of your official account merchant platform. After logging in to the merchant platform, set the key in-> account Settings-> API Security. This will be used later.

Account parameters description

The parameter API in the email details that APPIDappidappid is the unique identity of the Wechat public account or the open platform APP. After applying for a public account on the public platform or an APP account on the open platform, Wechat will automatically assign the corresponding appid to identify the application. This field value will also be included in the merchant's WeChat Pay approved email. After the WeChat Pay merchant number mch_id merchant applied for WeChat Pay, the merchant collection account assigned by WeChat Pay. API key key transaction process generates a signed key, which is only retained in the merchant system and WeChat Pay background, and will not be propagated in the network. Merchants take good care of the Key, do not transmit in the network, can not be stored in other clients, to ensure that the key will not be leaked. Merchants can log in to Wechat Merchant platform to make settings according to email prompts. AppsecretsecretAppSecret is the API password corresponding to APPID, which is used to obtain the credential access_token for calling the API. In WeChat Pay, you first obtain the user openid through the OAuth3.0 API, which is used for the API for issuing orders in Wechat's web payment mode. Get the AppSecret in the development mode (become a developer and the account has no abnormal status).

After these are completed, we also need to learn about a business process of official account payment:

The main interaction between merchant system and WeChat Pay system:

1. Merchant server calls unified order issuing API to request an order. For api, please see Public api [Unified order API]. Before requesting a prepaid order, we need to call Wechat OAuth3.0 web page authorization to obtain user Wechat OpenId, which is not detailed here. The following is the code implementation of issuing an order with prepaid payment:

String timeStamp = TenPayUtil.GetTimestamp (); string nonceStr = TenPayUtil.GetNoncestr (); string paySign = string.Empty; / / create payment reply object var packageReqHandler = new RequestHandler (null); string spbill_create_ip = Request.UserHostAddress; / / initialization / / packageReqHandler.Init () / / packageReqHandler.SetKey (TenPayInfo.Key); / / set package order parameters packageReqHandler.SetParameter ("appid", appID); / / Public account ID packageReqHandler.SetParameter ("body", StrUtil.GetCutString (productName, 100)); / / No more than 127character packageReqHandler.SetParameter ("mch_id", mchid) / / merchant number packageReqHandler.SetParameter ("nonce_str", nonceStr.ToLower ()); / Random string packageReqHandler.SetParameter ("notify_url", notifyUrl); / / URL packageReqHandler.SetParameter ("openid", openId) that receives notification from Tenpay; / / openid packageReqHandler.SetParameter ("out_trade_no", sp_billno) / / merchant order number / / packageReqHandler.SetParameter ("attach", ""); / / additional data can be used to distinguish different WeChat Pay business packageReqHandler.SetParameter ("spbill_create_ip", spbill_create_ip) in the future. / / the public network ip of the user, not the merchant server IP packageReqHandler.SetParameter ("total_fee", (onlinePayMoney * 100). ToString ("0"); / / the amount of goods in units (money * 100). ToString () packageReqHandler.SetParameter ("trade_type", "JSAPI") / / transaction type / / get package package string sign = packageReqHandler.CreateMd5Sign ("key", TenPayInfo.Key); packageReqHandler.SetParameter ("sign", sign); / / transaction type string data = packageReqHandler.ParseXML (); LoggerHelper.Log (data) / / call unified order issuing API to request order var result = TenPayV3Service.Unifiedorder (data); LoggerHelper.Log (result); var res = XDocument.Parse (result); string prepayId = string.Empty If (res.Element ("xml"). Element ("return_code"). Value = = "SUCCESS") {prepayId = res.Element ("xml"). Element ("prepay_id"). Value;} string package = string.Format ("prepay_id= {0}", prepayId); timeStamp = TenPayUtil.GetTimestamp () / / set payment parameters var paySignReqHandler = new RequestHandler (null); paySignReqHandler.SetParameter ("appId", appID); paySignReqHandler.SetParameter ("timeStamp", timeStamp); paySignReqHandler.SetParameter ("nonceStr", nonceStr); paySignReqHandler.SetParameter ("package", package); paySignReqHandler.SetParameter ("signType", "MD5") PaySign = paySignReqHandler.CreateMd5Sign ("key", TenPayInfo.Key); / / pass the information to the payment page ViewBag.appId = appID; ViewBag.timeStamp = timeSt ViewBag.nonceStr = nonceStr; ViewBag.package = package; ViewBag.paySign = paySign

The following is the code related to the page js:

/ / the WeixinJSBridgeReady event will be triggered when the internal initialization of Wechat's built-in browser is completed. Document.addEventListener ('WeixinJSBridgeReady', function onBridgeReady () {$(function () {/ / official account payment jQuery (' # getBrandWCPayRequest') .click (function (e) {WeixinJSBridge.invoke ('getBrandWCPayRequest', {"appId": "@ ViewBag.appId") / / official account name "timeStamp": "@ ViewBag.timeStamp", / / timestamp "nonceStr": "@ ViewBag.nonceStr", / / random string "package": "@ Html.Raw (ViewBag.package.ToString ())", / / expansion pack "signType": "MD5" / / Wechat signature method "paySign": "@ ViewBag.paySign" / / Wechat signature}, function (res) {if (res.err_msg = = "get_brand_wcpay_request:ok") {/ / alert ("WeChat Pay succeeds!") _ window.location.href = "@ WxPaySettingConfig.WmallURL/Wmall/TradePay/Success/@ViewBag.ShopId/?orderNo=@orderNoMark";} else if (res.err_msg = = "get_brand_wcpay_request:cancel") {/ / alert ("user cancels payment!") } else {_ window.location.href = "/ wxpay/jsapi/error/?isPayFail=1&csid=@ViewBag.ShopId&orderNo=@orderNoMark&biztype=1" } / / using the above method to determine the return of the frontend, Wechat team solemnly reminds: res.err_msg will return ok after the user pays successfully, but there is no guarantee that it is absolutely reliable. / / therefore, the Wechat team recommends that when the ok is returned, ask the merchant backend whether you have received the notification of a successful transaction. If so, the front end displays the interface of the successful transaction. If the notification is not received at this time, the merchant backend actively calls the API to query the order to query the current status of the order, and feedback it to the frontend to show the corresponding interface. }); / / WeixinJSBridge.log ('yo~ ready.');}, false)

two。 Merchant server receives payment notification. For api, please see Public api [payment result Notification API].

[HttpPost] public void NoticeUrl () {string xmlString = HttpClientHelper.GetPostString (Request); 5 / / log LoggerHelper.Log (string.Format ("[micro-payment] asynchronous notification parameter: {0}", xmlString)); 8 var returnMsg = new ReturnMessage () {Return_Code = "SUCCESS", Return_Msg = string.Empty} / / notify the message entity NotifyMessage message = null; / / the global variable within the method related to order processing bool isNeedDeal = false; / / identifies whether the order needs to be processed string orderNo = string.Empty; / / order number (the order needs to be judged according to the merchant packet field) CorpSalesOrder saleOrder = null Try {message = HttpClientHelper.XmlDeserialize (xmlString); / / the order number gets orderNo = message.Out_Trade_No; if (string.IsNullOrEmpty (orderNo)) {throw new InvalidOperationException ("order information not found.") } 45 var doc = new XmlDocument (); doc.LoadXml (xmlString); var dic = new Dictionary (); string sign = string.Empty Foreach (XmlNode node in doc.FirstChild.ChildNodes) {if (node.Name.ToLower ()! = "sign") dic.Add (node.Name, node.InnerText); else sign = node.InnerText } UnifiedWxPayModel model = UnifiedWxPayModel.CreateUnifiedModel (xddAppId, xddMchid, xddWxkey) If (model.ValidateMD5Signature (dic) Sign) {/ / process notification business logic: if (message.Return_Code = = "SUCCESS") {if (message.Result_Code = = "SUCCESS") { / / Business logic after successful payment is processed here} else {throw new InvalidOperationException (string.Format ("{0}: {1}") Message.Err_Code, message.Err_Code_Des)) }} else {throw new InvalidOperationException (message.Return_Msg) } catch (InvalidOperationException e) {/ / record exception log here returnMsg.Return_Code = "FAIL"; returnMsg.Return_Msg = e.Message LoggerHelper.Log ([WeChat Pay Asynchronous Notification] error, order number: "+ orderNo +", error reason: "+ e.Message);} catch (Exception e) {/ record exception log here returnMsg.Return_Code =" FAIL "; returnMsg.Return_Msg = e.Message LoggerHelper.Log ("[WeChat Pay Asynchronous Notification]] error, order number:" + orderNo + ", error reason:" + (e.InnerException = = null? E.Message: e.InnerException.ToString ());} Response.Write (returnMsg.ToXmlString ()); Response.End () } this is the end of the article on "example Analysis of WeChat Pay developed by Wechat official account". I hope the above content can be helpful to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.

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