赞
踩
微信登录:https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/login.html
流程图:
步骤分析:
小程序端,调用wx.login()获取code,就是授权码。
小程序端,调用wx.request()发送请求并携带code,请求开发者服务器(自己编写的后端服务)。
开发者服务端,通过HttpClient向微信接口服务发送请求,并携带appId+appsecret+code三个参数。
开发者服务端,接收微信接口服务返回的数据,session_key+opendId等。opendId是微信用户的唯一标识。
开发者服务端,自定义登录态,生成令牌(token)和openid等数据返回给小程序端,方便后绪请求身份校验。
小程序端,收到自定义登录态,存储storage。
小程序端,后绪通过wx.request()发起业务请求时,携带token。
开发者服务端,收到请求后,通过携带的token,解析当前登录用户的id。
开发者服务端,身份校验通过后,继续相关的业务逻辑处理,最终返回业务数据。
说明:
调用 wx.login() 获取 临时登录凭证code ,并回传到开发者服务器。
调用 auth.code2Session 接口,换取 用户唯一标识 OpenID 、 用户在微信开放平台帐号下的唯一标识UnionID(若当前小程序已绑定到微信开放平台帐号) 和 会话密钥 session_key。
之后开发者服务器可以根据用户标识来生成自定义登录态,用于后续业务逻辑中前后端交互时识别用户身份。
实现步骤:
点击确定按钮,获取授权码,每个授权码只能使用一次,每次测试,需重新获取。
请求方式、请求路径、请求参数
3). 发送请求
获取session_key和openid
若出现code been used错误提示,说明授权码已被使用过,请重新获取
配置微信登录所需配置项:
application-dev.yml
sky:
wechat:
appid: wxffb3637a228223b8
secret: 84311df9199ecacdf4f12d27b6b9522d
application.yml
sky:
wechat:
appid: ${sky.wechat.appid}
secret: ${sky.wechat.secret}
配置为微信用户生成jwt令牌时使用的配置项:
application.yml
sky:
jwt:
# 设置jwt签名加密时使用的秘钥
admin-secret-key: itcast
# 设置jwt过期时间
admin-ttl: 7200000
# 设置前端传递过来的令牌名称
admin-token-name: token
user-secret-key: itheima
user-ttl: 7200000
user-token-name: authentication
根据接口定义创建UserController的login方法:
public class UserController { @Autowired private UserService userService; @Autowired private JwtProperties jwtProperties; @PostMapping("/login") @ApiOperation("微信登录") public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO){ log.info("微信登录:{}",userLoginDTO.getCode()); //微信登录 User user = userService.wxLogin(userLoginDTO); //为微信用户生成jwt令牌 /* 1.创建一个HashMap对象claims,用于存储JWT的payload信息。*/ HashMap<String, Object> claims = new HashMap<>(); /* 2.将用户的ID存储在claims中,键为JwtClaimsConstant.USER_ID。*/ claims.put(JwtClaimsConstant.USER_ID, user.getId()); /* 3.调用JwtUtil的createJWT方法,传入JWT的密钥、过期时间和claims,生成JWT令牌*/ String token = JwtUtil.createJWT(jwtProperties.getAdminSecretKey(), jwtProperties.getAdminTtl(), claims); /*使用UserLoginVO的构建器模式创建一个userLoginVO对象,设置用户的ID、OpenID和JWT令牌。*/ UserLoginVO userLoginVO = UserLoginVO.builder() .id(user.getId()) .openid(user.getOpenid()) .token(token) .build(); return Result.success(userLoginVO); } }
其中,JwtClaimsConstant.USER_ID常量已定义。
创建UserService接口:
public interface UserService {
/**
* 微信登录
* @param userLoginDTO
* @return
*/
User wxLogin(UserLoginDTO userLoginDTO);
}
**创建UserServiceImpl实现类:**实现获取微信用户的openid和微信登录功能
@Service public class UserServiceImpl implements UserService { //微信服务接口地址 public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session"; @Autowired private WeChatProperties weChatProperties; @Autowired private UserMapper userMapper; /** * 微信登录 * @param userLoginDTO * @return */ public User wxLogin(UserLoginDTO userLoginDTO) { /*首先,通过调用getOpenid方法获取微信用户的openid,传递的参数是userLoginDTO中的code属性。*/ String openid = getOpenid(userLoginDTO.getCode()); /*然后,判断获取到的openid是否为空。如果为空,表示登录失败,抛出一个业务异常。*/ //判断openid是否为空,如果为空表示登录失败,抛出业务异常 if(openid == null){ throw new LoginFailedException(MessageConstant.LOGIN_FAILED); } /*接下来,通过调用userMapper的getByOpenid方法,根据openid查询数据库中是否存在该用户。 如果不存在,则表示当前用户是一个新用户。*/ //判断当前用户是否为新用户 User user = userMapper.getByOpenid(openid); /*如果是新用户,通过User.builder()创建一个User对象,并设置其openid属性为获取到的openid,createTime属性为当前时间。 然后,调用userMapper的insert方法将新用户插入到数据库中。*/ //如果是新用户,自动完成注册 if(user == null){ user = User.builder() .openid(openid) .createTime(LocalDateTime.now()) .build(); userMapper.insert(user);//后绪步骤实现 } //返回这个用户对象 return user; } /** * 调用微信接口服务,获取微信用户的openid * @param code * @return */ private String getOpenid(String code){ //调用微信接口服务,获得当前微信用户的openid /*首先创建一个HashMap对象map,用于存储请求参数。将appid、secret、js_code和grant_type参数放入map中。*/ Map<String, String> map = new HashMap<>(); map.put("appid",weChatProperties.getAppid()); map.put("secret",weChatProperties.getSecret()); map.put("js_code",code); map.put("grant_type","authorization_code"); /*然后,调用HttpClientUtil的doGet方法,传入微信登录接口地址WX_LOGIN和map作为参数,发送GET请求,获取微信接口返回的JSON字符串。*/ String json = HttpClientUtil.doGet(WX_LOGIN, map); /*接下来,使用JSON.parseObject方法解析JSON字符串,将其转换为JSONObject对象。 然后,通过getString方法,从JSONObject中获取openid字段的值。*/ JSONObject jsonObject = JSON.parseObject(json); String openid = jsonObject.getString("openid"); return openid; } }
创建UserMapper接口:
public interface UserMapper { /** * 判断当前用户是否为新用户 * @param openid * @return */ @Select("select * from sky_take_out.user where openid = #{openid}") User getByOpenid(String openid); /** * 插入数据 * @param user */ void insert(User user); }
创建UserMapper.xml映射文件:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.sky.mapper.UserMapper">
<insert id="insert" useGeneratedKeys="true" keyProperty="id">
insert into user (openid, name, phone, sex, id_number, avatar, create_time)
values (#{openid}, #{name}, #{phone}, #{sex}, #{idNumber}, #{avatar}, #{createTime})
</insert>
</mapper>
**编写拦截器JwtTokenUserInterceptor:**统一拦截用户端发送的请求并进行jwt校验
public class JwtTokenUserInterceptor implements HandlerInterceptor { @Autowired private JwtProperties jwtProperties; /** * 校验jwt * * @param request * @param response * @param handler * @return * @throws Exception */ /*preHandle方法用于在请求到达Controller方法之前进行拦截和处理*/ public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { //判断当前拦截到的是Controller的方法还是其他资源 /* 1.首先,通过判断handler是否为HandlerMethod,来确定当前拦截到的是Controller的方法还是其他资源。 如果不是动态方法,直接放行,返回true。*/ if (!(handler instanceof HandlerMethod)) { //当前拦截到的不是动态方法,直接放行 return true; } //1、从请求头中获取令牌 /* 2.然后,从请求头中获取令牌,通过request.getHeader(jwtProperties.getUserTokenName())方法 获取到名为jwtProperties.getUserTokenName()的请求头的值,即令牌。*/ String token = request.getHeader(jwtProperties.getUserTokenName()); //2、校验令牌 try { log.info("jwt校验:{}", token); /* 3.接下来,校验令牌。 通过调用JwtUtil.parseJWT方法,传入jwtProperties.getUserSecretKey()和令牌作为参数,解析令牌并获取其载荷信息。*/ Claims claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), token); /*如果解析成功,将用户ID从载荷中取出,并通过Long.valueOf方法转换为Long类型。 然后,将当前用户ID设置到BaseContext中,以便在后续的处理中可以获取到当前用户的ID。*/ Long userId = Long.valueOf(claims.get(JwtClaimsConstant.USER_ID).toString()); log.info("当前用户的id:", userId); BaseContext.setCurrentId(userId); //3、通过,放行 /*最后,如果校验通过,返回true,放行请求。如果校验不通过,设置响应状态码为401,并返回false,表示拦截请求。*/ return true; } catch (Exception ex) { //4、不通过,响应401状态码 response.setStatus(401); return false; } } }
在WebMvcConfiguration配置类中注册拦截器:
@Autowired
private JwtTokenUserInterceptor jwtTokenUserInterceptor;
/**
* 注册自定义拦截器
* @param registry
*/
protected void addInterceptors(InterceptorRegistry registry) {
log.info("开始注册自定义拦截器...");
//.........
registry.addInterceptor(jwtTokenUserInterceptor)
.addPathPatterns("/user/**")
.excludePathPatterns("/user/user/login")
.excludePathPatterns("/user/shop/status");
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。