vue 微信授权

思路: 条件–>appid, url(哪个连接要实现微信授权) , status (我这个传递的是手机号)
思路1一进这个页面判断缓存是否有openId ,没有就去授权,有直接可以提现或者充值

   //判断是否有openId值 没有执行submitForm 如果有直接跳转toWithdraw.vue页面
        const openIdTemp = this.$utils.getStorage("openId");
        if (openIdTemp != null) {
            // 已授权登录 直接提现 充值
            this.goingON = true;

        } else {
            // 未授权
            this.goingON = false;
        }
        let path = window.location.href;
        if (path.indexOf("code") != -1) {
            let pathArray = path.split("?");
            let params = pathArray[1];
            let paramArray = params.split("&");
            let codeStr = paramArray[0];
            let codeArray = codeStr.split("=");
            let code = codeArray[1];
            let stateStr = paramArray[1];
            let stateArray = stateStr.split("=");
            let phone = stateArray[1];
            this.$utils.setStorage("phone", phone);
            this.tail = phone;
            this.getOpenId(code, phone);
        }
        this.originalHeight = document.documentElement.clientHeight || document.body.clientHeight;
    },

思路2:之后调用微信连接拿到code值,根据code值传递后台拿到openId,将这个值返回前台
async getWxUser() {
//1.判断openId是否存在存储
//2.判断存储里面的openId
//3.根据 user 去查
//4.没有就获取微信授权登录
if (this.openId == undefined || this.openId == null || this.openId == “”) {
const openIdTemp = this.$utils.getStorage(“openId”);
if (openIdTemp == undefined || openIdTemp == null || openIdTemp == “”) {
const appid = “wx10b9490a067b1e61”;
const url = “http://www.aiocloud.ltd/toAuthorize”;
const status = this.form.phone;
window.location.href =
“https://open.weixin.qq.com/connect/oauth2/authorize?appid=”
+ appid + “&redirect_uri=”
+ url
+ “&response_type=code&scope=snsapi_userinfo&state=” + status
+ "#wechat_redirect ";
} else {
this.goingON = false;
}
} else {
this.goingON = false;
}
},

