Due to business needs, WeChat payment function is developed, which involves three payment methods:

  • JSAPI payment: WeChat webpage payment, need to open WeChat service number
  • Small program pay: pay in small program, need to open small program
  • H5 payment: in the mobile browser (WeChat internal network) in the web page payment

The premise of using WeChat payment must open WeChat merchant number, to use that payment method must be opened in the merchant platform (to review).

The money paid will eventually go to the merchant number (generally opened by the company finance).

WeChat payment in the process of large and small pit or step on a lot of, finally finished, sort out the development process.

Reference:

  • WeChat Payment – Access Guide
  • WeChat Payments – Development documentation

Applet payment

The development process

  1. Small program end request to create an order interface, the back end unified order accessorderIdAnd return
  2. The applet side gets throughwx.login()To obtaincode
  3. The applet side takes thiscodeandorderIdRequest the backend interface to obtain the required data for payment
  4. After obtaining the data required for payment, the applet side calls the wx.requestPayment() interface and calls the payment page directly
  5. Determining whether payment is successful after the logic

Pseudo code

async function wxPay(goodId) { // 1. Create order for orderId let orderId = await ajax (" POST ", "/ API/OrderProgram/CreateTheOrder", {goodId, / / commodity id}); // 2. Get code let code = await wxlogin(); / / based on pr encapsulated wx. Login / / 3. () method to obtain payment data let payData = await ajax (" POST ", "/ API/OrderProgram/WxXcxPay", {orderId, code, }); Let res = await payment(payData); // WX.requestPayment () method based on PR encapsulation // 5. Let payResult = res.errmsg; If (payResult == "RequestPayment: OK ") {console.log(" Payment was successful "); } else if (PayResult == "RequestPayment: Fail cancel") {console.log(" User cancels payment "); } else {console.log(" Payment failed "); }}

Matters needing attention

  1. If you apply for WeChat small program account successfully, you can get AppID (small program ID) and AppSecret (small program key). The application type is enterprise nature, otherwise you cannot access WeChat Pay
  2. WeChat small program certification through the certification of small program can be connected to WeChat payment and binding merchant platform
  3. To apply for a merchant platform account, you need the APPID that you applied for in the first step. If the application is successful, you can get MCHID (merchant ID) and MCHKEY (merchant key).
  4. After the merchant number associated with the letter applet WeChat and has been successfully verified, the merchants will be associated in the WeChat background WeChat payment menu
  5. Connect WeChat Pay and access it in WeChat background WeChat payment menu

reference

  • Small program payment documents
  • Small program development documentation

H5 pay

The development process

  1. Front-end request to create order interface, back-end unified order acquisitionorderIdAnd return
  2. Front end withorderIdRequest payment interface, getmweb_url.
  3. Then jumpmweb_urlIt’s going to jump to WeChat and automatically call the WeChat payment
  4. After the payment, return to the payment page and judge whether the payment is successful (request back-end query should be sent). 4.1 Refresh the page and get the latest payment (order) status. 4.2 Set a button “I have paid”, let the user click the automatic query status.

Pseudo code

async function wxH5Pay(goodId) { // 1. Create order for orderId let orderId = await ajax (" POST ", "/ API/OrderProgram/CreateTheOrder", {goodId, / / commodity id}); / / 2. Get pay jump URL let mweb_url = await ajax (" POST ", "/ API/OrderProgram/WxH5Pay", {orderId}); If (mweb_url) {location.href = mweb_url; } else {console.log(" Wrong address for callback "); } // 4. After the payment, return to the payment page and judge whether the payment is successful // 4.1 Refresh the page to get the latest order (product) status. // 4.2 Set a "I have paid" button, let the user click and check the status. }

Matters needing attention

  • Set the correct payment domain name on the merchant platform
  • Debugging needs to be done online, if you bother you can use Intranet penetration (Ngrok or peanut shell)
  • toredirect_urlforurlencodeTo deal with
  • H5 payment cannot be started directly in the WeChat client, please start it in the external browser.

reference

  • WeChat Payments -H5 Payments – Development steps

JSAPI payment (WeChat webpage payment)

The development process

  • Commodity page
  1. Front-end product page to create an order, the back end after the unified order to obtainorderId
  2. Front end withorderIdJump to the payment page,
  • Payment page
  1. Access code

    1. The first time you enter the page, determine if there is one in the pathcode
    2. There is nocode, request data jump authorization page,codeWill be returned together by the callback address
    3. getcode, and send it to the back end, which parses to itopenidKeep it.
  2. Click the OK Pay button to trigger the wxPay() method

    1. sendorderIdTo the back end, getwxData
    2. wxDataContained in thewx.configwx.chooseWXPayData for both interfaces.
    3. First callwx.config()And then in the callwx.chooseWXPay()If all is well, the payment page will pop up.
  3. Payment status is queried through the back end

Pseudo code

  • Commodity page
/ / 1. Create orders for orderId let orderId = await ajax (" POST ", "/ API/OrderProgram/CreateTheOrder", {goodId, / / commodity id}); This.$router. Push ({name: "wx_pay_page", params: {orderId: id}});
  • Entry file (main.js)
// main.js import wx from "weixin-js-sdk"; // main.js import wx from "weixin-js-sdk";
  • Pay the HTML page
<template> <div> <button @click="wxPay"> </button> </div> </template>

JS payment page

// Vue data(){return {orderId: this.$route.params.orderId, // orderId url: "",// get code url wxData:" }}, mounted(){// Code this.getCode()} methods: { getCode() { var code = this.getUrlPram("code"); if (code ! = null) { this.code = code; // Get the code and send it to the backend this.sendCode(code); } else {// Go get code this.getUrl(); }}, getUrl() {// Request the backend to get the URL required data, then jump to the page and return via the callback address, Access code. This. Axios. Post ("/API/OrderProgram GetOpenidAndAccessToken ", {orderId: this.orderId, }) .then((data) => { this.url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${data.appId}&redirect_uri=${data.redirect_uri}&response_type =${data.response_type}&scope=${data.scope}&state=${data.state}`; window.location.href = this.url; }) .catch((err) => { console.log(err); }); }, sendCode (code) {/ / send code to the back-end back-end parsing out the openid enclosing axios. Post ("/API/OrderProgram GetOpenidAndAccessTokenFromCode ", { code: code, }) .then((res) => { console.log(res); }) .catch((err) => { console.log(err); }); }, wxPay: Async function() {// Send orderId, For wx. ChooseWXPay and wx. Config parameters needed this. WxData = await this. Axios. Post ("/API/OrderProgram WxJSAPIPay ", {orderId: this.orderId } ); WxConfigData = this.wxData.wxConfigData () let wxPayData = this.wxData.wxConfigData () let wxPayData = this.wxData.wxPayData (); $this.$wx. Config ({debug: False, // When debug mode is enabled, the return value of all API calls will come out in client alert. To view the parameters passed in, you can open it on PC. The parameter information will be printed via log, and it will only be printed on PC. Timestamp: wxconfigdata. appId, // required, timestamp: wxconfigdata. timestamp, // required, generate signature timestamp nonceStr: WxConfigData. nonCestr, // mandatory, signature: wxConfigData.paySign, // mandatory, signature jSapilist: [" ChooseWxPay ",],}); $wx.chooseWXPay({timestamp: wxpaydata.timestamp, // pay the signature timestamp, note that all timestamp fields used in WeChat JSSDK are lowercase. NonceStr: wxpaydata.noncestr, // payment signature random string, no longer than 32 bits Wxpaydata.package, // the prepay_id parameter returned by the unified payment interface, the submission format is: prepay_id=\*\* *) signType: SignType, // The default is 'SHA1'. To use the new payment, you need to pass in 'MD5' PaySign: wxPayData.PaySign, // Payment Signature Success: (res) = bb0 {this.$toast($toast); }, fail: (err) => {this.$toast(" failed to pay "); }}); }},

Support both H5 payment and JSAPI payment

// After the order is created, determine which method the environment uses to pay. if (isWx()) { this.WXPay(orderId); } else {this.H5pay (orderId);} else {this.H5pay (orderId); / / after the execution of H5 pay above create order logic} / / judge whether WeChat browser function isWx () {let uAgent. = the navigator userAgent. ToLowerCase (); reutrn(/micromessenger/.test(uAgent)) ? true : false; }

Matters needing attention

  • Open WeChat merchant number – set the payment directory (if it is a SPA page like Vue, go to the root directory, that is, the address before the # sign)
  • Open WeChat public account (service number) – set the secure domain name, set the authorized domain name
  • Collection parameters: AppID and AppSecret
  • Add a reference document to the Web development tool developer (requires the developer to pay attention to the development of WeChat public account and WeChat public account security assistant) [Image upload failed…(image-b07878-1605777597831)]
  • Set the callback domain name (for example:www.xx.com/pay, the code obtained last will be spelled in the callback address returned, returned as followswww.xx.com/pay?code=xxxx)Reference 1

  • Access code

    • Refer to the Code documentation
    • Open the authorization address in the WeChat client web page. After the jump, get it after the return callback addresscode:
https://open.weixin.qq.com/connect/oauth2/authorize? Appid = your appid & redirect_uri = your callback address after obtaining code (return) &response_type=code (return type, default code) &scope=snsapi_base (scope of authorization, silent authorization taken to openID) &state= state (custom state, #wechat_redirect (redirect use must be carried)

The redirect_uri parameter should be the same as the callback domain name you set in the WeChat public account (for example: www.xx.com/pay). Note that the URL requires urlEncode.

When you request this address, the code will be brought back as an argument to the redirect_uri address you set, and then passed on to the back end.

  • The front end introduces JS-SKD

    • usescriptThe introduction ofjs-sdk
    • Download the usenpm 包weixin-js-sdk
  • To obtainwx.configThe parameters of the

  • To obtainwx.chooseWXPayRequired parameters

reference

  • WeChat Payments -JSAPI
  • WeChat official account – webpage authorization
  • JS-SDK development documentation

conclusion

The whole process down, give my experience is: small program pay the most aspects (because the configuration is less), followed by H5, JSAPI pay the most troublesome (more than half of the article is written about it)

In WeChat payment function development process, in fact, the most troublesome is not the development process, but his various configuration and authorization process, in order to get the required parameters and back and forth.

Some parameters are often used in the development process, such as appid, openid, and orderId

The payment process is the same in large diameter. First, get the user’s OpenID to know who you are, then place an order and get the OrderID together, and then deal with the payment methods of different platforms

Development of the relevant documents used, must be carefully read more than two times so far!!

Don’t die encountered problems just, more Baidu more Google, you may not be able to say that the problem you have encountered countless people have met and have a mature solution.

The front end and the back end should communicate more, and give feedback at any time if there are any problems (difficulties), and tell what parameters are needed well. When the views are not consistent, we should pay attention to control our emotions and avoid quarreling (…). .

Due to my limited level, I do not know much about the back-end process, so I can only sort out the whole payment process from the perspective of the front-end.

Above, hope to be helpful to you.