The most important thing is to use the wechat account to authorize one-click login, without complicated registration steps, and then quickly experience the functions of the application. Let’s take a look at the documents provided by wechat first.

Wechat login ability introduction

In order to facilitate users to use App, website, mobile web page, small program services, wechat provides different technical solutions, convenient for developers to access wechat login in different terminal platform services. Through this tutorial, developers can understand the wechat login capability provided by the platform for various terminal platforms, and can choose a reasonable access mode according to the actual use scenario.

The following are the functions of several types of wechat login:

type Authorization domain/interface User side usage process Access to the process
App Access the wechat SDK and call snsapi_userinfo (1) Select wechat login within the App. (2) Pull up the wechat client and open the user authorization page to complete the login authorization (1) Register an account on wechat open platform (open.weixin.qq.com) and complete the developer qualification certification. (2) Apply for [App mobile Application] and you can use it after approvalDevelopment of the document
Web application snsapi_login (1) The user uses wechat to scan codes on the PC. (2) The client opens the authorization page to complete login authorization (1) Register an account on wechat open platform (open.weixin.qq.com) and complete the developer qualification certification. (2) Apply for [website application] and you can use it and view it after approvalDevelopment of the document
H5 in wechat client Login ability using public account: snsapi_base snsapi_userinfo Snsapi_userinfo: (1) A user clicks login in H5, and the authorization window is aroused. (2) The user completes login authorization (1) Register the wechat public account, select the “service Number” type, and complete the wechat authentication. (2) Set the callback domain name in the management background of the public account. (3) Access the wechat login ability and viewDevelopment of the document
Small program wx.login wx.getUserInfo Wx. login: silent authorization, developers can obtain OpenID wx.getUserInfo: (1) the user clicks the component in the small program, arouses the login window. (2) The user completes the login authorization (1) Registration small program (2) Access wechat login function, viewDevelopment of the documentTo see theGuide to designing the login process

My service has App, official website, public account and small program at the same time. How can I get through user data?

For multi-platform services, if the developer wants to identify the user’s identity, for example, if the user wants to view the order of goods purchased in the App in the small program, the user’s identity can be recognized through the UnionID mechanism provided by the platform.

In addition, it should be noted that the H5 mobile phone station in non-wechat environment (directly opened by the browser) also needs to use the website application of open platform.

The login

Login of applets

Small programs can easily obtain the user identification provided by wechat through the login ability provided by wechat official, and quickly establish the user system within small programs.

Logon process timing

Note: Image source [small program development document]

This figure means that the code should be obtained through wx.login on the small program side, and then the code should be sent to the developer server through HTTP request, and then the developer server should send relevant parameters to the wechat interface server through HTTP request to obtain the OpenID. After the developer server obtains the OpenID, it can perform relevant operations, such as registering members in the library, and then returning the relevant data status to the small program end. Generally, it generates a token and returns it to the small program end. The small program end gets the token and caches it. Carry a token in the HTTP header when requesting an interface.

Added the getUserProfile interface

It should be noted that Tencent’s rules are changing all the time with the addition of getUserProfile. If a developer needs to obtain user profile information (avatar, nickname, gender, and region), it can be obtained through the wx.getUserProfile interface. For details, please refer to the official documents: mini program login, user information related interface adjustment instructions

Public Account login

If a user accesses a third-party web page in the wechat client, the public account can obtain the user’s basic information through the wechat web page authorization mechanism, so as to realize the business logic. Wechat public number web page development document is more detailed, so this article will not be too much to say, details can see the public number development document wechat web page development: web page authorization

Note: the login should be silent. The front-end only transmits code, and the back-end generates openId through code, and then queries whether the user is registered. If the user is registered, the login process will be followed, and if the user is not registered, nothing will be returned.

Openid

The user’s identity in the public account. Different public accounts have different Openids. Merchant background system can obtain user openID through login authorization, payment notification, order query and other APIS. It is used to identify the same user and send customer service messages and template messages to the user. Enterprise users need to use the userID to OpenID interface to convert the userIDS of enterprise members into Openids.

