要在微信公号中新建自定义菜单,然后导航到公司H5中,需要首先获取用户微信信息,然后再进行手机号绑定,以前微信公号开发做的不多,记录下,希望能帮到需要的朋友!
https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html#1
特别说明下,需要认证服务号才能通过页面授权获取用户信息,如下图:
登录微信公号后台进行设置(https://mp.weixin.qq.com/)
处于安全考虑,开发者密码,微信不保存,一旦忘记,需要重置,重置需管理员扫码和录入公号密码。
这里有个微信回写地址需要设置,必须是域名。
这样就设置完毕了。
简单就是拼接微信参数+httpclient调用微信接口。
@GetMapping("/wxlogin") public String wxlogin() { // 第一步:用户同意授权,获取code String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid + "&redirect_uri=" + http + "&response_type=code" + "&scope=snsapi_userinfo" + "&state=STATE#wechat_redirect"; return "redirect:" + url; }
这里的调用(wxcallback)是设置在微信公号中的回写地址,就是第一步的获取code的时候,&redirect_uri= http中,配置文件是这样的:
@GetMapping("/wxcallback") public String wxcallback(String code, ModelMap map) throws IOException { // 第二步:通过code换取网页授权access_token String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appid + "&secret=" + appsecret + "&code=" + code + "&grant_type=authorization_code"; JSONObject jsonObject = HttpClientUtils.doGet(url); String openid = jsonObject.getString("openid"); String access_Token = jsonObject.getString("access_token"); System.out.println(jsonObject); // 第四步:拉取用户信息(需scope为 snsapi_userinfo) url = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access_Token + "&openid=" + openid + "&lang=zh_CN"; JSONObject userInfoJson = HttpClientUtils.doGet(url); System.out.println("UserInfo:" + userInfoJson); // 2种情况: 我们是有账号体系的,微信帐号做来一个关联,来关联我们的账号体系 UserEntity userEntity = userService.getOpenid(openid); if (userEntity == null) { userEntity = new UserEntity(); userEntity.setType(0); userEntity.setOpenid(openid); userEntity.setNickname((String)userInfoJson.get("nickname")); userEntity.setImage((String)userInfoJson.get("headimgurl")); userService.insert(userEntity); } else { userEntity.setNickname((String)userInfoJson.get("nickname")); userEntity.setImage((String)userInfoJson.get("headimgurl")); userService.update(userEntity); } return "redirect:/gohome?openid=" +openid; }
代码中增加了用户关联的部分,可以不要。
微信公号中有个段特别说明,简单说就是假如是关注了公号,然后从自定义菜单进入,其实是静默获取的,不需要用户授权的,测试了下,确实如此。
https://github.com/ruanjianlaowang/wxoauth
?
java获取微信用户信息(含源码,直接改下appid就可以使用了)
原文:https://blog.51cto.com/ruanjianlaowang/2962488