iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > JAVA >通过java方式获取微信用户openId
  • 430
分享到

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

微信微信小程序java 2023-08-21 11:08:50 430人浏览 安东尼
摘要

通过java方式获取微信用户openId 0.先熟悉微信网页授权流程 https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authoriza

通过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
后,会携带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<String, String> 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<String, String> 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.后续改进

需要在中间(虚拟)页面判断访问渠道
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;    }

来源地址:https://blog.csdn.net/weixin_37926633/article/details/131353083

--结束END--

本文标题: 通过java方式获取微信用户openId

本文链接: https://www.lsjlt.com/news/376940.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作