Web page authorization to obtain the user OpenID

Applets get openID

Public account to obtain openID

APP for openid

pay

Before we understand wechat pay, we should first understand a few wechat payment related terms

  1. Wechat public platform

Wechat public platform is the entrance and management background of wechat public account application. Merchants can submit basic information, business information and financial information on the public platform to apply for opening the wechat payment function.

  1. Wechat open platform

The wechat open platform is an application entrance for merchants to access the wechat Pay open interface, through which they can apply for wechat APP payment.

  1. Wechat merchant platform

Wechat Merchant platform is a collection of merchant functions related to wechat Payment, including parameter configuration, payment data query and statistics, online refund, voucher or discount operation and other functions.

The wechat payment involved in our Web front end is generally wechat small program or wechat public number, so we should first apply for opening the wechat payment function in the management background of wechat small program or wechat public number. Before opening wechat pay, you should first register a wechat merchant on the wechat merchant platform, and then bind the relevant wechat small program and wechat public number in the wechat merchant platform, and then return to the wechat small program or wechat public number management background for confirmation of binding, this process is called the so-called opening wechat payment function.

Business flow chart

Key steps:

Step 3 Users place orders and initiate payment. Merchants can place orders and create payment orders through JSAPI.

Step 8 Merchants can activate wechat Payment through JSAPI in wechat browser to initiate payment request.

Step 15 After the user makes a successful payment, the merchant can receive the payment result notification API of wechat Pay.

Step 20 In the case that the merchant does not receive notification of wechat payment result, the merchant needs to actively call the query order API to query the payment result.

Applets payment

Small program payment refers to a scenario where users complete transactions within the existing small program of merchants by docking with the wechat Payment API.

Sample request

wx.requestPayment
(
	{
		"timeStamp": "1414561699"."nonceStr": "5K8264ILTKCH16CQ2502SI8ZNMTM67VS"."package": "prepay_id=wx201410272009395522657a690389285100"."signType": "RSA"."paySign": "oR9d8PuhnIc+YZ8cBHFCwfgpaK9gd7vaRvkYD7rthRAZ\/X+QBhcCYL21N7cHCTUxbQ+EAt6Uy+lwSN22f5YZvI45MLko8Pfso0jm46v5hqcVwrk6uddkGu T+Cdvu4WBqDzaDjnNa5UK3GfE1Wfl2gHxIIY5lLdUgWFts17D4WuolLLkiFZV+JSHMvH7eaLdT9N5GBovBwu5yYKUR7skR8Fu+LozcSqQixnlEZUfyE55feL OQTUYzLmR9pNtPbPsu6WVhbNHMS3Ss2+AehHvz+n64GDmXxbX++IOBvm2olHu3PsOUGRwhudhVf7UcGcunXt8cqNjKNqZLhLw4jq\/xDg=="."success":function(res){},
		"fail":function(res){},
		"complete":function(res){}})Copy the code

Request the sample uniapp

// #ifdef MP
uni.requestPayment({
    "timeStamp": res.data.timeStamp,
    "nonceStr": res.data.nonceStr,
    "package": res.data.packageValue,
    "signType": res.data.signType,
    "paySign": res.data.paySign,
    "success": function(res) {
        callbackQueryOrder(orderId).then(res= > {
            if (res.status === 'OK') {
                _this.$store.dispatch('saveCurrPayOrder', {... currPayOrder,status: 'success'})
                _this.$util.Tips({
                    title: 'Payment successful'.icon: 'success'
                }, {
                    tab: 4.url: toPages
                })
            }
        }).catch(err= > console.log(err))
    },
    "fail": function(res) {
        _this.$store.dispatch('saveCurrPayOrder', {... currPayOrder,status: 'fail'})
        _this.$util.Tips({
            title: 'Cancel payment'
        }, {
            tab: 4.url: toPages
        });
    },
    "complete": function(res) {
        uni.hideLoading();
        // Close the current page and jump to the order state
        if (res.errMsg == 'requestPayment:cancel') return that.$util.Tips({
            title: 'Cancel payment'
        }, {
            tab: 4.url: goPages }); }})// #endif
