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

Java中直接获取微信小程序openid通常是通过微信提供的服务器端接口或者客户端SDK来进行的,因为openid属于敏感信息,一般不会直接暴露在前端代码中。以下是大致的步骤: 1. **服务器端获取**: - 首先,你需要集成微信小程序的服务器开发者工具,并注册你的服务端应用。 - 使用微信官方提供的`统一下单接口`(https://mp.weixin.qq.com/wiki?t=api-showcode-1542097381&docid=216424)生成一个授权链接,用户点击后会跳转到微信登录页面并授权小程序。 - 用户授权后,微信服务器会将openid等信息返回给你的后端服务器。你可以通过POST请求来请求这个授权结果,通常需要设置好的AppID、Secret和回调URL。 ```java String appId = "your_app_id"; String secret = "your_secret"; // 生成授权链接 Map<String, String> params = new HashMap<>(); params.put("appid", appId); params.put("redirect_uri", "your_callback_url"); params.put("response_type", "code"); params.put("scope", "snsapi_userinfo"); String authUrl = "https://api.weixin.qq.com/sns/oauth2/authorize?" + params.toString(); // 通过GET或POST方式微信服务器发送请求 ``` 2. **客户端JS-SDK获取**: - 如果你想在用户的设备上获取openid,可以在小程序中使用微信的JS-SDK。用户授权后,会在客户端回调中提供openid,这时你需要在后端接收处理并存储。 ```java wx.login({ ..., success(res) { // res.code是你需要提交到后台换取access_token和openid的凭证 wx.request({ url: 'your_server_api', // 发送给后端 data: { code: res.code }, method: 'POST', ... }); } }); ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值