Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize WeChat Mini Programs login by Springboot

2025-01-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces Springboot how to achieve WeChat Mini Programs login, the article is very detailed, has a certain reference value, interested friends must read it!

Front end

.wxml

I agree

JS part

BindGetUserInfo (e) {let that = this let token = wx.getStorageSync ('token'); / / token is actually the openid returned by calling the Wechat login API at the backend. Each user is unique within the same Mini Program. Wx.showLoading ({title: 'loading', / / prompt box, loading style}) if (token) {/ / if there is already a token, the user is logged in, jump to the specified page wx.switchTab ({url:'})} else {/ / the user is not logged in yet Apply for user authorization wx.getUserProfile ({desc:'to improve the membership profile', / / declare the use after obtaining the user's personal information, which will be displayed in the pop-up window Please fill in success: (res) = > {that.setData ({userInfo: res.userInfo) carefully / / Save user information}) if (res.errMsg = = "getUserProfile:ok") {let code = null wx.login ({success: function (e) {code = e.code let params = {}) Params.code = code; / / user code Note: each login of a user's code is random, so there is no need to store params.avatarUrl = res.userInfo.avatarUrl; / / user avatar params.nickName = res.userInfo.nickName; / / user Wechat name params.gender = res.userInfo.gender / / user gender 0 is unknown, 1 is male, 2 is female / / and the address information set by user Wechat is useless. Therefore, wx.request ({url:'', / / background interface data: params, method: 'POST', header: {' Content-Type': 'application/json') is not processed. 'Xmure NideshopkoTokencodes: wx.getStorageSync ('token')} Success: function (res) {/ / URL is your background interface console.log (res) if (res.data.code = 200) {/ / store user information wx.setStorageSync ('userInfo', res.data.userInfo) Wx.setStorageSync ('token', res.data.userInfo.openId) Wx.switchTab ({url:'/ / Jump to the specified page}) wx.hideLoading () / / close prompt box} else {/ / output error message })} else {/ / the user pressed the reject button wx.showModal ({title: 'warning Notification' Content:'if you click deny authorization, you will not be able to display your personal information properly. Click OK to re-obtain the authorization.' , success: function (res) {/ / processing after the user refuses to log in}});})}}

The foreground part is here, and the detailed explanation is written in the comments. If login is used in many places, or whether the user is logged in or not, it is recommended to encapsulate it to facilitate the call.

Backstage

In the background part, I use the springboot framework. In order to facilitate beginners to learn, I will paste the whole module at the back, including the jar package.

First of all, let's take a look at the project directory structure.

POM.XML

The content of the jar package is not complicated. I'm sure there's nothing wrong with you.

Com.alibaba fastjson 1.2.47 mysql mysql-connector-java 8.0.23 org.springframework.boot spring-boot-starter-web 2.4.4 com.alibaba druid 1.1.10 org.mybatis.spring.boot mybatis-spring-boot-starter 2.1.4 log4j log4j 1.2.17 org.projectlombok lombok 1.16.18

Configuration class application.yml

The content of the configuration class is not complicated, so I won't explain it here.

Mybatis: type-aliases-package: com.cxb.pojo config-location: classpath:mybatis/mybatis-config.xml mapper-locations: classpath:mybatis/mapper/*.xmlspring: application: name: item # Database part datasource: type: com.alibaba.druid.pool.DruidDataSource driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql:///item?useUnicode=treu&charactEncoding=utf-8 username: root password: 123456wxMini: appId: # Mini Program's appid Where can I get the key if you don't know? Baidu secret: # Mini Program key

Mybatis-config.xml

Tool class WeChatUtil

This tool class is a relatively simple tool class I found on the Internet. Because the parameters returned by the Wechat login interface are encrypted, it needs to be decrypted.

Package com.cxb.utils;import com.alibaba.fastjson.JSONObject;import lombok.extern.slf4j.Slf4j;import javax.net.ssl.HttpsURLConnection;import java.io.*;import java.net.URL;import java.net.URLConnection;import java.nio.charset.StandardCharsets;/** * WeChat Mini Programs tool class * / @ Slf4jpublic class WeChatUtil {public static String httpRequest (String requestUrl, String requestMethod, String output) {try {URL url = new URL (requestUrl) HttpsURLConnection connection = (HttpsURLConnection) url.openConnection (); connection.setDoOutput (true); connection.setDoInput (true); connection.setUseCaches (false); connection.setRequestMethod (requestMethod); if (null! = output) {OutputStream outputStream = connection.getOutputStream (); outputStream.write (output.getBytes (StandardCharsets.UTF_8)) OutputStream.close ();} / / read the returned content from the input stream InputStream inputStream = connection.getInputStream (); InputStreamReader inputStreamReader = new InputStreamReader (inputStream, StandardCharsets.UTF_8); BufferedReader bufferedReader = new BufferedReader (inputStreamReader); String str; StringBuilder buffer = new StringBuilder () While ((str = bufferedReader.readLine ())! = null) {buffer.append (str);} bufferedReader.close (); inputStreamReader.close (); inputStream.close (); connection.disconnect (); return buffer.toString ();} catch (Exception e) {e.printStackTrace () } return ";";} / * send the request for POST method to the specified URL * * @ param url send the request URL * @ param json request parameter, which should be in the form of json. * response result of the remote resource represented by @ return * / public static String httpPost (String url, JSONObject json) {PrintWriter out = null; BufferedReader in = null; String result = ""; try {URL realUrl = new URL (url); / / Open connection to URL URLConnection conn = realUrl.openConnection () / / set general request properties conn.setRequestProperty ("accept", "* / *"); conn.setRequestProperty ("connection", "Keep-Alive"); conn.setRequestProperty ("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1 Sv1)") / / to send a POST request, you must set the following two lines: conn.setDoOutput (true); conn.setDoInput (true); / / get the output stream corresponding to the URLConnection object out = new PrintWriter (conn.getOutputStream ()); / / send the request parameter out.print (json) / / buffer out.flush () of the flush output stream; / / define the BufferedReader input stream to read the URL response in = new BufferedReader (new InputStreamReader (conn.getInputStream (); String line; while ((line = in.readLine ())! = null) {result=result.concat (line) }} catch (Exception e) {System.out.println ("an exception occurred sending a POST request!" + e); e.printStackTrace ();} / / use the finally block to close the output stream and input stream finally {try {if (out! = null) {out.close ();} if (in! = null) {in.close () } catch (IOException ex) {ex.printStackTrace ();}} return result;}}

Next is the project theme code, because only to do a simple demo, so the content is not complex, but whether it is learning or ordinary small projects are no problem, you can rest assured to use

Dao layer UserDao

Package com.cxb.dao;import com.cxb.pojo.User;import org.apache.ibatis.annotations.Mapper;import org.springframework.stereotype.Repository;@Mapper@Repositorypublic interface UserDao {User queryById (String openId); void insertUser (User user); void updateUser (User user);}

Service layer UserService

Package com.cxb.service;import com.cxb.dao.UserDao;import com.cxb.pojo.User;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;@Servicepublic class UserService implements UserDao {@ Autowired private UserDao userDao; @ Override public User queryById (String openId) {return userDao.queryById (openId);} @ Override public void insertUser (User user) {userDao.insertUser (user) @ Override public void updateUser (User user) {userDao.updateUser (user);}}

Entity class User

Package com.cxb.pojo;import lombok.AllArgsConstructor;import lombok.Data;import lombok.NoArgsConstructor;import lombok.experimental.Accessors;import java.io.Serializable;import java.util.Date;@Data@NoArgsConstructor@Accessors (chain = true) public class User implements Serializable {private Long id; / / id private String code; / / is just to receive parameters and does not need to be stored in the database private String openId; / / one of the parameters returned by the Wechat login interface, that is, token private String nickName / / Wechat name private String avatarUrl; / / avatar private String gender; / / gender 0 unknown 1 male and 2 female private Date firstLoginTime; / / first login time private Date lastLoginTime; / / last login time}

SQL partial UserMapper.xml

Select * from user where open_id = # {openId} insert into user (open_id, nick_name, avatar_url, gender, first_login_time Last_login_time) values (# {openId}, # {nickName}, # {avatarUrl}, # {gender}, # {firstLoginTime} # {lastLoginTime}) update user `nick_ name` = # {nickName}, `avatar_ url` = # {avatarUrl}, `gender` = # {gender}, `last_login_ time` = # {lastLoginTime} where id = # {id}

Controller UserController

Package com.cxb.controller;import com.alibaba.fastjson.JSONObject;import com.cxb.pojo.User;import com.cxb.service.UserService;import com.cxb.utils.WeChatUtil;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.*;import java.util.Date Controller@RequestMapping (value = "/ user") public class UserController {@ Value ("${wxMini.appId}") public String appId; @ Value ("${wxMini.secret}") public String secret; @ Autowired private UserService userService; @ RequestMapping (value = "/ login", method = RequestMethod.POST) @ ResponseBody public JSONObject login (@ RequestBody User user) {String code = user.getCode (); JSONObject object=new JSONObject () If (code = "" | ".equals (code)) {object.put (" code ", 300); object.put (" msg "," code cannot be empty! "); return object } else {/ / Wechat API service, obtain openid and session_key String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appId +" & secret= "+ secret +" & js_code= "+ code +" & grant_type=authorization_code "by calling the jscode2session API in Wechat API service; String str = WeChatUtil.httpRequest (url," GET ", null) / / call the utility class to decrypt JSONObject jsonObject=JSONObject.parseObject (str); String openid = (String) jsonObject.get ("openid"); if (openid! = null & &! ".equals (openid)) {/ / login succeeded User userVo=new User (); userVo.setNickName (user.getNickName ()) UserVo.setAvatarUrl (user.getAvatarUrl ()); userVo.setOpenId (openid); userVo.setGender (user.getGender ()); userVo.setFirstLoginTime (new Date (System.currentTimeMillis (); userVo.setLastLoginTime (new Date (System.currentTimeMillis (); User us = userService.queryById (openid) If (us! = null) {/ / is not the first time to log in, update user information userVo.setId (us.getId ()); userService.updateUser (userVo) } else {/ / login for the first time to store user information userService.insertUser (userVo);} object.put ("code", 200); object.put ("msg", "login successful!") Object.put ("userInfo", userVo); return object;} else {object.put ("code", 400); object.put ("msg", "unknown error, please try again!"); return object }}

Launch class item

Package com.cxb;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.context.annotation.Bean;import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;@SpringBootApplicationpublic class item {/ / read configuration file information @ Bean public static PropertySourcesPlaceholderConfigurer placeholderConfigurer () {PropertySourcesPlaceholderConfigurer c = new PropertySourcesPlaceholderConfigurer (); c.setIgnoreUnresolvablePlaceholders (true); return c } public static void main (String [] args) {SpringApplication.run (item.class,args);}}

The part of the database should not be shared. I believe you can build it yourself according to the entity class.

The above is all the contents of the article "how to achieve WeChat Mini Programs login in Springboot". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report