ソースを参照

Merge remote-tracking branch 'origin/master'

jk-GitHub-coder 4 年 前
コミット
03fd44e193

+ 125 - 0
YijiaRestful/src/main/java/com/platform/yijia/controller/WXLoginController.java

@@ -0,0 +1,125 @@
+package com.platform.yijia.controller;
+
+import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.JSONObject;
+import com.platform.yijia.utils.ConstantUtil;
+import com.platform.yijia.utils.HttpClientUtil;
+import com.platform.yijia.utils.SignUtil;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+import java.io.UnsupportedEncodingException;
+import java.net.URLEncoder;
+import java.text.ParseException;
+
+/**
+ * @Author : suxinghua
+ * @CreateTime : 2020/11/25
+ * @Description :
+ **/
+
+@RestController
+@RequestMapping("/wxAuth")
+public class WxLoginController {
+
+
+    /**
+     * 用于给微信验证token
+     *
+     * @param request
+     * @param response
+     * @return
+     * @throws IOException
+     */
+    @RequestMapping("/checkToken")
+    public String checkToken(HttpServletRequest request, HttpServletResponse response) throws IOException {
+        // 微信加密签名
+        String signature = request.getParameter("signature");
+        // 时间戳
+        String timestamp = request.getParameter("timestamp");
+        // 随机数
+        String nonce = request.getParameter("nonce");
+        // 随机字符串
+        String echostr = request.getParameter("echostr");
+
+        if (SignUtil.checkSignature(signature, timestamp, nonce)) {
+            System.out.println("校验token成功");
+            return echostr;
+        } else {
+            System.out.println("校验token不成功");
+            return null;
+        }
+    }
+
+    /**
+     * 用于获取出回调地址  (引导用户调用此接口,成功后自动调取回调地址然后取出用户信息)
+     *
+     * @param response
+     * @throws IOException
+     */
+    @RequestMapping("/login")
+    public String wxLogin(HttpServletResponse response)  throws ParseException {
+        //请求获取code的回调地址
+        //用线上环境的域名或者用内网穿透,不能用ip
+        String callBack = "http://www.onlyfido.top/wxAuth/callBack";//域名填你自己的
+        //请求地址
+        String url = null;
+        try {
+            url = "https://open.weixin.qq.com/connect/oauth2/authorize" +
+                    "?appid=" + ConstantUtil.APPID +
+                    "&redirect_uri=" + URLEncoder.encode(callBack, "utf-8") +
+                    "&response_type=code" +
+                    "&scope=snsapi_userinfo" +
+                    "&state=STATE#wechat_redirect";
+        } catch (UnsupportedEncodingException e) {
+            e.printStackTrace();
+        }
+
+        System.out.println(url);
+        //重定向
+       // response.sendRedirect(url);
+        return "redirect:" + url;
+    }
+
+    /**
+     * 回调方法
+     *
+     * @param request
+     * @param response
+     * @throws IOException
+     */
+    //	回调方法
+    @RequestMapping("/callBack")
+    public String wxCallBack(HttpServletRequest request, HttpServletResponse response) throws IOException {
+        String code = request.getParameter("code");
+        //获取access_token
+        String url = "https://api.weixin.qq.com/sns/oauth2/access_token" +
+                "?appid=" + ConstantUtil.APPID +
+                "&secret=" + ConstantUtil.APPSECRET +
+                "&code=" + code +
+                "&grant_type=authorization_code";
+
+        String result = HttpClientUtil.doGet(url);
+
+        System.out.println("请求获取access_token:" + result);
+        //返回结果的json对象
+        JSONObject resultObject = JSON.parseObject(result);
+
+        //请求获取userInfo
+        String infoUrl = "https://api.weixin.qq.com/sns/userinfo" +
+                "?access_token=" + resultObject.getString("access_token") +
+                "&openid=" + resultObject.getString("openid") +
+                "&lang=zh_CN";
+
+        String resultInfo = HttpClientUtil.doGet(infoUrl);
+        JSONObject resultInfoObject = JSON.parseObject(resultInfo);
+
+        //此时已获取到userInfo,再根据业务进行处理
+        System.out.println("请求获取userInfo:" + resultInfo);
+        return resultInfoObject.toString();
+    }
+
+}

+ 7 - 0
YijiaRestful/src/main/java/com/platform/yijia/utils/ConstantUtil.java

@@ -0,0 +1,7 @@
+package com.platform.yijia.utils;
+
+public class ConstantUtil {
+
+    public  static String APPID="wxc8189d3b3a7283e0";//填你自己的
+    public  static String APPSECRET="3f18fc7e4b02de2f8a14f55b55ab6245";//填你自己的
+}

+ 139 - 0
YijiaRestful/src/main/java/com/platform/yijia/utils/HttpClientUtil.java

