Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

  • Uni. login request temporary code
  • Uni. request Exchange data to the background
  • Iii. Source code
  • Foreground: Add interface in GetUserInfo
  • Background: SpringBoot Background data processing
  • Four, achieve the effect

Development requirements: Our team is in the process of developing WeChat applet, need binding WeChat user information to the database, you will need to get the user’s unique identifier openid, and WeChat for security is banned small program to directly access the interface, so we can’t directly to the user’s openid, which need by calling WeChat authorized login interface implementation.

I am Sun Bujian 1208. This article was written in the summer vacation of 2021 when I participated in the Software Design Competition for College students in Shandong Province. It was mainly the first time I came into contact with small program development (UNIAPP + Springboot), and I have written down all the problems ENCOUNTERED. I hope my article can help you.

This article is based on uniApp + Springboot wechat mini program authorized login interaction. If you are not familiar with UniApp, you can go to this 20,000 words blog ([front-end tour] Uni-App study notes) to learn about it.

Official login flow chart (logical flow) :

Main steps:

  1. The front-end gets the code(wx.login) and passes it to the server.
  2. The server accesses the official interface using parameters AppID and AppSecret to obtain the OpenId.
  3. The server processes the OpenId and returns it to the front end.

Matters needing attention

  1. The session keysession_keyUser dataEncrypted signatureThe key. For the security of the application’s own data, the developer serverThe session key should not be issued to applets, nor should it be provided externally.
  2. Temporary login credential code can only be used once.

Uni. login request temporary code

In wechat applet, use wechat open interface :wx.login(Object Object), call interface to obtain login credentials (code)

In uniApp, we call the interface through uni.login(OBJECT) to get the login credentials (code).

OBJECT Parameter Description

Parameter names type mandatory instructions Platform Difference Description
provider String no Log in to the service provideruni.getProviderIf this parameter is not set, the login list selection interface will be displayed
scopes String/Array See platform differences description Authorization type, default auth_base. Support auth_base (silent authorization)/auth_user (active authorization)/auth_zhima (Sesame Credit) Alipay small program
timeout Number no Timeout duration, in ms Wechat small program, Baidu small program
univerifyStyle Object no A key to log inThe page style App 3.0.0 +
success Function no The interface called a successful callback
fail Function no Interface failed to invoke the callback function
complete Function no Callback function at the end of an interface call (executed on success and failure)

Success Returns parameter description

Parameter names instructions
authResult The login information provided by the service provider varies with the service provider
code Applets proprietary, user login credentials. Developers need to use code to exchange information such as openID and session_key in developer server background
errMsg Description information

The sample

uni.login({
  provider: 'weixin'.success: function (res) {
    console.log(res.Result); }});Copy the code

Uni. request Exchange data to the background

We pass uni.request(OBJECT) : To initiate a request to the background, the background sends the obtained certificate (code) through the foreground. The background needs to send the request to the wechat interface, and then wechat returns a STRING in JSON format to the background. After the background processing, Then exchange the user login status information, including the unique identifier of the user in the current small program (OpenID), the unique identifier under the wechat open platform account (unionID) and the session key (session_key) of this login, and then return to the foreground.

uni.request(OBJECT): Initiates a network request.

When each applets runs, network apis need to be whitelisted before being used.

OBJECT Parameter Description

Parameter names type mandatory The default value instructions Platform Difference Description
url String is Developer server interface address
data Object/String/ArrayBuffer no Requested parameters App (custom component compilation mode) does not support the ArrayBuffer type
header Object no Set the requested header. Referer cannot be set in the header. Cookies are automatically loaded on App and H5 terminals, and cannot be manually modified on H5 terminals
method String no GET Valid values are described below
timeout Number no 60000 Timeout duration, in ms H5(HBuilderX 2.9.9+), APP(HBuilderX 2.9.9+), wechat small program (2.10.0), Alipay small program
dataType String no json If set to JSON, a json.parse will be attempted on the returned data
responseType String no text Sets the data type of the response. Valid values: text, arrayBuffer Alipay small program is not supported
sslVerify Boolean no true Verifying an SSL Certificate Only supported on Android App (HBuilderX 2.3.3+)
withCredentials Boolean no false Whether credentials (cookies) are carried with cross-domain requests Only H5 supported (HBuilderX 2.6.15+)
firstIpv4 Boolean no false Ipv4 is preferred for DNS resolution App-android only (HBuilderX 2.8.0+)
success Function no Received a successful callback from the developer server
fail Function no Interface failed to invoke the callback function
complete Function no Callback function at the end of an interface call (executed on success and failure)

Method valid values

It must be capitalized. Valid values vary from platform to platform.

