WeChat payment for WeChat public account development
Feb 22, 2017 pm 04:02 PMA few days ago, due to company project requirements, I wanted to create a function for online recharge using WeChat. This is to click on a web page in the WeChat browser to call up WeChat payment. Now let’s briefly talk about WeChat payment public account payment ’s development process:
First of all, your official account must be a certification service account, and must have the permission for WeChat payment; before developing and writing the code, we must make some payment-related The information is set up to facilitate subsequent operations. After is activated, WeChat will send you an email, which contains some information related to the background login of your official account merchant platform. After logging in to the merchant platform, go to -> ;Account Settings->API SecuritySet the key in it, which will be used later;
API parameter name | Detailed description | |
---|---|---|
appid | appid is the unique identifier of the WeChat public account or open platform APP. Apply for a public account on the public platform or in After applying for 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 Payment approval email. | |
mch_id | The merchant’s payment account assigned by WeChat Pay after the merchant applies for WeChat Pay. | |
key | The signature key generated during the transaction process is only retained in the merchant system and WeChat payment background, and will not be stored on the network spread in. The merchant must keep the key properly and do not transmit it on the network or store it in other clients to ensure that the key will not be leaked. Merchants can log in to the WeChat merchant platform according to the email prompts to set up. | |
secret | AppSecret is the interface password corresponding to the APPID, which is used to obtain the interface call credential access_token. In WeChat payment, the user's openid is first obtained through the OAuth2.0 interface. This openid is used by the order interface in the web payment mode within WeChat. Obtain the AppSecret in development mode (become a developer and the account has no abnormal status). |
After completing these, we still need to understand a business process of official account payment:
##Main interactions between merchant system and WeChat payment system:
1. The merchant server calls the unified ordering interface to request an order. For the API, please refer to the public api [Unified Ordering API]; before requesting a prepaid order, we need to call the WeChat OAuth2.0 web page to authorize the user to obtain the user's WeChat OpenId. This will not be explained in detail here. The following is the code implementation for prepaid orders:
string timeStamp = TenPayUtil.GetTimestamp(); string nonceStr = TenPayUtil.GetNoncestr(); string paySign = string.Empty; //創(chuàng)建支付應答對象 var packageReqHandler = new RequestHandler(null); string spbill_create_ip = Request.UserHostAddress; //初始化 //packageReqHandler.Init(); //packageReqHandler.SetKey(TenPayInfo.Key); //設置package訂單參數 packageReqHandler.SetParameter("appid", appID); //公眾賬號ID packageReqHandler.SetParameter("body", StrUtil.GetCutString(productName, 100)); //不能超過127個字符 packageReqHandler.SetParameter("mch_id", mchid); //商戶號 packageReqHandler.SetParameter("nonce_str", nonceStr.ToLower()); //隨機字符串 packageReqHandler.SetParameter("notify_url", notifyUrl); //接收財付通通知的URL packageReqHandler.SetParameter("openid", openId); //openid packageReqHandler.SetParameter("out_trade_no", sp_billno); //商家訂單號 // packageReqHandler.SetParameter("attach", ""); //附加數據 未來可用于區(qū)分不同微信支付業(yè)務 packageReqHandler.SetParameter("spbill_create_ip", spbill_create_ip); //用戶的公網ip,不是商戶服務器IP packageReqHandler.SetParameter("total_fee", (onlinePayMoney * 100).ToString("0")); //商品金額,以分為單位(money * 100).ToString() packageReqHandler.SetParameter("trade_type", "JSAPI"); //交易類型 //獲取package包 string sign = packageReqHandler.CreateMd5Sign("key", TenPayInfo.Key); packageReqHandler.SetParameter("sign", sign); //交易類型 string data = packageReqHandler.ParseXML(); LoggerHelper.Log(data); //調用統(tǒng)一下單接口請求訂單 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(); //設置支付參數 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); //將信息傳遞給支付頁面 ViewBag.appId = appID; ViewBag.timeStamp = timeStamp; ViewBag.nonceStr = nonceStr; ViewBag.package = package; ViewBag.paySign = paySign;
##The following is the page js related code:
<script type="text/javascript"> // 當微信內置瀏覽器完成內部初始化后會觸發(fā)WeixinJSBridgeReady事件。 document.addEventListener('WeixinJSBridgeReady', function onBridgeReady() { $(function () { //公眾號支付 jQuery('#getBrandWCPayRequest').click(function (e) { WeixinJSBridge.invoke('getBrandWCPayRequest', { "appId": "@ViewBag.appId", //公眾號名稱 "timeStamp": "@ViewBag.timeStamp", //時間戳 "nonceStr": "@ViewBag.nonceStr", //隨機串 "package": "@Html.Raw(ViewBag.package.ToString())",//擴展包 "signType": "MD5", //微信簽名方式 "paySign": "@ViewBag.paySign" //微信簽名 }, function (res) { if (res.err_msg == "get_brand_wcpay_request:ok") { //alert("微信支付成功!"); window.location.href = "@WxPaySettingConfig.WmallURL/Wmall/TradePay/Success/@ViewBag.ShopId/?orderNo=@orderNoMark"; } else if (res.err_msg == "get_brand_wcpay_request:cancel") { //alert("用戶取消支付!"); } else { window.location.href = "/wxpay/jsapi/error/?isPayFail=1&csid=@ViewBag.ShopId&orderNo=@orderNoMark&biztype=1"; } // 使用以上方式判斷前端返回,微信團隊鄭重提示:res.err_msg將在用戶支付成功后返回ok,但并不保證它絕對可靠。 //因此微信團隊建議,當收到ok返回時,向商戶后臺詢問是否收到交易成功的通知,若收到通知,前端展示交易成功的界面;若此時未收到通知,商戶后臺主動調用查詢訂單接口,查詢訂單的當前狀態(tài),并反饋給前端展示相應的界面。 }); }); }); //WeixinJSBridge.log('yo~ ready.'); }, false); </script>
2. The merchant server receives the payment notification. For the API, please refer to the public API [
Payment Result Notification API】
[HttpPost] public void NoticeUrl() { string xmlString = HttpClientHelper.GetPostString(Request); 5 //此處應記錄日志 LoggerHelper.Log(string.Format("【微支付】異步通知參數:{0}", xmlString)); 8 var returnMsg = new ReturnMessage() { Return_Code = "SUCCESS", Return_Msg = string.Empty }; //通知消息實體 NotifyMessage message = null; //訂單處理相關的方法內全局變量 bool isNeedDeal = false; //標識訂單是否需要處理 string orderNo = string.Empty; //訂單編號 (需要根據商家數據包字段判斷所屬訂單) CorpSalesOrder saleOrder = null; try { message = HttpClientHelper.XmlDeserialize<NotifyMessage>(xmlString); //訂單號 獲得 orderNo = message.Out_Trade_No; if (string.IsNullOrEmpty(orderNo)) { throw new InvalidOperationException("未找到該訂單信息."); } 45 var doc = new XmlDocument(); doc.LoadXml(xmlString); var dic = new Dictionary<string, string>(); 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)) { //處理通知 業(yè)務邏輯: if (message.Return_Code == "SUCCESS") { if (message.Result_Code == "SUCCESS") { //此處處理支付成功后的業(yè)務邏輯 } 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) { //此處記錄異常日志 returnMsg.Return_Code = "FAIL"; returnMsg.Return_Msg = e.Message; LoggerHelper.Log("【微信支付異步通知】出錯,訂單編號:" + orderNo + ",錯誤原因:" + e.Message); } catch (Exception e) { //此處記錄異常日志 returnMsg.Return_Code = "FAIL"; returnMsg.Return_Msg = e.Message; LoggerHelper.Log("【微信支付異步通知】出錯,訂單編號:" + orderNo + ",錯誤原因:" + (e.InnerException == null ? e.Message : e.InnerException.ToString())); } Response.Write(returnMsg.ToXmlString()); Response.End(); }For more WeChat payment related articles on WeChat public account development, please pay attention to the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Scrapy implements article crawling and analysis of WeChat public accounts. WeChat is a popular social media application in recent years, and the public accounts operated in it also play a very important role. As we all know, WeChat public accounts are an ocean of information and knowledge, because each public account can publish articles, graphic messages and other information. This information can be widely used in many fields, such as media reports, academic research, etc. So, this article will introduce how to use the Scrapy framework to crawl and analyze WeChat public account articles. Scr

The difference between WeChat public account authentication and non-authentication lies in the authentication logo, function permissions, push frequency, interface permissions and user trust. Detailed introduction: 1. Certification logo. Certified public accounts will obtain the official certification logo, which is the blue V logo. This logo can increase the credibility and authority of the public account and make it easier for users to identify the real official public account; 2. Function permissions. Certified public accounts have more functions and permissions than uncertified public accounts. For example, certified public accounts can apply to activate the WeChat payment function to achieve online payment and commercial operations, etc.

Python is an elegant programming language with powerful data processing and web crawling capabilities. In this digital era, the Internet is filled with a large amount of data, and crawlers have become an important means of obtaining data. Therefore, Python crawlers are widely used in data analysis and mining. In this article, we will introduce how to use Python crawler to obtain WeChat public account article information. WeChat official account is a popular social media platform for publishing articles online and is an important tool for promotion and marketing of many companies and self-media.

In today's Internet era, WeChat official accounts have become an important marketing channel for more and more companies. If you want your WeChat official account to implement more functions, you often need to write corresponding interfaces. This article will use PHP language as an example to introduce how to build a WeChat public account API interface. 1. Preparation Before writing the WeChat public account API interface, the developer needs to have a WeChat public account and apply for developer interface permissions in the WeChat public platform. After the application is successful, you can obtain the relevant developer AppID and AppSe

How to use Laravel to develop an online ordering system based on WeChat official accounts. With the widespread use of WeChat official accounts, more and more companies are beginning to use them as an important channel for online marketing. In the catering industry, developing an online ordering system based on WeChat public accounts can improve the efficiency and sales of enterprises. This article will introduce how to use the Laravel framework to develop such a system and provide specific code examples. Project preparation First, you need to ensure that the Laravel framework has been installed in the local environment. OK

The public account can not only post one article per day, but can publish up to eight articles at a time. How to publish multiple articles: 1. Click "Material Management" on the left, and then click "New Graphic and Text Material" to start editing. First article; 2. After editing the first article, click the + sign under the first article on the left and click "Graphic Message" to edit the second article; 3. After finishing multiple images and text, click " Save and send in bulk" to complete the publishing of multiple articles.

With the popularity of the Internet and the widespread use of mobile devices, WeChat official accounts have become an indispensable part of corporate marketing. Through WeChat public accounts, companies can easily interact with users, promote products and services, and increase brand awareness. In order to better develop WeChat public account applications, more and more developers and companies choose to use Go language to build WeChat public account applications. Go language is a programming language developed by Google. Its syntax is concise and suitable for building high-performance, high-concurrency real-time applications. In terms of ease of use and

According to news from this website on August 1, the WeChat Public Platform Operations Center issued an article today saying that the platform found that some articles published by operators contain feudal superstitions and use religion, feng shui, fortune and other gimmicks to make money or gain attention. Such content is very likely Causing misleading or property damage to users. WeChat will conduct continuous inspections, and once any illegal content is discovered, corresponding actions will be taken according to the specific degree of the violation. The violation cases attached to this site are as follows: publishing superstition-related titles, using intimidation, inducement and other tones to exaggerate the harm or negative impact of a certain behavior. ▲Picture source WeChat Public Platform Operation Center, the same article below provides services with feudal superstitions such as fortune telling, fortune telling, and divination, and includes paid items, such as the sale of transshipment and disaster relief products. Improperly collecting users’ personal privacy information in the name of providing relevant services
