一,微信获取认证信息分两种类型
本文采用第一种.
二 前端代码
首先获取code,然后重定向到当前页.
1)redirect_uri =替换成当前页面的地址
2)appid=换成自己微信公众号的appid
重定向后的页面结果如下
http://xxxxxx/xxxx/xxxx.html&code=xxxx&state=123;
然后,把获取到的code ajax请求后台,获取用户信息,存储到后端
三 后端代码
1)接口逻辑
Map data = RequestMapToUtil.getPostByTextPlain(request);
String code = data.get("code");
String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=xxxxxxxxxx&secret=xxxxxx&code=" + code + "&grant_type=authorization_code"; JSONObject jsonObject = WeiXinUtil.getCode(url, "GET", null);
String openid = jsonObject.getString("openid"); if (StringUtils.isNotBlank(openid) && !StringUtils.equals("null", openid)) { request.getSession().setAttribute("openid", openid);
HdWxUser hdWxUser = new HdWxUser(); hdWxUser.setCreateOn(new Date()); hdWxUser.setOpenid(openid); hdWxUser.setSource(data.get("from")); hdWxUser.setUrl(data.get("localUrl")); try { hdWxUserService.save(hdWxUser); } catch (Exception e) { // 不处理 } }
appid =替换为自己公众号的
secret =替换为自己公众号的
2)工具方法
public static JSONObject getCode(String requestUrl, String requestMethod, String outputStr) { JSONObject jsonObject = null; StringBuffer buffer = new StringBuffer(); try { URL url = new URL(requestUrl); HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
httpUrlConn.setDoOutput(true); httpUrlConn.setDoInput(true); httpUrlConn.setUseCaches(false); // 设置请求方式(GET/POST) httpUrlConn.setRequestMethod(requestMethod);
if ("GET".equalsIgnoreCase(requestMethod)) httpUrlConn.connect();
// 当有数据需要提交时 if (null != outputStr) { OutputStream outputStream = httpUrlConn.getOutputStream(); // 注意编码格式,防止中文乱码 outputStream.write(outputStr.getBytes("UTF-8")); outputStream.close(); }
// 将返回的输入流转换成字符串 InputStream inputStream = httpUrlConn.getInputStream(); InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8"); BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null; while ((str = bufferedReader.readLine()) != null) { buffer.append(str); } bufferedReader.close(); inputStreamReader.close(); // 释放资源 inputStream.close(); inputStream = null; httpUrlConn.disconnect(); jsonObject = JSONObject.parseObject(buffer.toString()); } catch (ConnectException ce) { log.error("Weixin server connection timed out."); } catch (Exception e) { log.error("https request error:{}", e); } return jsonObject; }
至此方法结束,数据库只存储了openid. 由于参数设置的snsapi_base(见第一大标题).
交流 QQ 1360215811.