1 需求
在开发微信小程序项目时,登录采用的是openId方式,这是一种用户无感的登录方式,用户点开微信小程序时,去调用后端的登录接口。
核心代码
@Slf4j
@Component
public class WeChatUtil {
private static final String xcxAppId = "xxx";
private static final String xcxAppSecret = "xxx";
public static JSONObject getSessionKeyOrOpenId(String code) {
String url = "https://api.weixin.qq.com/sns/jscode2session";
Map<String, String> params = new HashMap<>();
params.put("appid", xcxAppId);
params.put("secret", xcxAppSecret);
params.put("js_code", code);
params.put("grant_type", "authorization_code");
return JSON.parseObject(HttpClientUtil.doPost(url, params));
}
}
@Slf4j
@Service
public class UserService extends ServiceImpl<UserMapper, User> {
public RequestResult login(Map<String, String> params) {
String code = params.get("code");
JSONObject weChatObject = WeChatUtil.getSessionKeyOrOpenId(code);
String openId = weChatObject.getString("openid");
if (StrUtil.isEmpty(openId)) {
return RequestResult.fail("获取微信openid失败");
}
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("open_id", openId);
User findUser = baseMapper.selectOne(queryWrapper);
if (findUser != null) {
findUser.setToken(JwtUtil.createTokenByUserIdOpenId(String.valueOf(findUser.getId()), openId));
return RequestResult.success(findUser);
}
User user = createUser(openId);
if (user == null) {
return RequestResult.fail("用户信息初始化失败");
}
user.setToken(JwtUtil.createTokenByUserIdOpenId(String.valueOf(user.getId()), openId));
return RequestResult.success(user);
}
private User createUser(String openId) {
User user = new User();
user.setOpenId(openId);
user.setCreateTime(DateUtil.now());
int result = baseMapper.insert(user);
return result > 0 ? user : null;
}
}