method App H5 Wechat applets Alipay small program Baidu applet Bytedance applet
GET Square root Square root Square root Square root Square root Square root
POST Square root Square root Square root Square root Square root Square root
PUT Square root Square root Square root x Square root Square root
DELETE Square root Square root Square root x Square root x
CONNECT x Square root Square root x x x
HEAD x Square root Square root x Square root x
OPTIONS Square root Square root Square root x Square root x
TRACE x Square root Square root x x x

Success Returns parameter description

parameter type instructions
data Object/String/ArrayBuffer Data returned by the developer server
statusCode Number The HTTP status code returned by the developer server
header Object The HTTP Response Header returned by the developer server
cookies Array.<string> Cookies returned by the developer server in the format of an array of strings

Data Data Description

The final data sent to the server is of type String. If the data passed in is not of type String, it is converted to String. The conversion rules are as follows:

  • forGETMethod that converts the data to a Query String. For example,{ name: 'name', age: 18 }The result of the transformation isname=name&age=18.
  • forPOSTMethods andheader['content-type']application/jsonThe data will be JSON serialized.
  • forPOSTMethods andheader['content-type']application/x-www-form-urlencodedIs converted to a Query String.

The sample

uni.request({
    url: 'https://www.example.com/request'.// This is an example, not a real interface address.
    data: {
        text: 'uni.request'
    },
    header: {
        'custom-header': 'hello' // Customize the request header
    },
    success: (res) = > {
        console.log(res.data);
        this.text = 'request success'; }});Copy the code

The return value

If you want to return a requestTask, you need to pass in at least one of the Success/fail/complete parameters. Such as:

var requestTask = uni.request({
    url: 'https://www.example.com/request'.// This is an example, not a real interface address.
    complete: () = >{}}); requestTask.abort();Copy the code

If the Success/fail/complete parameters are not passed, the wrapped Promise object is returned: the Promise wrapper

With requestTask, you can interrupt a requestTask.

List of methods for the requestTask object

methods parameter instructions
abort Interrupt request task
offHeadersReceived Cancel listening for HTTP Response Header eventsWechat small program platformSupport,The document details
onHeadersReceived Listen for HTTP Response Header events. Will be earlier than the request completion event, only wechat small program platform support,The document details

The sample

const requestTask = uni.request({
    url: 'https://www.example.com/request'.// This is an example, not a real interface address.
    data: {
        name: 'name'.age: 18
    },
    success: function(res) {
        console.log(res.data); }});// Interrupt the request task
requestTask.abort();
Copy the code

Tips

  • The request ofheadercontent-typeThe default isapplication/json.
  • To avoid theheaderUse Chinese, or use encodeURIComponent for encoding, otherwise in Baidu small program error.
  • Network-requestedtimeoutCan be unified inmanifest.jsonIn the configurationnetworkTimeout.
  • Note Cross-domain problems during local debugging on the H5 terminal. For details, see Debugging Cross-domain Problem Solution
  • H5 cookies are cross-domain restricted (like when developing websites). The old version of UNI. request does not support withCredentials configuration, so you can use XHR objects or other libraries directly.
  • Uni-app plug-ins are available in the market in tripartite packages such as Flyio and Axios
  • Server addresses, such as localhost and 127.0.0.1, can only be accessed on a PC but cannot be accessed on a mobile phone. Please use a standard IP address and ensure that the phone can connect to the computer network
  • It is recommended that the amount of data in a single network request be less than 50 KB (only JSON data, not images). Obtain excessive data in pages to improve application experience.

Ps: Know the ids of the various platforms, they all have the same functionality.

  • OpenID: OpenID is used by default in wechat applications (public accounts, small programs, etc.). Generally, OpenID is returned by the interface requested during development. In the small program or wechat web page without authorization, silent can also get OpenID. It can be said that OpenID is the most important ID in wechat ecosystem. It can be understood that OpenID is encrypted by AppID and wechat user ID, which is related to wechat application (each application will have AppID), and each wechat application will generate a unique user identification.
  • AppID and AppSecret: Both the official account and the mini program have an AppID to identify the current wechat application, and if it needs to be developed, the interface requests all need to use AppSecret.
  • Wechat user ID: wechat user ID is encrypted and cannot be obtained. Generally, we use wechat robot development, commonly used is wechat or wechat nickname as ID.
  • UnionID: inside the wechat open platform, after making the account binding, a unified UnionID will be generated. After binding, the wechat application (small program, public number, etc.) can use an ID. Obtaining the UnionID requires user authorization.
  • UUID: it is mainly for front-end devices, such as applets or web pages. It takes some development to obtain OpenID, so if the OpenID cannot be obtained, we will generally generate a random ID for the current browser or applets.
  • UserID: indicates the real ID of a user, usually the ID of an existing database.