Recently in my work, THERE is an H5 page that needs to realize the functions of wechat Payment and Alipay payment. Now it has been completed. Please take some time to write it and share it with those who need it.
Step 1: Determine your current environment
Determine the environment to which the user belongs and execute different payment procedures according to the different environment.
If (/ MicroMessenger/test (window. The navigator. UserAgent)) {/ / alert (' WeChat '); The (} else if (/ AlipayClient/window. The navigator. UserAgent)) {/ / alert (' alipay '); } else {//alert(' other browsers '); }Copy the code
Step 2: If it is wechat environment, you need to conduct webpage authorization first
Detailed introduction of web page authorization can be found in wechat related documents. No introductions here.
Step 3:
1. Wechat Pay
There are two methods for wechat payment: 1: call WeixinJSBridge, the built-in interface provided by wechat browser; 2: introduce wechat JSSDK, use wx.chooseWXPay method, need to verify configuration through config interface injection permission first. I use the first method here. After obtaining the signature and timestamp data from the background, I can directly call WeixinJSBridge, the built-in interface provided by wechat browser, to complete the payment function.
getRequestPayment(data) { function onBridgeReady() { WeixinJSBridge.invoke( "getBrandWCPayRequest", { "appId": Data. appId, // public ID, passed by merchant "timeStamp": data.timeStamp, // timeStamp, number of seconds since 1970 "nonceStr": data.nonceStr, // random string "package": Data. Package, "signType": data. SignType, // wechat signature: "paySign": }, function(res) {alert(json.stringify (res)); // get_brand_wcpay_request if (res.err_msg == "get_brand_wcpay_request: OK ") { //res.err_msg will return OK after the user has paid successfully, but it is not guaranteed to be absolutely reliable. }}); } if (typeof WeixinJSBridge == "undefined") { if (document.addEventListener) { document.addEventListener( "WeixinJSBridgeReady", onBridgeReady, false ); } else if (document.attachEvent) { document.attachEvent("WeixinJSBridgeReady", onBridgeReady); document.attachEvent("onWeixinJSBridgeReady", onBridgeReady); } } else { onBridgeReady(); }},Copy the code
2. Alipay payment
Compared with wechat, the front end of Alipay payment is simpler. The background will return a form to the front end. What we need to do is to submit the form. The relevant codes are as follows:
This.$api.alipaypay (data). Then ((res) => {// console.log(' pay ', res.data) if (res.code == 200) { var resData =res.data const div = document.createElement('div') div.id = 'alipay' div.innerHTML = resData document.body.appendChild(div) document.querySelector('#alipay').children[0].submit() // }}). Catch ((err) => {})Copy the code