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.

Iii. Source code

1. Call wechat API wx.login() to get the code.

2. Pass the obtained code to the back end, which obtains the code and requests the official interface of wechat small program and returns it to the front end OpenID.

3. After knowing the OpenID, perform operations related to the user to determine the login status of the user.

Foreground: Add interface in GetUserInfo

GetUserInfo() {
				var _this = this;
				// Add constraint, no protocol can be authorized
				if (this.value === false) {
					uni.showToast({
						title: 'Please read check agreement'.icon: 'error'.duration: 2000
					});
				} else {
					uni.getUserProfile({
						desc: 'login'.lang: 'zh_CN'.success: (res) = > {
							console.log('Information acquired', res.userInfo);
							_this.nickName = res.userInfo.nickName;
							_this.setNn(res.userInfo.nickName);
							uni.getLocation({
								type: 'gci02'.success: res= > {
									uni.reLaunch({
										url: 'Login2'}); }}); },fail: (res) = > {
							console.log('User refused authorization');
							uni.showToast({
								title: 'Authorization failed'.icon: 'error'.duration: 2000}); }}); }}login() {
					let _this = this;
					uni.showLoading({
						title: 'Logging in... '
					});
					// Get the login user code
					uni.login({
						provider: 'weixin'.success: function(res) {
							if (res.code) {
								let code = res.code;
								console.log('the user code:, res.code);
								uni.request({
									url: "https://xxxxxxx:8084/wxLogin/getOpenid".method: 'POST'.header: {
										'Content-Type': 'application/x-www-form-urlencoded'
									},
									data: {
										code: res.code, //wx.login Indicates the code after successful login
										role: _this.role,
									},
									success: function(cts) {
										var openid = cts.data.openid; Openid Indicates the unique id of the openID user
										var userInfo = {
											openid: openid,
											role: _this.role
										};
										console.log(_this.role);
										_this.saveUserInfo(userInfo);
										uni.hideLoading();
										uni.switchTab({
                                            // Jump after successful login
											url: '.. /myCenter/myCenter'}); }}); }else {
								uni.showToast({
									title: 'Login failed! '.duration: 2000
								});
								console.log('Login failed! '+ res.errMsg) } }, }); }}Copy the code

Background: SpringBoot Background data processing

  1. The appID and Secret of the small program obtained first are encapsulated as an interface

  2. Interface, splicing SQL, send HTTP request to wechat

  3. Encapsulate the returned result into a map set and return it to the front end

    @PostMapping("/getOpenid")
    @ResponseBody
    public Map<String, Object> getOpenId(@RequestParam("code") String code,
                                         @RequestParam(value = "role") Integer role) throws IOException {
        / / return code
        System.out.println("========== Enter the wxLogin/getOpenid method ==========");
        System.err.println("Wechat Authorized Login");
        System.err.println("Code values." + code);
        Map<String, Object> resultMap = new HashMap<>();
        String appid = ConstUtil.getAppId();
        String secret = ConstUtil.getSECRET();

        / / stitching SQL
        String loginUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid +
                "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code";

        CloseableHttpClient client = null;
        CloseableHttpResponse response = null;

        // Create an httpGet request
        HttpGet httpGet = new HttpGet(loginUrl);
        // Send the request
        client = HttpClients.createDefault();
        // Execute the request
        response = client.execute(httpGet);
        // Get the returned data
        HttpEntity entity = response.getEntity();

        String result = EntityUtils.toString(entity);
        System.out.println("Results returned by wechat" + result);

        resultMap.put("data", result);

        // Parse the returned result
        JSONObject json_test = JSONObject.parseObject(result);
        String openid = json_test.getString("openid");
        String sessionKey = json_test.getString("session_key");
        System.err.println("The openid value." + openid);
        System.err.println("SessionKey value" + sessionKey);

        Users users = usersService.getUserByOpenid(openid);

        System.err.println("User Information:" + users);

        if (StringUtils.isEmpty(openid)) {
            resultMap.put("state", ResponseCode.SUCCESS.getCode());
            resultMap.put("message"."Openid not obtained");
            return resultMap;
        } else {
            // Check whether this is the first login
            if (users == null) {
                resultMap.put("state", ResponseCode.SUCCESS.getCode());
                resultMap.put("openid", openid);
                resultMap.put("sessionKey", sessionKey);
                resultMap.put("message"."No user information found");
            } else {
                // Query whether there is any result
                UserRole uRes = userRoleService.getUserRole(openid, role);
                // Encapsulate the object
                UserRole userRole = new UserRole(openid, role);
                // If it is not the first login, log in the second time to judge, if it does not have the identity, add, if it has the identity, do not process
                if (uRes == null) {
                    userRoleService.insert(userRole);
                }
                resultMap.put("state", ResponseCode.SUCCESS.getCode());
                // Get the map key
                resultMap.put("openid", openid);
                resultMap.put("sessionKey", sessionKey);
                resultMap.put("user", users);
                resultMap.put("message"."The user already exists");
            }
            response.close();
            client.close();
        }
        return resultMap;
    }
Copy the code

Four, achieve the effect