@@ -0,0 +1,139 @@
+package com.platform.yijia.utils;
+
+import org.apache.http.NameValuePair;
+import org.apache.http.client.entity.UrlEncodedFormEntity;
+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.client.utils.URIBuilder;
+import org.apache.http.entity.ContentType;
+import org.apache.http.entity.StringEntity;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClients;
+import org.apache.http.message.BasicNameValuePair;
+import org.apache.http.util.EntityUtils;
+
+import java.io.IOException;
+import java.net.URI;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * @Author : suxinghua
+ * @CreateTime : 2020/11/24
+ * @Description :
+ **/
+public class HttpClientUtil {
+
+    public static String doGet(String url, Map<String, String> param) {
+
+        // 创建Httpclient对象
+        CloseableHttpClient httpclient = HttpClients.createDefault();
+
+        String resultString = "";
+        CloseableHttpResponse response = null;
+        try {
+            // 创建uri
+            URIBuilder builder = new URIBuilder(url);
+            if (param != null) {
+                for (String key : param.keySet()) {
+                    builder.addParameter(key, param.get(key));
+                }
+            }
+            URI uri = builder.build();
+
+            // 创建http GET请求
+            HttpGet httpGet = new HttpGet(uri);
+
+            // 执行请求
+            response = httpclient.execute(httpGet);
+            // 判断返回状态是否为200
+            if (response.getStatusLine().getStatusCode() == 200) {
+                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
+            }
+        } catch (Exception e) {
+            e.printStackTrace();
+        } finally {
+            try {
+                if (response != null) {
+                    response.close();
+                }
+                httpclient.close();
+            } catch (IOException e) {
+                e.printStackTrace();
+            }
+        }
+        return resultString;
+    }
+
+    public static String doGet(String url) {
+        return doGet(url, null);
+    }
+
+    public static String doPost(String url, Map<String, String> param) {
+        // 创建Httpclient对象
+        CloseableHttpClient httpClient = HttpClients.createDefault();
+        CloseableHttpResponse response = null;
+        String resultString = "";
+        try {
+            // 创建Http Post请求
+            HttpPost httpPost = new HttpPost(url);
+            // 创建参数列表
+            if (param != null) {
+                List<NameValuePair> paramList = new ArrayList<>();
+                for (String key : param.keySet()) {
+                    paramList.add(new BasicNameValuePair(key, param.get(key)));
+                }
+                // 模拟表单
+                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
+                httpPost.setEntity(entity);
+            }
+            // 执行http请求
+            response = httpClient.execute(httpPost);
+            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
+        } catch (Exception e) {
+            e.printStackTrace();
+        } finally {
+            try {
+                response.close();
+            } catch (IOException e) {
+                e.printStackTrace();
+            }
+        }
+
+        return resultString;
+    }
+
+    public static String doPost(String url) {
+        return doPost(url, null);
+    }
+
+    public static String doPostJson(String url, String json) {
+        // 创建Httpclient对象
+        CloseableHttpClient httpClient = HttpClients.createDefault();
+        CloseableHttpResponse response = null;
+        String resultString = "";
+        try {
+            // 创建Http Post请求
+            HttpPost httpPost = new HttpPost(url);
+            // 创建请求内容
+            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
+            httpPost.setEntity(entity);
+            // 执行http请求
+            response = httpClient.execute(httpPost);
+            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
+        } catch (Exception e) {
+            e.printStackTrace();
+        } finally {
+            try {
+                response.close();
+            } catch (IOException e) {
+                e.printStackTrace();
+            }
+        }
+
+        return resultString;
+    }
+}
+

+ 53 - 0
YijiaRestful/src/main/java/com/platform/yijia/utils/SignUtil.java

@@ -0,0 +1,53 @@
+package com.platform.yijia.utils;
+
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.util.Arrays;
+
+/**
+ * @Author : suxinghua
+ * @CreateTime : 2020/11/24
+ * @Description :
+ **/
+public class SignUtil {
+
+    private static String token = "jiaduoduowxtest";//填你自己的
+
+
+    public static boolean checkSignature(String signature, String timestamp, String nonce) {
+        String[] paramArr = new String[] { token, timestamp, nonce };
+        Arrays.sort(paramArr);
+        String content = paramArr[0].concat(paramArr[1]).concat(paramArr[2]);
+
+        String ciphertext = null;
+        try {
+            MessageDigest md = MessageDigest.getInstance("SHA-1");
+            byte[] digest = md.digest(content.getBytes());
+            ciphertext = byteToStr(digest);
+        } catch (NoSuchAlgorithmException e) {
+            e.printStackTrace();
+        }
+
+        return ciphertext != null ? ciphertext.equals(signature.toUpperCase()) : false;
+    }
+
+
+    private static String byteToStr(byte[] byteArray) {
+        String strDigest = "";
+        for (int i = 0; i < byteArray.length; i++) {
+            strDigest += byteToHexStr(byteArray[i]);
+        }
+        return strDigest;
+    }
+
+
+    private static String byteToHexStr(byte mByte) {
+        char[] Digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
+        char[] tempArr = new char[2];
+        tempArr[0] = Digit[(mByte >>> 4) & 0X0F];
+        tempArr[1] = Digit[mByte & 0X0F];
+
+        String s = new String(tempArr);
+        return s;
+    }
+}