SoFunction
Updated on 2025-03-09

Steps to use WeChat Pay and Alipay payment for WeChat public account h5 (front end)

plan:

1. WeChat Payment

Considering the authorization issue, WeChat Pay uses JS-SDK to make payments

2. Alipay payment

Question: After h5 WeChat authorization, you can no longer open the payment link of Alipay directly with WeChat browser.

Solution: Use an intermediate page to point to pay by jumping to the browser

Implementation:

1. WeChat Pay:

The first step is WeChat authorization, add route interception and obtain code. The specific code is as follows ↓

// 
(async (to: RouteLocationNormalized,from: RouteLocationNormalized,next) => {
    // Determine whether there is openId, that is, authorize direct release    if () {
        next()
    } else {
        // No authorization to obtain code and release it        const code = await getCode()
        await queryInfo(code)
        next()
    }
})

// Get codefunction getCode() {
    const code = getUrlCode()?.code
    if (!code) {
        // No code requests the backend interface to link and jump to get the code (the link value is the authorization link of WeChat. After successful authorization, it will jump back to the callback address, and the code parameters will be carried on the callback address)        return getWxOauthUrl({
            redirectUrl: 
        }).then(async ({data}) => {
            if ( === 0) {
                ()
            }
        })
    } else {
        return code
    }
}

// Get user information through codefunction queryInfo(code: string) {
    return getUserInfo([code]).then(({data}) => {
        const result =  || {}
        ('getUserInfo', result)
        ('getUserOpenId', )
    })
}

// General method to get url parametersfunction getUrlCode() {
    // Intercept the code method in the url    const url = ;
    const theRequest = new Object();
    if (("?") !== -1) {
        const str = (1);
        const strs = ("&");
        for (let i = 0; i < ; i++) {
            theRequest[strs[i].split("=")[0]] = strs[i].split("=")[1];
        }
    }
    return theRequest;
}

Payment process can be carried out after the authorization is successful

Core code

// First introduce WeChat JS-SDK in
<script src="/open/js/jweixin-1.6."></script>

// Then add the following code to the payment logic ~
if (typeof WeixinJSBridge == "undefined") {
               if () {
                  ('WeixinJSBridgeReady', onBridgeReady, false);
                } else if () {
                  ('WeixinJSBridgeReady', onBridgeReady);
                  ('onWeixinJSBridgeReady', onBridgeReady);
                }
              } else {
                onBridgeReady();
              }

function onBridgeReady(result) {
              ('getBrandWCPayRequest', {
                "appId": ,   //The official account ID, transferred to the merchant                "timeStamp": ,   // Time stamp, seconds since 1970                "nonceStr": ,      //Random string                "package": ,
                "signType": ,     //WeChat signature method:                "paySign": 
              },
              function (res) {
                if (( || res.err_msg) === "get_brand_wcpay_request:ok") {
                  // Use the above method to judge the front-end return, the WeChat team solemnly reminds:                  //res.err_msg will return ok after the user pays successfully, but it does not guarantee that it is absolutely reliable.                  
                }
              });
            }

This way, WeChat payment is over

2. Alipay payment:

Because it is on the h5 page after WeChat authorization, payment cannot be made directly on the WeChat page

So the first step is to jump to the middle page when clicking on payment.

First define an intermediate page:

Note: Put this page in the publish directory

// Jump to the middle page and bring the parameters requested to pay with them.(`${}/?params=${encodeURIComponent((params))}`)

The core content is as follows

let getQueryString = function (url, name) {
        let reg = new RegExp("(^|\\?|&)" + name + "=([^&]*)(\\s|&|$)", "i");
        if ((url)) return RegExp.$(/\+/g, " ");
    };

    // Get the form returned by the interface and make payment    function handlePayForm(data) {
        const div = ("div");
        ("id", "payContainer");
         = data
        (div);
        const payContainer = ("#payContainer");
        const submit = (
            'form[name="punchout_form"] input[type="submit"]'
        );
        ();
        setTimeout(function () {
            ();
        }, 500);
    };
    if (('error') !== -1) {
        alert('Parameter error, please check');
    } else {
        // Determine whether the current browser environment is a WeChat browser        let ua = ();
        let tip = (".weixin-tip");
        let tipImg = (".J-weixin-tip-img");
        const query = (decodeURIComponent(getQueryString(, 'params')))

        if (('micromessenger') !== -1) {
            // If it is a page in WeChat, give a guide (please pay through the browser)            // This page is defined by yourself        } else {
            // OK, this is an external browser, requesting the interface to get the payment from form            axios({
                url: '',
                data: query,
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                }
            }).then(({data}) => {
                if ( === 0) {
                    // The form form returned by the backend is used to pay                    if ( &&  === "SUCCESS") {
                        // ==> is a payment from form                        handlePayForm()
                    }
                }
            })
        }
    }

This way you can jump to the external browser of WeChat for normal payment functions

Summarize

This is the article about the use of WeChat payment and Alipay payment for WeChat public account h5. For more information about the use of WeChat payment for WeChat and Alipay payment for related public account h5, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!