Home 微信登录后端
Post
Cancel

微信登录后端

Happy Lunar Year!


流程:https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/login.html

前端获取授权码,向 https://api.weixin.qq.com/sns/jscode2session 发起请求,获取 session_key 和 openid

微信请求接口:https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/user-login/code2Session.html

分析设计

接口设计

请求路径:/user/user/login

请求方式:POST

请求参数:code String (微信用户授权码)

返回数据:

  • id integer (用户 id)
  • openid (微信 openid)
  • token (jwt 令牌)

数据库表设计

用户第一次使用小程序会自动注册,将相关信息存储到 user 表

字段名 数据类型 说明
id bigint 主键,自增
openid varchar(45) 微信用户唯一标识
name varchar(32) 用户姓名
phone varchar(11) 手机号
gender varchar(2) 性别
id_number varchar(18) 身份证号
avatar varchar(500) 微信用户头像路径
create_time datetime 注册时间

个人身份注册的小程序没有权限获取到微信用户的手机号

程序配置

首先配置微信登录所需参数

application-dev.yml

1
2
3
4
sky:
  wechat:
    appid: your_appid
    secret: your_secret

application.yml

1
2
3
4
sky:
  wechat:
    appid: ${sky.wechat.appid}
    secret: ${sky.wechat.secret}

配置为微信用户生成 jwt 令牌时使用的配置项

1
2
3
4
5
6
sky:
  jwt:
    # 用户相关
    user-secret-key: key
    user-ttl: 7200000
    user-token-name: authentication

Java

业务代码

controller

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
@RestController
@RequestMapping("/user/user")
@Api(tags = "用户相关接口")
@Slf4j
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令牌
        HashMap<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(), claims);

        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .openid(user.getOpenid())
                .token(token)
                .build();

        return Result.success(userLoginVO);
    }
}

service

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
@Service
@Slf4j
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;

    @Override
    public User wxlogin(UserLoginDTO userLoginDTO) {
        String openid = getOpenid(userLoginDTO.getCode());

        // 判断openid是否合法
        if (openid == null){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }

        // 判断是否为新用户
        User user = userMapper.getByOpenid(openid);
        // 若为新用户,自动注册
        if (user == null){
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insert(user);
        }
        return user;
    }

    // 调用微信接口,获取用户openid
    private String getOpenid(String code){
        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");

        String json = HttpClientUtil.doGet(WX_LOGIN, map);

        JSONObject jsonObject = JSON.parseObject(json);
        String openid = jsonObject.getString("openid");
        return openid;
    }
}

Mapper

1
2
3
4
5
6
7
@Mapper
public interface UserMapper {
    @Select("select * from user where openid = #{openid}")
    User getByOpenid(String openid);

    void insert(User user);
}

Mapper XML

1
2
3
4
5
6
7
8
9
<?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">
        insert into user(openid, name, phone, sex, id_number, avatar, create_time)
        VALUES (#{openid}, #{name}, #{phone}, #{sex}, #{idNumber}, #{avatar}, #{createTime})
    </insert>
</mapper>

拦截器

统一拦截用户端发送的请求进行 jwt 校验

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
@Component
@Slf4j
public class JwtTokenUserInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtProperties jwtProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 判断拦截类型,是controller还是其他资源
        if(!(handler instanceof HandlerMethod)){
            // 当前拦截的不是动态方法,直接放行
            return true;
        }

        // 从请求中获取令牌
        String token = request.getHeader(jwtProperties.getUserTokenName());
        // 校验令牌
        try {
            log.info("jwt校验:{}", token);
            Claims claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), token);
            Long userId = Long.valueOf(claims.get(JwtClaimsConstant.USER_ID).toString());
            log.info("当前用户id:{}", userId);
            BaseContext.setCurrentId(userId);
            // 校验通过
            return true;
        }catch (Exception ex){
            // 校验未通过
            return false;
        }
    }
}

在 WebMvcConfiguration 注册拦截器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
	@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");
    }
This post is licensed under CC BY 4.0 by the author.

了解微信小程序

CentOS 7 安装 Xfce