功能描述:需要获取公众号下openId对应的用户基本信息;
实现思路:通过网页授权获取到code 用code 换取openid 和access_token 用openid和access_token获取用户基本信息;
第一步:获取code
调用微信获取code接口
接口地址:https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxb82f22f6b7011d4e&redirect_uri=http%3a%2f%2fds.tunnel.echomod.cn%2fDentalinkServiceWeb%2fuser%2fwechatCheck&response_type=code&scope=snsapi_base&state=STATE&connect_redirect=1#wechat_redirect
appid: 在公众号内可以查看。
redirect_uri:外网能访问的项目地址要具体到方法 也就是说接收code的方法。其他参数默认就好.
第二步:获取openid和access_token首先接收code:代码如下:@RequestMapping("/wechatCheck") @ResponseBody public ModelAndView wechatCheck(@RequestParam(value = "code", required = true) String code, HttpServletRequest request, HttpServletResponse response, HttpSession session) throws Exception { ModelAndView model = new ModelAndView(); try { String openId = ""; //微信openId String accessToken = ""; //微信access_token openId = (String) request.getSession().getAttribute(SessionConstants.OPENID_SESSION_ID); accessToken = (String) request.getSession().getAttribute(SessionConstants.ACCESSTOKEN_SESSION_ID); if (openId == null || "".equals(openId)) { // 获取openId try { JSONObject src = WechatTools.queryOpenId(code); //调用微信接口 openId = src.getString("openid"); //微信openId accessToken = src.getString("access_token"); //微信access_token System.out.println(src); } catch (Exception e) { e.printStackTrace(); logger.error("获取openId错误========================"+e.getMessage()+"========================"); } }工具类方法url地址是获取openid和access_token接口地址地址:https://api.weixin.qq.com/sns/oauth2/access_token?appid=wxb82f22f6b7011d4e&secret=be373618314eec41a2c65567c44764ee&grant_type=authorization_codeappid: 在公众号内可以查看。secret:是你APPID密钥 在公众号内查看public class WechatTools { private static Logger logger = Logger.getLogger(WechatTools.class); public static JSONObject queryOpenId(String code) throws Exception { //String openId = ""; String url = (String)PropertiesHandler.getConfigValue("wechat.openid.url").toString(); if (url == null || "".equals(url)) { throw new RecruitException(ErrorsInfo.SYS_ERROR, "系统异常,缺少openId URL配置", "系统异常"); } String params = "&code=" + code; url = url + params; JSONObject json = HttpClientTools.doGet(url); logger.error("微信返回========================" + json + "=========================="); logger.error("微信返回========================" + json + "=========================="); logger.error("微信返回========================" + json + "=========================="); /*if (json != null) { openId = json.getString("openid"); if (openId == null) { throw new RecruitException(ErrorsInfo.ERR00003, "微信错误,获取不到openId", "微信错误"); } } String src = json.toString();*/ return json; }doget方法
/** * Http Client 自定义工具类 * @author kail.huang */ public class HttpClientTools { private static Logger logger = Logger.getLogger(HttpClientTools.class); /** * Http Get 请求方法 * @param url * @return * @throws Exception */ public static JSONObject doGet(String url) throws Exception { JSONObject json = null; HttpGet httpGet = new HttpGet(url); // 创建httpClientBuilder HttpClientBuilder clientBuilder = HttpClientBuilder.create(); // httpclient CloseableHttpClient httpClient = clientBuilder.build(); try { HttpResponse httpResponse = httpClient.execute(httpGet); HttpEntity entity = httpResponse.getEntity(); if (entity != null) { String result = EntityUtils.toString(entity, "UTF-8"); json = JSONObject.fromObject(result); } } catch (ClientProtocolException e) { e.printStackTrace(); logger.error(e.getMessage()); throw new RecruitException(ErrorsInfo.ERR00001, "HttpClient 请求异常", "HttpClient 请求异常,请检查日志!"); } catch (IOException e) { e.printStackTrace(); logger.error(e.getMessage()); throw new RecruitException(ErrorsInfo.ERR00002, "IO 读取异常", "IO 读取异常,请检查日志!"); } return json; }第三步:获取微信个人信息通过openid和access_token获取微信个人信息url:https://api.weixin.qq.com/sns/userinfo?到这里就能成功获取用户个人信息了 如下信息代码如下:/**wechat.userInfo.url * 获取微信用户个人信息 * @param openId * @param userId * @return */ public static SnsUserinfoVO snsUserinfoVO(String openId,String accessToken, long userId) throws Exception{ SnsUserinfoVO snsUserInfo = null; SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式 String url = (String)PropertiesHandler.getConfigValue("wechat.userInfo.url").toString(); if (url == null || "".equals(url)) { throw new RecruitException(ErrorsInfo.SYS_ERROR, "系统异常,缺少获取微信userInfo URL配置", "系统异常"); } String params = "access_token="+accessToken+"&openid="+openId+"&lang=zh_CN"; url = url + params; logger.error("调用接口url========================" + url + "=========================="); JSONObject jsonObject = HttpClientTools.doGet(url); logger.error("调用接口获取微信用户个人信息 微信返回参数========================" + jsonObject + "=========================="); snsUserInfo = new SnsUserinfoVO(); // 用户的标识 snsUserInfo.setOpenId(jsonObject.getString("openid")); // 昵称 snsUserInfo.setNickName(jsonObject.getString("nickname")); // 性别(1是男性,2是女性,0是未知) snsUserInfo.setSex(jsonObject.getInt("sex")); // 用户所在国家 snsUserInfo.setCountry(jsonObject.getString("country")); // 用户所在省份 snsUserInfo.setProvince(jsonObject.getString("province")); // 用户所在城市 snsUserInfo.setCity(jsonObject.getString("city")); // 用户头像 snsUserInfo.setHeadImgUrl(jsonObject.getString("headimgurl")); //提交时间 snsUserInfo.setInputTime(df.format(new Date())); //修改时间 snsUserInfo.setModifyTime(df.format(new Date())); //提交者 snsUserInfo.setInputBy(userId); //修改者 snsUserInfo.setModifyBy(userId); //状态 snsUserInfo.setStatus(1); return snsUserInfo; }
{"openid":"oMEfB0d5-CpkKLsWIp3Yvmk-Wp5E","nickname":"卓力","sex":1,"language":"zh_CN","city":"河源","province":"广东","country":"中国","headimgurl":"http://wx.qlogo.cn/mmopen/Q3auHgzwzM4v340hdqKAkhkTG2SJjjBpE8MR2eNEUSbGzn2r3yAbibQxib6eiaXicYXA08ZkIiajiaWibohY5GiaMqZ4eZNmcgR07TdPXUGhqDMgkgU/0","privilege":[]}