Java微信公众号授权登录
1. 微信授权登录机制授权机制
微信移动设备授权登录是基于 OAuth2.0 协议标准构建的,从分类上来看,这种登陆方式满足 协议标准 的 第四种方式,即凭证式。
凭证式的认证方式
- 应用通过URL中携带 client_id 和 client_secret 来发出认证请求。
- 目标网站接收请求后两项验证通过后,直接返回令牌。
- 该令牌对应的是唯一应用,而不是唯一用户,所有整个应用的用户发送的请求都使用同一令牌。
2. 配置内网穿透
- 使用NATAPP网站配置隧道,获取本地电脑的临时域名。
- 详细配置教程NATAPP注册账号配置隧道
3. 微信公众号测试号配置
扫码登录 微信公众平台
获取个人的测试号信息,也就是对应我们上文提到的 client_id 和 client_secret

- 修改JS安全域名为内网穿透获得的临时域名

- (这里的接口网址不带http)
- 扫码关注自己的公众测试号,这样才能进行之后的扫码授权等操作

- 开启测试号网页授权功能并配置


(这里依然使用获得的临时域名)
4. 网页授权登录配置
查看[官方文档]( 微信开放文档 (qq.com) )
掌握了网页授权登录的基本步骤
2 第二步:通过code换取网页授权access_token
代码实现
前台获取code
//截取code值 getUrlParam(name) { var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)') let url = window.location.href.split('#')[0] let search = url.split('?')[1] if (search) { var r = search.substr(0).match(reg) if (r !== null) return unescape(r[2]) return null } else return null },发送含参的url请求
//判断信息是否传入 if(code==null){ return ResultJson.failure(ResultCode.ID_NOTFOUND); } String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + weiXinProperties.getAppid() + "&secret=" + weiXinProperties.getAppsecret() + "&code=" + code + "&grant_type=authorization_code";获取 access_token
JSONObject jsonObject = HttpUtils.httpGet(url); String openId = jsonObject.getString("openid"); String access_Token = jsonObject.getString("access_token"); String accessToken = weiXinShareService.getAccessToken();获取用户信息
// 拉取用户信息(需scope为 snsapi_userinfo) url = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access_Token + "&openid=" + openId + "&lang=zh_CN"; JSONObject userInfoJson = HttpUtils.httpGet(url); log.info("拉取到的用户信息"+userInfoJson.toJSONString()); if(String.valueOf(userInfoJson.get("errcode")).equals("40014")){ return ResultJson.failure(ResultCode.NOT_ONLY_CODE); }总体代码
@GetMapping("/getUserInfo") public ResultJson getUserInfo(String code,HttpServletResponse response) throws Exception { //判断信息是否传入 if(code==null){ return ResultJson.failure(ResultCode.ID_NOTFOUND); } String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + weiXinProperties.getAppid() + "&secret=" + weiXinProperties.getAppsecret() + "&code=" + code + "&grant_type=authorization_code"; JSONObject jsonObject = HttpUtils.httpGet(url); String openId = jsonObject.getString("openid"); String access_Token = jsonObject.getString("access_token"); String accessToken = weiXinShareService.getAccessToken(); // 拉取用户信息(需scope为 snsapi_userinfo) url = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access_Token + "&openid=" + openId + "&lang=zh_CN"; JSONObject userInfoJson = HttpUtils.httpGet(url); log.info("拉取到的用户信息"+userInfoJson.toJSONString()); if(String.valueOf(userInfoJson.get("errcode")).equals("40014")){ return ResultJson.failure(ResultCode.NOT_ONLY_CODE); } if(userInfoJson!=null){ //业务操作判断 }
版权声明:本文为weixin_45750855原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。