通过java方式获取微信用户openId

0.先熟悉微信网页授权流程

https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html

1.内网穿透

目的:使本地的服务能在微信客户端进行访问

1.购买隧道

https://natapp.cn/tunnel/buy

2.进行配置

配置域名,ip和端口。在这里配本地可以访问的服务的ip和端口。

3 下载客户端

3 打开命令行在客户端同级目录执行:natapp -authtoken=xxxxxxxxxx,使隧道服务上线

2.注册微信公众平台测试账号

1.进入系统注册测试账号

2.扫码关注

3.绑定域名

填写上一步绑定的域名 到这里就可以实现在微信端对本地服务进行调用

3.代码实现

@RequestMapping("/getCodeAndOpenId")

public WxInfo getCodeAndOpenId(@RequestParam("code") String code) {

log.info("==> 先获取code,再获取openid 。code={}", code);

Map params = new HashMap();

params.put("appid", "wxb00b277049d87059");

params.put("secret", "4f407849f4b50854ff6fbec3cc3d28a6");

params.put("grant_type", "authorization_code");

params.put("code", code);

String result = HttpGetUtil.httpRequestToString(

"https://api.weixin.qq.com/sns/oauth2/access_token", params);

WxInfo wxInfo = new WxInfo();

if (result != null) {

JSONObject jsonObject = JSONObject.parseObject(result);

String openid = jsonObject.get("openid").toString();

log.info("==> 获取的 openid={}", openid);

wxInfo.setCode(code);

wxInfo.setOpenid(openid);

}

return wxInfo;

}

说明:用户在微信端点击链接: https://open.weixin.qq.com/connect/oauth2/authorize?redirect_uri=http://niki.nat300.top/getCodeAndOpenId&appid=wxb00b277049d87059&response_type=code&scope=snsapi_base&state=1#wechat_redirect 后,会携带code跳转到 http://niki.nat300.top/getCodeAndOpenId,即执行getCodeAndOpenId方法 这个方法会根据code去获取openid

3.在微信端访问授权页面

在微信端任意一个窗口打开

4.返回结果

微信页面上返回了openid

5.总结

根据开发文档描述https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect,在访问这个授权页面后,需要跳转到最终真是访问的页面,实际上不需要,只需要是一个方法就行,而如果这个方法正好是获取openid的,那么正好顺势获取code,只需要通过一个方法就能获得openid。

6.工具类

public class HttpGetUtil {

public static String httpRequestToString(String url, Map params) {

String result = null;

try {

InputStream is = httpRequestToStream(url, params);

BufferedReader in = new BufferedReader(new InputStreamReader(is,

"UTF-8"));

StringBuffer buffer = new StringBuffer();

String line = "";

while ((line = in.readLine()) != null) {

buffer.append(line);

}

result = buffer.toString();

} catch (Exception e) {

return null;

}

return result;

}

private static InputStream httpRequestToStream(String url, Map params) {

InputStream is = null;

try {

if (!(params == null)) {

String parameters = "";

boolean hasParams = false;

for (String key : params.keySet()) {

String value = URLEncoder.encode(params.get(key), "UTF-8");

parameters += key + "=" + value + "&";

hasParams = true;

}

if (hasParams) {

parameters = parameters.substring(0, parameters.length() - 1);

}

url += "?" + parameters;

}

URL u = new URL(url);

HttpURLConnection conn = (HttpURLConnection) u.openConnection();

conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

conn.setRequestProperty("Accept-Charset", "UTF-8");

conn.setRequestProperty("contentType", "utf-8");

conn.setConnectTimeout(50000);

conn.setReadTimeout(50000);

conn.setDoInput(true);

//设置请求方式,默认为GET

conn.setRequestMethod("GET");

is = conn.getInputStream();

} catch (UnsupportedEncodingException e) {

e.printStackTrace();

} catch (MalformedURLException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

return is;

}

}

7.后续改进

1.需要在中间(虚拟)页面判断访问渠道 2.如果是微信则需要通过授权链接跳转到明细保存接口 3.否则直接跳转到明细保存接口

@RequestMapping("/share/middle")

public String middle(HttpServletRequest request, HttpServletResponse response) throws IOException {

String userAgent = request.getHeader("user-agent").toLowerCase();

if (userAgent.indexOf("micromessenger") != -1) {

log.info("==>用户访问的方式是微信渠道");

response.sendRedirect("https://open.weixin.qq.com/connect/oauth2/authorize?redirect_uri=http://niki.nat300.top/saveAccessDetail&appid=wxb00b277049d87059&response_type=code&scope=snsapi_base&state=1#wechat_redirect");

} else {

log.info("==>用户访问的方式是其他渠道");

response.sendRedirect("http://niki.nat300.top/saveAccessDetail?code=123");

}

return "";

}

@RequestMapping("/saveAccessDetail")

public WxInfo saveAccessDetail(HttpServletRequest request, @RequestParam("code") String code) {

String userAgent = request.getHeader("user-agent").toLowerCase();

WxInfo wxInfo = new WxInfo();

if (userAgent.indexOf("micromessenger") != -1) {

log.info("==>用户访问的方式是微信");

log.info("==> 先获取code,再获取openid 。code={}", code);

Map params = new HashMap();

params.put("appid", "wxb00b277049d87059");

params.put("secret", "4f407849f4b50854ff6fbec3cc3d28a6");

params.put("grant_type", "authorization_code");

params.put("code", code);

String result = HttpGetUtil.httpRequestToString(

"https://api.weixin.qq.com/sns/oauth2/access_token", params);

if (result != null) {

JSONObject jsonObject = JSONObject.parseObject(result);

String openid = jsonObject.get("openid").toString();

log.info("==> 获取的 openid={}", openid);

wxInfo.setCode(code);

wxInfo.setOpenid(openid);

}

}

log.info("==>执行存入redis操作");

response.sendRedirect("https://www.apache.org/");

log.info("==>跳转到最终实际访问的页面。。。。。。。。。。。。。。");

return wxInfo;

}

推荐链接

评论可见,请评论后查看内容,谢谢!!!评论后请刷新页面。