ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

vue 微信授权

2021-10-27 16:31:18  阅读:181  来源: 互联网

标签:openId vue String 微信 connection blWxUserDTO toString 授权 null


思路: 条件–>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;
}

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

标签:openId,vue,String,微信,connection,blWxUserDTO,toString,授权,null
来源: https://blog.csdn.net/weixin_52090775/article/details/119007771

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有