Due to business needs, we developed wechat payment function, involving three payment methods:

  • JSAPI payment: wechat webpage payment, need to open wechat service number
  • Small program payment: in the small program payment, need to open a small program
  • H5 payment: pay on the web page in the mobile browser (out of wechat Intranet)

The prerequisite for using wechat pay is to open a wechat merchant number, and to use that payment method, you need to open it on the merchant platform (to be audited).

The money paid will end up in the merchant number (usually opened by the company finance).

The development of 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 Pay – Access guidelines
  • Wechat Pay – Develop documentation

Applets payment

The development process

  1. Small program end request to create order interface, unified backend order to obtainorderIdAnd return
  2. Small program side get throughwx.login()To obtaincode
  3. Small program end take thiscodeandorderIdRequest the back-end interface to get the data required for payment
  4. After obtaining the data required for payment, the applet side calls the wx.requestPayment() interface and invokes the payment page directly
  5. The logic after determining whether the payment is successful

Pseudo code

async function wxPay(goodId) {
  // 1. Create order to obtain orderId
  let orderId = await ajax("POST"."/api/OrderProgram/CreateTheOrder", {
    goodId, Id / / commodities
  });
  // 2. Get code
  let code = await wxlogin(); // Wx.login () method based on pr encapsulation
  // 3. Get payment data
  let payData = await ajax("POST"."/api/OrderProgram/WxXcxPay", {
    orderId,
    code,
  });
  // 4. Initiate payment
  let res = await payment(payData); // Wx.requestPayment () based on PR encapsulation
  // 5. Check whether the payment is successful
  let payResult = res.errMsg;
  if (payResult == "requestPayment:ok") {
    console.log("Payment successful");
  } else if (payResult == "requestPayment:fail cancel") {
    console.log("User cancels payment");
  } else {
    console.log("Payment failure"); }}Copy the code

Matters needing attention

  1. AppID (mini program ID) and AppSecret (mini program key) can be obtained after successful application. The application type is enterprise; otherwise, wechat Payment cannot be accessed
  2. Only authenticated small programs can be connected to wechat Pay and bound merchant platforms
  3. Application for merchant platform account requires the AppID applied in the first step. MchID (merchant ID) and MchKey (merchant key) can be obtained after successful application.
  4. When both wechat and merchants are authenticated successfully, they will be associated in the wechat payment menu in the wechat background
  5. Access to wechat Pay Access to wechat Pay menu in the wechat background

reference

  • Applet payment document
  • Applets development documentation

H5 pay

The development process

  1. Front-end request to create order interface, back-end unified order to obtainorderIdAnd return
  2. Front end withorderIdRequest payment interface, obtainmweb_url.
  3. Then jumpmweb_urlIt will jump to wechat and automatically call wechat Pay
  4. 4.1 Refresh the page to obtain the latest payment (order) status. 4.2 Set up a button “I have paid”, let the user click automatic query status.

Pseudo code

async function wxH5Pay(goodId) {
  // 1. Create order to obtain orderId
  let orderId = await ajax("POST"."/api/OrderProgram/CreateTheOrder", {
    goodId, Id / / commodities
  });
  // 2. Get the payment jump URL
  let mweb_url = await ajax("POST"."/api/OrderProgram/WxH5Pay", { orderId });
  // 3. Redirect the URL to wechat pay
  if (mweb_url) {
    location.href = mweb_url;
  } else {
    console.log("Callback address error");
  }
  // 4. Return to the payment page after payment to judge whether the payment is successful
  // 4.1 Refresh the page to obtain the latest order (product) status.
  // 4.2 Set up a "I have paid" button, let the user click after the query status.
}
Copy the code

Matters needing attention

  • Set up the correct payment domain name on the merchant platform
  • Debugging needs to be online, if too much trouble can use internal penetration (Ngrok or peanut shell)
  • toredirect_urlforurlencodeTo deal with
  • H5 payment cannot be initiated directly in wechat client, please initiate it in external browser.

reference

  • Wechat Pay -H5 pay – development steps

JSAPI Payment (wechat webpage payment)

The development process

  • Commodity page
  1. Create orders on the front commodity page, and obtain orders on the back endorderId
  2. Front end withorderIdJump to the Payment page,
  • Payment page
  1. To obtaincode
    1. Enter the page for the first time and check whether there is a pathcode
    2. There is nocode, request data jump authorization page,codeWill be returned together by the callback address
    3. getcode, sent to the back end, which parses toopenidKeep it well.
  2. Click the Ok payment button to triggerwxPay()methods
    1. sendorderIdTo the back end, fetchwxData
    2. wxDataContained in thewx.configwx.chooseWXPayData for both interfaces.
    3. First callwx.config()And then callwx.chooseWXPay()If everything works, the payment page will pop up.
  3. Payment status is queried through the backend

Pseudo code

  • Commodity page
// 1. Create order to obtain orderId
let orderId = await ajax("POST"."/api/OrderProgram/CreateTheOrder", {
  goodId, Id / / commodities
});
// 2. Jump to the payment page with id
this.$router.push({ name: "wx_pay_page".params: { orderId: id } });
Copy the code
  • Entry Document (main.js)
// main.js introduces js-sdk
import wx from "weixin-js-sdk";
Copy the code
  • Pay the HTML page
<template>
  <div>
    <button @click="wxPay">Click on the pay</button>
  </div>
</template>
Copy the code

JS payment page