Copy the code

Payment by public account (PAYMENT by JSAPI website)

JSAPI webpage payment, namely the daily public account payment, can click the page link in the wechat public account, moments of friends, chat session, or use wechat “Scan scan” to scan the page address TWO-DIMENSIONAL code to open the HTML5 page of the merchant in wechat, and place an order to complete the payment on the page.

The necessary parameter prepay_id to initiate payment was obtained through JSAPI ordering interface, and then the front-end JS method provided by wechat Pay was used to initiate payment by public account.

Note:

  1. Ensure that the request directory for actual payment is the same as the directory configured in the background (the root directory can be configured now, and the configuration takes effect within 5 minutes); otherwise, wechat payment cannot be invoked successfully. For details, see the Payment Authorization directory.
  2. The WeixinJSBridge built-in object is not valid in other browsers.
  3. JSSDK’s WX. ChooseWXPay evokes payment, evokes format content to refer to the public number development guide.
  4. JSSDK JSSDK Usage instructions Link address, content description information.
  5. The res object returned by evocation payment is hump format returned by JSSDK, while err_msg is format returned by WeixinJSBridge. If merchants use different methods, the character case and format of the response should be paid attention to.

Initiate a wechat payment request

wx.chooseWXPay({
  timestamp: 0.// 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: ' '.// The payment signature is a random string, no longer than 32 bits
  package: ' '.// The prepay_id parameter returned by the unified payment interface is submitted in the format prepay_id=\*\* *)
  signType: ' '.// Wechat Pay V3 is passed into RSA, and the format of wechat Pay V2 is the same as the signature format of V2 unified order
  paySign: ' '.// Pay the signature
  success: function (res) {
    // Callback function after successful payment}});Copy the code

To view detailed WeChat pay V3 development documentation: pay.weixin.qq.com/wiki/doc/ap…

address

Applets get addresses

wx.chooseAddress(Object object)

Public number to obtain the address

Shared shipping address interface

Example uniapp code

// Get the wechat address
getWxAddress() {
    let that = this;
    // #ifdef MP-WEIXIN
    uni.authorize({
        scope: 'scope.address'.success: function(res) {
            uni.chooseAddress({
                success: function(res) {
                    console.log(res);
                    const item = {
                        province: res.provinceName,
                        city: res.cityName,
                        region: res.countyName,
                        detailAddress: res.detailInfo,
                        default: false.name: res.userName,
                        phoneNumber: res.telNumber,
                        id: ' ',
                    }
                    that.editAddress(item)
                },
                fail: function(res) {
                    if (res.errMsg == 'chooseAddress:cancel') return that.$util
                        .Tips({
                        title: 'Deselect'}); }})},fail: function(res) {
            uni.showModal({
                title: 'You have refused to import wechat address permission'.content: 'Enter permission management and adjust authorization? '.success(res) {
                    if (res.confirm) {
                        uni.openSetting({
                            success: function(res) {}}); }else if (res.cancel) {
                        return that.$util.Tips({
                            title: 'Cancelled! '}); }}})},}// #endif
    // #ifdef H5
    // return
    this.$wechat.openAddress().then(res= >{
        const item = {
            province: res.provinceName,
            city: res.cityName,
            region: res.countyName,
            detailAddress: res.detailInfo,
            default: false.name: res.userName,
            phoneNumber: res.telNumber,
            id: ' ',
        }
        that.editAddress(item)

    }).catch(err= >{
        console.log('failure',err);
    })
    // #endif
}
Copy the code

positioning

Applets get location

You can see the details of the article I wrote before: a summary of the work of the wechat small program based on positioning to achieve the punch card function

Public account to obtain location

Uni-app has a ready-made interface to get latitude and longitude directly

// Get latitude and longitude
export function getLocation() {
    return new Promise((resolve, reject) = > {
        uni.getLocation({
            type: 'gcj02'.success: function(res) {
                uni.setStorageSync('user_latitude', res.latitude)
                uni.setStorageSync('user_longitude', res.longitude)
                resolve(res)
            },
            fail: function(err) {
                uni.showToast({
                    title: 'Access location denied'
                })
                reject(err)
            }
        })
    })
}
Copy the code

Public location is converted to an address

Json file in the root directory, then select the last source view, find the last H5 configuration, and use Tencent interface for cross-domain proxy (use HBuilder X internal browser will not appear cross-domain problems).

Development environment to solve cross-domain problems (via proxy)

"h5" : {
        "devServer" : {
            "https" : false."port" : 80."disableHostCheck" : true."proxy" : { // Can delegate multiple
                "/TencentGet" : {
                    "target" : "https://apis.map.qq.com/ws/geocoder/v1/".// Tencent map reverse address resolution
                    "changeOrigin" : true."secure" : false."pathRewrite" : {
                        "^/TencentGet" : ""}}}},}Copy the code

Production environment to solve cross-domain problems (nginx configuration proxy_pass)

location /TencentGet {
     proxy_pass   https://apis.map.qq.com/ws/geocoder/v1/;
}
Copy the code

Take a public method to obtain city information by latitude and longitude ި

// Get address information by latitude and longitude
export function getLocationCity(latitude, longitude) {
    // #ifdef H5
    // There are cross-domains that need to be represented in the manifest
    let baseUrl = `/TencentGet/? coord_type=5&get_poi=0&output=json&location=${latitude}.${longitude}&key=${key}`


    return new Promise((resolve, reject) = > {
        uni.request({
            url: baseUrl,
            method: 'GET'
        }).then(res= > {
            uni.setStorageSync('city_address', res[1].data.result)
            uni.setStorageSync('city', res[1].data.result.address_component.city)
            resolve(res[1].data.result)
        }).catch(err= >{})})// #endif
    // With the exception of H5
    // #ifndef H5
    return new Promise((resolve, reject) = > {
        var that = this
        var map = new TencentMap({
            key: key
        })
        map.reverseGeocoder({
            location: {
                latitude: latitude,
                longitude: longitude
            },
            success: function(res) {
                // console.log(' Tencent obtains city name ', res)
                uni.setStorageSync('city_address', res.result)
                uni.setStorageSync('city', res.result.address_component.city)
                resolve(res.result)
            },
            fail: function(err) {
                reject(err)
            }


        })
    })
    // #endif
}
Copy the code

The phone number

Applets get phone numbers

Details can be viewed: obtain the phone number

Public number to obtain the phone number

The public account can’t get a phone number

Qr code

The small program code can be generated through the API provided by wechat official

wxacode.createQRCode graphs

wxacode.getUnlimited

Applets can also be opened by scanning the normal linked QR code in the development Settings in Development Management

Small program page switch on the camera to scan the TWO-DIMENSIONAL code

// #ifdef MP
wx.scanCode({
    onlyFromCamera: true.// Only scan from the camera is allowed
    scanType: ['qrCode'].// Only qr code scanning is allowed
    success(res) {
        console.log('res', res)
        _this.handlerScanQRCodeResult(res.result)
    }
})
// #endif
Copy the code

Turn on the camera on the H5 page of the official account to scan the QR code

// #ifdef H5
_this.$wechat.scanQRCode({
    needResult: 1.// The default value is 0, the scan result is processed by wechat, 1 directly returns the scan result,
    scanType: ["qrCode"."barCode"] // You can specify whether to scan a two-dimensional code or a one-dimensional code
}).then(res= > {
    console.log('res', res)
    const result = res.resultStr; // If needResult is 1, scan the result
    _this.handlerScanQRCodeResult(result)
}).catch(err= > console.log('Scan error', err));
// #endif
Copy the code

Scan common link qr code to open small program

In order to facilitate the small program developers to promote the small program more easily, compatible with the existing offline TWO-DIMENSIONAL code, wechat public platform open scanning ordinary link two-dimensional code jump small program ability.

Qr Code Jump rule

Note: Starting from May 2017, wechat client supports QR code rules based on “sub-path matching”. Such as original qr code links to http://www.qq.com/a/123456, of which 12345 were business parameters are configurable rules http://www.qq.com/a/ implementation code open small programs.

The wechat client scan code will control the jump according to the following matching rules:

  1. The protocol and domain name of the QR code link are consistent with the configured QR code rules.
  2. The two-dimensional code link belongs to the sub-path of the two-dimensional code rule configured in the background. (If you need to support sub-path matching, please confirm the QR code rules configured in the background/At the end)
  3. If qr code rules contain parameters, link?The parameter part is followed by the parameter part, which must match the prefix.

Common types of matching errors:

Qr code rules have been configured on the background Offline QR code complete link The reason for the error
www.qq.com/a/b www.qq.com/a/b Inconsistent agreement
www.qq.com/a/b www.weixin.qq.com/a/b Domain name is different
www.qq.com/a/b?id=123 www.qq.com/a/b?id=132 The parameter does not match the prefix
www.qq.com/a/b www.qq.com/a/bc Does not belong to a subpath
www.qq.com/a/b www.qq.com/a/b/123 The rules are not/At the end, child path matching is not supported
www.qq.com/a/ (published) www.qq.com/a/b (unpublished) www.qq.com/a/b Hitting an unpublished rule does not jump the applets
Qr code content acquisition

After configuring the qr code jump rule in the background of the mini-program, you can use wechat (client version 6.5.6 and above) to scan the code to open the mini-program.

Two-dimensional code link content will be brought to the page in the form of parameter Q, in the onLoad event extraction of Q parameters and their own decodeURIComponent once (for small games can use wx.getEnterOptionsSync interface to obtain), you can obtain the complete content of the original two-dimensional code. A parameter, scancode_time (UNIX timestamp, in seconds), is appended to indicate the time for the user to scan codes.

Page({
  onLoad(query) {
    const q = decodeURIComponent(query.q) // Get the original link content of the QR code
    const scancode_time = parseInt(query.scancode_time) // Get the user scan time UNIX timestamp}})Copy the code
Directly use wechat scan to deal with the results of small program scanning
/** * Get url parameter support Chinese *@param String param Carries the parameter * */
getUrlParams: function(params) {
    let url = params.substring(params.indexOf("?")); // Get the "?" in the url The string following the character
    let theRequest = new Object(a);if (url.indexOf("?") != -1) {
        let str = url.substr(1);
        let strs = str.split("&");
        for (let i = 0; i < strs.length; i++) {
            theRequest[strs[i].split("=") [0]] = unescape(strs[i].split("=") [1]); }}return theRequest;
}
Copy the code
Process the scan result
/** * process the scan result */
handlerScanQRCodeResult(result) {
    if (result.includes(appConfig.PUBLISHURL) || result.includes(appConfig.PUBLISHURL_MINI)) {
        const params = this.$util.getUrlParams(result)
        if (params.pickCode) {
            this.$util.Tips('/pages/users/order/verificationGoodsList? pickCode=' + params.pickCode)
        } else {
            this.$util.Tips({
                title: "Not a verification code."}}})else {
        console.log('Not a verification code')
        this.$util.Tips({
            title: "Not a verification code."})}},Copy the code
Matters needing attention

Note that the configuration of the applets cannot be tested until they are published, and the parameters of the tests must be written into the configuration

The generated QR codes can be tested using development tools

To view detailed developers.weixin.qq.com/miniprogram…