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);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值