java微信验证

  • Post author:
  • Post category:java


@Value("${custom.wechat.appId}")
private String wechatAppId;  //微信公众号appID

@Value("${custom.wechat.secret}")
private String wechatSecret; //微信公众号appsecret

@GetMapping(value = "/wechatAuthorization")
@ApiOperation(value = "微信验证")
public ResultVO wechatAuthorization(@RequestParam String wechatCode) {
    try {
        if (StringUtils.isEmpty(wechatCode)) {
            return ResultVO.FAIL("请先获取微信授权!", null);
        }
        Map<String, String> param = new HashMap<>();
        param.put("appid", wechatAppId);
        param.put("secret", wechatSecret);
        param.put("code", wechatCode);
        param.put("grant_type", "authorization_code");
        RestTemplate restTemplate = new RestTemplate();
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + wechatAppId + "&secret=" + wechatSecret
                + "&code=" + wechatCode + "&grant_type=authorization_code";
        ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
        if (response != null && response.getStatusCode() == HttpStatus.OK) {
            Map<String, Object> resultMap = new HashMap<>();
            String errCode = JSONObject.parseObject(response.getBody()).getString("errcode");
            if (StringUtils.isEmpty(errCode)) {
                String openId = JSONObject.parseObject(response.getBody()).getString("openid");
                SysUser entity = sysUserService.getOne(
                        new LambdaQueryWrapper<SysUser>().eq(SysUser::getUserName, openId)
                );
                if (entity != null) {
                    String token = JwtUtil.sign(entity);
                    resultMap.put("status", true);
                    resultMap.put("token", token);
                    resultMap.put("account", entity.getAccount());
                    RedisTool.set(JwtUtil.getTokenCacheKey(entity.getId()), token);
                } else {
                    resultMap.put("status", false);
                    resultMap.put("openId", openId);
                }
                return ResultVO.SUCCESS(resultMap);
            } else {
                log.error("微信验证wechatCode:【" + wechatCode + "】");
                log.error("微信验证response:【" + JSON.toJSONString(response) + "】");
                return ResultVO.FAIL("微信验证失败!errCode【" + errCode + "】", null);
            }
        }
        return ResultVO.FAIL("微信验证失败!", null);
    } catch (Exception e) {
        e.printStackTrace();
        log.error("微信验证异常!", e);
        return ResultVO.ERROR("微信验证异常!", null);
    }
}



版权声明:本文为weixin_43853787原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。