• springboot实现网站微信扫码登录


    一、创建网站应用

    1. 在微信开发平台上面创建以个网站应用

    2. 微信开发平台地址 https://open.weixin.qq.com/https://open.weixin.qq.com/

    二、配置基本信息

    1. 把公用的信息放在application.yml中

      #微信开放平台创建的网站应用的appid
      AppID: *********
      #微信开放平台创建的网站应用的appsecret
      AppSecret: ***********************************
      scope: snsapi_login
      #微信开放平台创建的网站 设置的授权回调域
      redirect_url: 自己的回调地址,必须是公网能够访问的
    

    2. 获取微信二维码信息

       @Value("${AppID}")
        private String appid;
    
        @Value("${redirect_url}")
        private String callBack;
    
        @Value("${scope}")
        private String scope;
    
        @Value("${AppSecret}")
        private String appsecret;
        
        @Override
        public String getWechatCode() {
            try {
                String oauthUrl = "https://open.weixin.qq.com/connect/qrconnect?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect";
                String redirect_uri = URLEncoder.encode(callBack, "utf-8");
                oauthUrl =  oauthUrl.replace("APPID",appid).replace("REDIRECT_URI",redirect_uri).replace("SCOPE",scope);
                logger.info(oauthUrl);
                return ReturnMessage.success(0,"获取完成",oauthUrl);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return ReturnMessage.fail(44,"失败");
        }

    备注:在前端页面直接加载oauthUrl 就可以出现二维码界面了。直接用的微信的页面,也可以根据自己的爱好进行设计页面。如下图
     

    3. 接收扫码之后的信息

    httpUtil--这部分代码是在网上找的,但是这个是后来写的。如果发现原作者请告知
    import com.alibaba.fastjson.JSONObject;
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpStatus;
    import org.apache.http.client.config.RequestConfig;
    import org.apache.http.client.methods.CloseableHttpResponse;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.entity.StringEntity;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClients;
    import org.apache.http.util.EntityUtils;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
    import java.io.IOException;
    
    /**
     * 封装http get post
     */
    public class HttpUtils {
    
        private static Logger logger = LoggerFactory.getLogger(HttpUtils.class); // 日志记录
    
        private static RequestConfig requestConfig = null;
    
        static {
            // 设置请求和传输超时时
            requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build();
        }
    
        /**
         * post请求传输json参数
         *
         * @param url       url地址
         * @param jsonParam 参数
         * @return
         */
        public static JSONObject httpPost(String url, JSONObject jsonParam) {
            // post请求返回结果
            CloseableHttpClient httpClient = HttpClients.createDefault();
            JSONObject jsonResult = null;
            HttpPost httpPost = new HttpPost(url);
            // 设置请求和传输超时时请求
            httpPost.setConfig(requestConfig);
            try {
                System.out.println(jsonParam);
                if (null != jsonParam) {
                    // 解决中文乱码问题
                    StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");
                    entity.setContentEncoding("UTF-8");
                    entity.setContentType("application/json");
                    httpPost.setEntity(entity);
                }
                System.out.println(jsonParam);
                CloseableHttpResponse result = httpClient.execute(httpPost);
                // 请求发请求成功,并得到响应
                if (result.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    String str = "";
                    try {
                        // 读取服务器返回过来的json字符串数
                        str = EntityUtils.toString(result.getEntity(), "utf-8");
                        // 把json字符串转换成json对象
                        jsonResult = JSONObject.parseObject(str);
                    } catch (Exception e) {
                        logger.error("post请求提交失败:" + url, e);
                    }
                }
            } catch (IOException e) {
                logger.error("post请求提交失败:" + url, e);
            } finally {
                httpPost.releaseConnection();
            }
            return jsonResult;
        }
    
        /**
         * post请求传输String参数 例如:name=Jack&sex=1&type=2
         * Content-type:application/x-www-form-urlencoded
         *
         * @param url      url地址
         * @param strParam 参数
         * @return
         */
        public static JSONObject httpPost(String url, String strParam) {
            // post请求返回结果
            CloseableHttpClient httpClient = HttpClients.createDefault();
            JSONObject jsonResult = null;
            HttpPost httpPost = new HttpPost(url);
            httpPost.setConfig(requestConfig);
            try {
                if (null != strParam) {
                    // 解决中文乱码问题
                    StringEntity entity = new StringEntity(strParam, "utf-8");
                    entity.setContentEncoding("UTF-8");
                    entity.setContentType("application/x-www-form-urlencoded");
                    httpPost.setEntity(entity);
                }
                CloseableHttpResponse result = httpClient.execute(httpPost);
                // 请求发宋成功,并得到响应
                if (result.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    String str = "";
                    try {
                        // 读取服务器返回过来的json字符串数据
                        str = EntityUtils.toString(result.getEntity(), "utf-8");
                        // 把json字符串转换成json对象
                        jsonResult = JSONObject.parseObject(str);
                    } catch (Exception e) {
                        logger.error("post请求提交失败:" + url, e);
                    }
                }
            } catch (IOException e) {
                logger.error("post请求提交失败:" + url, e);
            } finally {
                httpPost.releaseConnection();
            }
            return jsonResult;
        }
    
        /**
         * 发送get请求
         *
         * @param url 路径
         * @return
         */
        public static JSONObject httpGet(String url) {
            // get请求返回结果
            JSONObject jsonResult = null;
            CloseableHttpClient client = HttpClients.createDefault();
            // 发送get请求
            HttpGet request = new HttpGet(url);
            request.setConfig(requestConfig);
            try {
                CloseableHttpResponse response = client.execute(request);
    
                // 请求发送成功,并得到响应
                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    // 读取服务器返回过来的json字符串数组
                    HttpEntity entity = response.getEntity();
                    String strResult = EntityUtils.toString(entity, "utf-8");
                    // 把json字符串转换成json对象
                    jsonResult = JSONObject.parseObject(strResult);
                } else {
                    logger.error("get请求提交失败:" + url);
                }
            } catch (IOException e) {
                logger.error("get请求提交失败:" + url, e);
            } finally {
                request.releaseConnection();
            }
            return jsonResult;
        }
    
    }


    作者:shmilylyp
    链接:https://www.jianshu.com/p/ce506c35c9bb
    来源:简书
    著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
  • 相关阅读:
    Java的审计项目导入---基于现有的微服务项目上再加个xmsj
    vo中对date格式的时间格式的处理,方便到前台展示
    Java的Maven项目的导入
    [2020-05]测试短信发送记录
    那些年总是记不住的前端写法!
    【HTML+CSS】比较清淡的一个表格。
    C# 里这么写 busiDate.replace('-', ' ').trim(),可以把2020-04-01转为 20200401;java里这么些只能转为2020 04 01……
    radType条件没有用?
    我的程序里面出现了下面的警告:Unreachable code请问是什么原因?该怎么解决呢?
    ubuntu18.04安装Charles及问题
  • 原文地址:https://www.cnblogs.com/niudaxianren/p/12691833.html
Copyright © 2020-2023  润新知