微信登入後端

📢 本文由 gemini-2.5-flash 翻譯

新年快樂!


流程: 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 表格

欄位名稱資料類型說明
idbigint主鍵,自動遞增
openidvarchar(45)微信使用者唯一識別碼
namevarchar(32)使用者姓名
phonevarchar(11)手機號碼
gendervarchar(2)性別
id_numbervarchar(18)身分證字號
avatarvarchar(500)微信使用者頭像路徑
create_timedatetime註冊時間

以個人身分註冊的小程式沒有權限取得微信使用者的手機號碼

程式配置

首先配置微信登入所需參數

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");
    }