java微信授权实现

1.获取用户code 

@Autowired
private RedisTemplate<String, String> redisTemplate;

/**
 * 用户同意授权,获取code
 *
 * @return java.lang.String
 * @date 2022/2/15
 **/
@Override
public void wxAuthorizeUrl(String redirectUri, HttpServletResponse response) {
    String urlString = "";
    String url = "";
    try{
        urlString = URLEncoder.encode(payConfig.getRedirectUri(), "utf-8");
        url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+payConfig.getAppId()+"&redirect_uri="+urlString+"&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
        response.sendRedirect(url);
        //放入缓存
        String regMobileKey = RedisKeyConstants.REDIRECT_KEY;
        final BoundValueOperations<String, String> regKey = redisTemplate.boundValueOps(regMobileKey);
        regKey.set(redirectUri.replace("~","#"), 5, TimeUnit.MINUTES);
    }catch (Exception e){
        log.error("用户同意授权 异常:",e);
        throw new ServiceException("用户同意授权 异常:"+e.toString());
    }
}

2.创建实体

@Data
public class WxAuthorizeDto {

    @JSONField(name = "access_token")
    private String accessToken;

    @JSONField(name = "expires_in")
    private String expiresIn;

    @JSONField(name = "refresh_token")
    private String refreshToken;

    @JSONField(name = "openid")
    private String openId;

    @JSONField(name = "scope")
    private String scope;

    @JSONField(name = "errcode")
    private String errCode;

    @JSONField(name = "errmsg")
    private String errMsg;
}

3.通过code获取openId

   /**
     * 微信授权获取openId;
     * @param code :
     *
     * @date 2022/2/15
     **/
    @Override
    public WxAuthorizeDto wxAuthorizeOpenId(String code,HttpServletResponse response) {
        try {
            //通过code换取网页授权access_token
            String result = HttpUtil.get("https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + payConfig.getAppId() + "&secret=" + payConfig
                    .getSecret() + "&code=" + code + "&grant_type=authorization_code");
            if (StringUtils.isEmpty(result)) {
                throw new ServiceException(PayEnum.WX_AUTHORIZE_IS_NULL.getValue(),
                    PayEnum.WX_AUTHORIZE_IS_NULL.getDescription());
            }
            WxAuthorizeDto wxAuthorizeDto = JSONObject.parseObject(result, WxAuthorizeDto.class);
            if (StringUtils.isNotEmpty(wxAuthorizeDto.getErrCode())) {
                throw new ServiceException(Integer.parseInt(wxAuthorizeDto.getErrCode()), wxAuthorizeDto.getErrMsg());
            }
            //拉取用户信息
            String resultUser = HttpUtil.get("https://api.weixin.qq.com/sns/userinfo?access_token="+ wxAuthorizeDto.getAccessToken() +"&openid="+ wxAuthorizeDto.getOpenId() +"&lang=zh_CN");
            WxUserInfoDto wxUserInfoDto = JSONObject.parseObject(resultUser, WxUserInfoDto.class);
            if (StringUtils.isNotEmpty(wxUserInfoDto.getErrCode())) {
                throw new ServiceException(Integer.parseInt(wxUserInfoDto.getErrCode()), wxUserInfoDto.getErrMsg());
            }
            //获取缓存
            final BoundValueOperations<String, String> regKey = redisTemplate.boundValueOps(RedisKeyConstants.REDIRECT_KEY);
            if(ObjectUtil.isEmpty(regKey)){
                return null;
            }
            //如果回调url需要带参数需要这样处理
            String url = regKey.get();
            if(url.contains("?")){
                url = url + "&openId="+wxAuthorizeDto.getOpenId();
            }else {
                url = url + "?openId="+wxAuthorizeDto.getOpenId();
            }
            response.sendRedirect(url);
            return wxAuthorizeDto;
        }catch (Exception e){
            log.error("微信授权获取openId 异常:",e);
            throw new ServiceException("微信授权获取openId 异常:"+e.toString());
        }
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值