微信公众号获取code,openid,token

650 阅读1分钟
  1. 首先,需要有一个测试号,可以在这个网站申请 mp.weixin.qq.com/debug/cgi-b…

  2. 测试号的菜单跳转到自己的网站

image.png

/**
 *  创建菜单
 * */
@GetMapping(value = "/create-menu")
public Object test () {
    String token = AccessTokenUtil.getToken();
    String paramStr = "{\n" +
            "  "button":[\n" +
            "    {\n" +
            "      "type":"click",\n" +
            "      "name":"关于我们",\n" +
            "      "key":"get-post"\n" +
            "    },\n" +
            "    {\n" +
            "      "name":"查询工资",\n" +
            "      "type":"view",\n" +
            "      "url":"http://hnshuitou.natapp1.cc/user/init"\n" +
            "    },\n" +
            "    {\n" +
            "      "type":"view",\n" +
            "      "name":"后台测试",\n" +
            "      "url":"http://hnshuitou.natapp1.cc/system/getcode"\n" +
            "    }]\n" +
            "}\n";
    try {
        OkHttpClient client = new OkHttpClient();
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8") , paramStr);
        Request request = new Request.Builder().url(menuUrl + "?access_token=" + token).post(requestBody).build();
        Response response = client.newCall(request).execute();
        if (response.isSuccessful()) {
            System.out.println("创建菜单成功");
        }
    }catch (Exception e) {
        log.error("创建菜单出错");
    }
    return "success";
}

这里使用后台测试这个菜单跳转进行测试

<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>正在加载...</title>
    <link href="${pageContext.request.contextPath}/fwh/css/style.css" type="text/css" rel="stylesheet"/>
    <script src="${pageContext.request.contextPath}/fwh/js/zepto.min.js"></script>

    <script type="text/javascript">

        window.onload=function(){
            //code
            var code = getUrlParam(location.href , "code");
            // alert("1111111");
            alert(code);
            if (code != null) {
                //有code,跳转到UserController的plogin方法
                // window.location.href = "http://hnshuitou.natapp1.cc/system/init?code=" + code;
                window.location.href = "http://172.16.107.87:3000/#/login";

            }else {
                //回调地址
                var redirectUrl = "http://hnshuitou.natapp1.cc/system/getcode";
                var appid = "wx4385a7293e7d3647";
                window.location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appid+"&redirect_uri=" + redirectUrl + "&response_type=code&scope=snsapi_userinfo";
                // window.location.href = "http://hnshuitou.natapp1.cc/system/getcode";
            }
        };
        function getUrlParam(url,name){
            var pattern = new RegExp("[?&]"+name+"=([^&]+)", "g");
            var matcher = pattern.exec(url);
            var items = null;
            if(null != matcher){
                try{
                    items = decodeURIComponent(decodeURIComponent(matcher[1]));
                }catch(e){
                    try{
                        items = decodeURIComponent(matcher[1]);
                    }catch(e){
                        items = matcher[1];
                    }
                }
            }
            return items;
        }
    </script>
</head>
<body>
<div class="ny-head ny-head-log">
    <div class="ny-head-l"><img src="${pageContext.request.contextPath}/fwh/img/ico-colse.png"></div>
    <div class="ny-head-c">身份认证</div>
    <div class="ny-head-r"><img src="${pageContext.request.contextPath}/fwh/img/ico-dot.png"> </div>
</div>

<div class="login-box">
    <div class="profile_photo">
        <p>正在加载,请稍后...</p>
    </div>
</div>

</body>
</html>

这里新建了一个页面,freemaker模板yemian,过这个页面来获取code,第一次到这个页面是没有code的,通过这个页面跳转到回调地址,我们自己写的方法中,然后再次跳转到这个页面,就可以输出code了

https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appid+"&redirect_uri=" + redirectUrl + "&response_type=code&scope=snsapi_userinfo"

拿到code之后,将自己的测试号appid和secret和code拼接到一起向微信服务器发送请求,在响应中可以找到openid和secret

//    获取用户的openid
public String getOpenId (String code) throws IOException {
    System.out.println("进入getOpenId方法");
    //客户端
    OkHttpClient client = new OkHttpClient();
    //构建的Request
    Request request = new
            Request.Builder()
            .url(loginTokenUrl + "?appid=" + appId + "&secret=" + secret + "&code=" + code + "&grant_type=authorization_code").build();
    //得到响应信息
    Response response = client.newCall(request).execute();
    //响应体
    String body = response.body().string();
    //转换为JSON对象
    JSONObject object = JSON.parseObject(body);
    //提取accessToken
    String accessToken = object.getString("access_token");
    //提取openid
    String openId = object.getString("openid");
    return openId;
}

发送的请求

image.png

接收的响应

image.png