// Vue
data(){
    return {
        orderId: this.$route.params.orderId, / / order id
        url: ' '.// Get the url of code
        wxData: null.// Data required by the Js-SDK interface}},mounted(){
    // Check if there is 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 {
            / / to take code
            this.getUrl(); }},getUrl() {
        // Request the backend to get the required url data, then jump to the page through the callback address back, get the 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 the code to the back end. The back end parses the OpenID
        this.axios
            .post("/api/OrderProgram/GetOpenidAndAccessTokenFromCode", {
                code: code,
            })
            .then((res) = > {
                console.log(res);
            })
            .catch((err) = > {
                console.log(err);
            });
    },
    wxPay: async function() {
        // Send orderID to get the parameters required for wx.chooseWxpay and wx.config
        this.wxData = await this.axios.post(
            "/api/OrderProgram/WxJSAPIPay",
            { orderId: this.orderId }
        );
        let wxConfigData = this.wxData.wxConfigData // Get the data required by wx.choosewxpay ()
        let wxPayData = this.wxData.wxPayData;// Get the data required by wx.config()
        this.$wx.config({
            debug: false.// If debug mode is enabled, the return value of all API calls will be displayed in the client alert. If you want to view the parameters passed in, you can open it in the PC, and the parameter information will be printed in the log.
            appId: wxConfigData.appId, // Mandatory, the unique identifier of the public account
            timestamp: wxConfigData.timeStamp, // Mandatory to generate the timestamp of the signature
            nonceStr: wxConfigData.nonceStr, // Mandatory to generate a random string of signatures
            signature: wxConfigData.paySign, // Mandatory, signature
            jsApiList: [
                "chooseWXPay",]});// Execute the payment
        this.$wx.chooseWXPay({
            timestamp: wxPayData.timeStamp, // Payment signature timestamp, note that all use timestamp fields in wechat JSSDK are lowercase. But the latest version of the payment background generated signature timeStamp field name needs to capitalize the S character
            nonceStr: wxPayData.nonceStr, // The payment signature is a random string, no longer than 32 bits
            package: wxPayData.package, // The prepay_id parameter returned by the unified payment interface is submitted in the format prepay_id=\*\* *)
            signType: wxPayData.signType, // Signature mode, default is 'SHA1', use the new version of payment to pass 'MD5'
            paySign: wxPayData.paySign, // Pay the signature
            success: (res) = > {
                this.$toast("Payment successful");
            },
            fail: (err) = > {
                this.$toast("Payment failure"); }}); }},Copy the code

Both H5 payment and JSAPI payment are supported

// After the order is created, determine which method the environment uses to pay for it.
if (isWx()) {
  this.WXPay(orderId); // Jump to the payment page logic with orderId
} else {
  this.H5Pay(orderId); Execute the logic after creating the order in H5 payment above
}
// Check whether it is wechat browser
function isWx() {
  let uAgent = navigator.userAgent.toLowerCase();
  reutrn(/micromessenger/.test(uAgent)) ? true : false;
}
Copy the code

Matters needing attention

  • [image-4cfca7-1605777597831] [image-4cfca7-1605777597831] [image-4CFca7-1605777597831]

  • [image-db9786-1605777597831] [image-DB9786-1605777597831]

  • Collection parameters: appId and AppSecret

  • Add Web development tool developers (need developers to focus on the development of wechat public account and wechat public account security assistant) reference document [image-b07878-1605777597831]

  • Set the callback domain name (for example: www.xx.com/pay, the last obtained code will be spelled with this callback address and returned as www.xx.com/pay?code=xxxx) refer to 1 [image-d619b7-1605777597831]

  • Access code

    • Refer to the code document

    • Open the authorized address in the wechat client web page, jump, and get the code after the returned callback address:

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 &state= state (custom state, default code) &response_type=code (return type, default code) &scope=snsapi_base Optional) #wechat_redirect (Redirects must be carried)Copy the code

The redirect_uri parameter should be the same as the callback domain you set in your wechat account (for example: www.xx.com/pay). Note that the URL needs to be urlEncode.

After requesting this address, the code will be brought back with the parameters in the redirect_URI address you set, and passed to the back end.

  • The front end introduces JS-SKD

    • usescriptThe introduction ofjs-sdk
    • Download the usenpm 包weixin-js-sdk
  • [image-6f3528-1605777597831] [image-6f3528-1605777597831]

  • Get the parameters required for wx. ChooseWXPay

reference

  • Wechat Pay -JSAPI
  • Wechat official account – Webpage authorization
  • Js-sdk development documentation

conclusion

The whole process came down, giving me the experience is: small program payment is the most aspect (because of less configuration), followed by H5, JSAPI payment is the most troublesome (most of the article was written about it)

In the development process of wechat payment function, the most troublesome is not the development process, but its various configuration and authorization process, in order to get the required parameters.

Some of the parameters in the development process are frequently used, such as AppID, OpenID, orderId

The payment process is basically the same. First get the openID of the user, know who you are, and then place the unified order and get the orderId, and then deal with the payment methods of different platforms

Development of related documents, must carefully read more than two times!!

Do not die when you encounter problems, more baidu more Google, you may have encountered countless people have encountered the problem and have a mature solution.

Front-end and back-end to communicate more, there is any problem (difficult) feedback at any time, what parameters need to say well, when the point of view is not consistent, do not pay attention to the control of emotions, do not quarrel (. .

Because of my limited level, I don’t 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 help you.