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

通过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<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.后续改进

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;
    }

  • 3
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C是计算机科学中的一种编程语言。它是由美国贝尔实验室的丹尼斯·里奇于1972年为开发UNIX操作系统而设计的。C语言是一种高级语言,但也具有接近底层的功能和性能。它为程序员提供了更高的灵活性和控制力。 C语言是一种结构化的编程语言,它使用简单的语法和关键字,使程序员能够编写高效的代码。C语言具有良好的可移植性,因此可以在不同的操作系统和硬件上运行,这也使得C语言成为了广泛使用的编程语言之一。 C语言的特点包括强大的指针操作功能、内存管理的能力、丰富的运算符和数据类型。它还提供了丰富的标准库,包括输入输出函数、字符串处理函数等,简化了编程过程。 C语言的应用范围非常广泛。它被用于开发操作系统、编译器、数据库系统、嵌入式系统以及各种科学和工程领域的应用程序。许多其他编程语言,如C++和Java,都是以C语言为基础发展而来的。 学习C语言对于计算机科学专业的学生来说非常重要。掌握C语言可以帮助他们理解计算机底层的工作原理,并提高他们的编程能力。此外,C语言也是很多公司和科研机构招聘时的必备技能之一。 总之,C语言是一种重要的编程语言,具有广泛的应用和重要的教育价值。掌握C语言可以帮助人们成为优秀的程序员,并为他们的职业发展带来更多的机会。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值