Taking UNI-App as an example, this paper introduces wechat applets login, payment (applets, wechat H5, non-wechat H5) instant request encryption method

WeChat login

Wechat has adjusted the API for obtaining user information, so it is not recommended to use the @getUserInfo method of Button and call getUserProfile API of DOM click to obtain user information.

tips: Call getUserProfile to decrypt userInfo information may refresh session_key, so the new code will fail to decrypt, so you need to use the previous code, here we use a simple way, wx.login in the show hook, each authorization is called again. Ensure that the decryption code used to decrypt the message is the same as that used to encrypt it.

<template>
    <button @tap="getWxUserinfo">WeChat login</button>
</template>
Copy the code
export default {
    data() {
        return {
            wxCode: null}},onShow() {
        this.getCode()
    },
    methods: {
        / / get wxCode
        getCode(callback) {
            wx.login({
                success: res= > {
                    this.wxCode = res.code
                    callback && callback(res.code)
                }
            });
        },
        // Get user information
        getWxUserinfo() {
            wx.getUserProfile({
                desc: 'To improve user profile'.success: res= > {
                    console.log(res)
                    wx.showLoading({
                            title: 'Logging in'.mask: true
                    })
                    this.getCode(code= > {
                        const data = {
                            code: this.wxCode,
                            iv: res.iv,
                            encryptedData: res.encryptedData
                        }
                        // Initiate a login request
                        wx.request({
                            url: '/api/login'.method: 'POST'.success: res= > {
                                console.log(res);
                                // Login succeeded

                                wx.hideLoading()
                            }
                        })
                    })
                },
                fail: err= > {
                    // Failed to obtain information
                    console.log(err)
                }
            })
        }
    }
}

Copy the code

Wechat mini program payment

Uni.requestpayment () = uni.requestPayment(); uni.requestPayment() = uni.requestPayment(); uni.requestPayment() = uni.requestPayment()

wx.login({
    success: res= > {
        wx.request({
            url: '/api/wxpay'.method: 'POST'.data: {
                code: res.code,
                order_id: 'order id'.// Example of background interface parameters
                pay_type: 'wxpay'.// Example of background interface parameters
            },
            success: res= > {
                // The returned data is a JSON string, which is converted into an object
                const result = JSON.parse(res.data.pay_data)
                wx.requestPayment({
                    provider: 'wxpay'.timeStamp: result.timeStamp,
                    nonceStr: result.nonceStr,
                    package: result.package,
                    signType: result.signType,
                    paySign: result.paySign,
                    success: res= > {
                        // The payment was successful
                        console.log('success:' + JSON.stringify(res))
                    },
                    fail: err= > {
                        // Payment failed
                        console.log('fail:' + JSON.stringify(err))
                    }
                })
            }
        })
    }
})
Copy the code

H5 Payment (wechat browser /JSPAI)

Access code

Get the code when you log in, the background gets the openId and stores it, and then the background doesn’t need to get it where it’s used (it doesn’t expire)

getCode(){
    let appid = 'xxxxxxxxxxxx'
    let url = 'https://xxx.xxxx.xxx'
    let redirect_uri = encodeURIComponent(url)// Call back the page address
    window.location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid + "&redirect_uri=" + redirect_uri + "&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect"
}
Copy the code

Encapsulate the H5 payment code

** * Pay * URL background order interface address * data order parameter * callback callback function */const payH5 = {
    onBridgeReady: function(url, data, callback) {
        wx.request({
            url,
            method: 'POST',
            data,
            success(res) {
                // The data returned by the background is a string
                const result_H5 = JSON.parse(res.data.pay_data)
                WeixinJSBridge.invoke(
                    'getBrandWCPayRequest', {
                        "appId": result_H5.appId, // The public id is passed in by the merchant
                        "timeStamp": result_H5.timeStamp, // Timestamp, the number of seconds since 1970
                        "nonceStr": result_H5.nonceStr, / / random string
                        "package": result_H5.package,
                        "signType": result_H5.signType, // wechat signature:
                        "paySign": result_H5.paySign // Wechat signature
                    },
                    function(res) {
                        if (res.err_msg == "get_brand_wcpay_request:ok") {
                            callback && callback('Payment successful')}else {
                            callback && callback('Payment failure')}}); },fail(err) {
                console.log('Network error:', err)
            }
        })
    },
    doPay(url, $params, callback) {
        if (typeof WeixinJSBridge == "undefined") {
            if (document.addEventListener) {
                document.addEventListener('WeixinJSBridgeReady'.this.onBridgeReady, false);
            } else if (document.attachEvent) {
                document.attachEvent('WeixinJSBridgeReady'.this.onBridgeReady);
                document.attachEvent('onWeixinJSBridgeReady'.this.onBridgeReady); }}else {
            this.onBridgeReady(url, $params, callback)
        }
    }
}