思路三:后台根据code值拿到微信的openId值
window.location.href 向微信那边获得用户同意返回的code值, 根据code值去后台兑换openId
后面根据openId,可以去完成支付 (openId: 用户在微信的唯一标识)
后台创建HttpClient类 用来处理响应的链接

    public static String doGet(String httpurl) {
    HttpURLConnection connection = null;
    InputStream is = null;
    BufferedReader br = null;
    String result = null;// 返回结果字符串
    try {
        // 创建远程url连接对象
        URL url = new URL(httpurl);
        // 通过远程url连接对象打开一个连接,强转成httpURLConnection类
        connection = (HttpURLConnection) url.openConnection();
        // 设置连接方式:get
        connection.setRequestMethod("GET");
        // 设置连接主机服务器的超时时间:15000毫秒
        connection.setConnectTimeout(15000);
        // 设置读取远程返回的数据时间:60000毫秒
        connection.setReadTimeout(60000);
        // 发送请求
        connection.connect();
        // 通过connection连接,获取输入流
        if (connection.getResponseCode() == 200) {
            is = connection.getInputStream();
            // 封装输入流is,并指定字符集
            br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            // 存放数据
            StringBuffer sbf = new StringBuffer();
            String temp = null;
            while ((temp = br.readLine()) != null) {
                sbf.append(temp);
                sbf.append("\r\n");
            }
            result = sbf.toString();
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        // 关闭资源
        if (null != br) {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        if (null != is) {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        connection.disconnect();// 关闭远程连接
    }

    return result;
}

public static String doPost(String httpUrl, String param) {
    HttpURLConnection connection = null;
    InputStream is = null;
    OutputStream os = null;
    BufferedReader br = null;
    String result = null;
    try {
        URL url = new URL(httpUrl);
        // 通过远程url连接对象打开连接
        connection = (HttpURLConnection) url.openConnection();
        // 设置连接请求方式
        connection.setRequestMethod("POST");
        // 设置连接主机服务器超时时间:15000毫秒
        connection.setConnectTimeout(15000);
        // 设置读取主机服务器返回数据超时时间:60000毫秒
        connection.setReadTimeout(60000);

        // 默认值为:false,当向远程服务器传送数据/写数据时,需要设置为true
        connection.setDoOutput(true);
        // 默认值为:true,当前向远程服务读取数据时,设置为true,该参数可有可无
        connection.setDoInput(true);
        // 设置传入参数的格式:请求参数应该是 name1=value1&name2=value2 的形式。
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        // 设置鉴权信息:Authorization: Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0
        connection.setRequestProperty("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");
        // 通过连接对象获取一个输出流
        os = connection.getOutputStream();
        // 通过输出流对象将参数写出去/传输出去,它是通过字节数组写出的
        os.write(param.getBytes());
        // 通过连接对象获取一个输入流,向远程读取
        if (connection.getResponseCode() == 200) {

            is = connection.getInputStream();
            // 对输入流对象进行包装:charset根据工作项目组的要求来设置
            br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

            StringBuffer sbf = new StringBuffer();
            String temp = null;
            // 循环遍历一行一行读取数据
            while ((temp = br.readLine()) != null) {
                sbf.append(temp);
                sbf.append("\r\n");
            }
            result = sbf.toString();
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        // 关闭资源
        if (null != br) {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (null != os) {
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (null != is) {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        // 断开与远程地址url的连接
        connection.disconnect();
    }
    return result;
}
    
    在controller调用
      @PostMapping("/info")
public AiocloudResult<Object> getUserInfo(
        @RequestParam(value = "userId", required = true) String userId,
        @RequestParam(value = "code", required = true) String code,
        HttpServletRequest request
){
    System.out.println(userId);
    System.out.println(code);
    AiocloudResult<Object> result = new AiocloudResult<>();
    try{
        String url =
                "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + WxConfig.appid
                + "&secret=" + WxConfig.secret
                + "&code=" + code
                + "&grant_type=authorization_code";

        String res = HttpClient.doGet(url);
        System.out.println(res);
        JSONObject obj = JSONObject.parseObject(res);
        Object openId= obj.get("openid");
        result.setData(openId);

        //openId 放在服务器上
        HttpSession session = request.getSession();
        session.setAttribute("openid", openId);

        String accessToken = obj.get("access_token").toString();
        Object refreshToken = obj.get("refresh_token");
        String tokenUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + accessToken
                + "&openid=" + openId + "&lang=zh_CN";
        String userInfoStr = HttpClient.doGet(tokenUrl);
        JSONObject userInfoObj = JSONObject.parseObject(userInfoStr);
        Object nickName = userInfoObj.get("nickname");
        Object sex = userInfoObj.get("sex");
        Object province = userInfoObj.get("province");
        Object city = userInfoObj.get("city");
        Object country = userInfoObj.get("country");
        Object headimgurl = userInfoObj.get("headimgurl");

        BlWxUserDTO blWxUserDTO = new BlWxUserDTO();
        if(StringUtils.isNotBlank(userId)){
            List<BlWxUserVO> blWxUserVOList = blWxUserApp.getListByUserId(userId);
            if(blWxUserVOList != null && blWxUserVOList.size() > 0){
                for (BlWxUserVO blWxUserVO: blWxUserVOList){
                    if(userId != null){
                        blWxUserDTO.setBlUserId(userId);
                    }
                    if (city != null) {
                        blWxUserDTO.setCity(city.toString());
                    }
                    if (country != null) {
                        blWxUserDTO.setCountry(country.toString());
                    }
                    if (headimgurl != null) {
                        blWxUserDTO.setHeadImgUrl(headimgurl.toString());
                    }
                    blWxUserDTO.setOpenid(openId.toString());
                    if (province != null) {
                        blWxUserDTO.setProvince(province.toString());
                    }
                    if (refreshToken != null) {
                        blWxUserDTO.setRefreshToken(refreshToken.toString());
                    }
                    if(nickName != null){
                        blWxUserDTO.setNickname(nickName.toString());
                    }
                    if (sex != null) {
                        blWxUserDTO.setSex(sex.toString());
                    }
                    blWxUserDTO.setId(blWxUserVO.getId());
                    blWxUserDTO.setUpdateTime(new Date());
                    blWxUserApp.updateInfo(blWxUserDTO);
                }
            } else {
                if(userId != null){
                    blWxUserDTO.setBlUserId(userId);
                }
                if (city != null) {
                    blWxUserDTO.setCity(city.toString());
                }
                if (country != null) {
                    blWxUserDTO.setCountry(country.toString());
                }
                if (headimgurl != null) {
                    blWxUserDTO.setHeadImgUrl(headimgurl.toString());
                }
                blWxUserDTO.setOpenid(openId.toString());
                if (province != null) {
                    blWxUserDTO.setProvince(province.toString());
                }
                if(nickName != null){
                    blWxUserDTO.setNickname(nickName.toString());
                }
                if (refreshToken != null) {
                    blWxUserDTO.setRefreshToken(refreshToken.toString());
                }
                if (sex != null) {
                    blWxUserDTO.setSex(sex.toString());
                }
                blWxUserDTO.setId(UuidUtil.getUuid());
                blWxUserDTO.setCreateTime(new Date());
                blWxUserDTO.setUpdateTime(new Date());
                blWxUserApp.insertInfo(blWxUserDTO);
            }
        }
    }catch (Exception e){
        result.setCode(AiocloudResult.ERROR);
        result.setMsg("获取微信openid失败");
        log.error(e.getMessage());
        e.printStackTrace();
    }
    return result;
}

将微信用户的信息保存到数据库

上一篇:微信公众号打开h5 注册界面点击微信登录,获取微信信息绑定本地用户,一键登录


下一篇:atcoder beginner contest 239 E题