Taro实现获取openid(附Spring boot代码)

1.前端代码(Taro)

 /**
         * evt
         * 微信快捷登录
         */
        const evtWxFastLogin = () => {
            Taro.login({
                success: function (res) {
                    if (res.code) {
                        // 获取到code后,将其传给后端
                        console.log(res.code);
                        let params = {
                            code:res.code
                        }
                        request.sendReq(request.apiUris.wxFastLogin,params).then(res=>{
                            console.log(res);
                        })
                    } else {
                        console.log("登录失败!" + res.errMsg);
                    }
                },
            });
        };

2.后端代码(Spring)

@PostMapping("/wx/openid")
    public WeiXinVO getOpenid(@RequestBody WeiXinIO weiXinIO) throws Exception {
        String code = weiXinIO.getCode();
        System.out.println("code"+code);
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        String appId = "wx7131f988a361b9dd";
        String secret = "ce245e780bdd94f7afca228ad0ef1213";

        // 向微信开放平台接口发送请求,获取openid
        System.out.println("发送消息");
        String params = "appid=" + appId + "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code";
        URL reqUrl = new URL(url + "?" + params);
        HttpURLConnection connection = (HttpURLConnection) reqUrl.openConnection();
        connection.setRequestMethod("GET");
        connection.setDoOutput(true);
        connection.setUseCaches(false);

        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        System.out.println("获取到的消息");
        System.out.println(reader);
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        reader.close();

        // 解析返回的json数据,获取openid
        JSONObject jsonObject = new JSONObject(sb.toString());
        String openid = jsonObject.getStr("openid");

        System.out.println(openid);
        WeiXinVO weiXinVO = new WeiXinVO();
        weiXinVO.setOpenId(openid);
        return weiXinVO;
    }

你可能感兴趣的:(taro,spring,boot,后端)