export default payH5
Copy the code

Pay for calls

Import this file to the desired page or mount it to the Vue prototype (described here in uni-app)

/ / introduction:
import H5Pay from './api/h5Pay.js' // H5Pay.doPay(url,params,callback)

export default {
    methods: {
        H5pay(){
            H5Pay.doPay(
            'url',
            {
                order_id: order_id,/ / order number
                pay_type: ' '.// Payment method
            }, 
            function(msg) {
                // Payment results
                console.log(msg)
            }
        )
    }
}
Copy the code

H5 Payment (non-wechat built-in browser)

Window.location. href = mwev_URL + redirect_URI (” redirect_URI “=” redirect_URI “) The URL requires encodeURIComponent encoding

dopayWeb() { // Non-wechat browser payment
    wx.request({
        url: '/api/h5pay'.method: 'POST'.data: {
            order_id: 'order id'.// Example of background interface parameters
            pay_type: 'wxpay'.// Example of background interface parameters
        },
        success(res) {
            console.log(res);
            const url = res.pay_url
            const redirect_uri = encodeURIComponent(url)
            window.location.href = url + "&redirect_uri=" + redirect_uri 
        },
        fail(err) {
            console.log('Network error')}})},Copy the code

Distinguish whether it is wechat built-in browser

function isMicroMessenger() {
    let userAgent = window.navigator.userAgent;    
    if(userAgent.indexOf('MicroMessenger') > -1) result = true;
    return false;
}
Copy the code

Js generates interface request parameter signature encryption

Define rules:

All request parameters (including public parameters) are sorted by key in ascending order, and then combined into the form key1=value1&key2=value2

Parames = {b:value-b, c:value-c,a:value-a} string = “a=value-a&b= value-B&c =value-c” Md5: sign = MD5 (string + secret) md5: sign = MD5 (string + secret) sceret = md5(string + secret) sceret = md5(string + secret

/** * defines the object sorting method */
objectSort(parames) 
{ 
    var newkeys = Object.keys(parames).sort();
    var newObj = {};
    for(var i = 0; i < newkeys.length; i++) 
    {
        newObj[newkeys[i]] = parames[newkeys[i]]; 
    }
    return newObj;
}
/** * Calculate signature method */
makeSign(params)
{
    var sign = ' ';
    var parm = ' ';

    params = objectSort(params);
    for (let i in params)
    {
        var j = params[i];
        parm += i + '=' + j + '&';
    }
    parm = parm.slice(0, -1);
    parm.trim();

    sign = Md5.md5(Md5.md5(parm)+$secret);//$secret is the key allocated by the back end
    return sign;
},
/** * Filter null characters */ in the data argument	
filterData(data){
    var result = {};
    for (let i in data) 
    {
        var value = data[i];
        if (typeof (value) == 'undefined') {
                value = ' ';
        }
        if(typeof(value) == 'string'){
                value = value.trim();
        }
        if(value) { result[i] = value; }}return result; 
},
/** * Build the data argument */
bulidData(data) {
    if(typeof(data) ! ='object'){
            data = {};
    }
    // Build parameters
    data.timestamp = (new Date()).valueOf();
    data.app_id = Config.app_info.app_id;
    / / filter
    data = this.filterData(data);
    // Check whether the user is logged in
    var token = Helper.user.getToken();
    if(token)
    {
            data.token = token;
    }
    data.sign = this.makeSign(data);
    return data;
},
Copy the code