Explorar o código

fix: "TODO: 微信登录"

ritchie %!s(int64=2) %!d(string=hai) anos
pai
achega
79460b6b97

+ 26 - 0
src/main/java/com/szwl/config/CorsConfig.java

@@ -0,0 +1,26 @@
+package com.szwl.config;
+
+import org.springframework.web.filter.CorsFilter;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.web.cors.CorsConfiguration;
+import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
+
+@Configuration
+public class CorsConfig {
+
+    @Bean
+    public CorsFilter corsFilter() {
+        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
+        CorsConfiguration config = new CorsConfiguration();
+//        config.addAllowedOrigin("*"); // 允许所有域名访问,可以根据需求修改
+        config.addAllowedOrigin("http://localhost:8080");
+        config.addAllowedOrigin("http://szwltest.sunzee.com.cn");
+        config.addAllowedOrigin("https://open.weixin.qq.com");
+        config.addAllowedOrigin("https://api.weixin.qq.com");
+        config.addAllowedHeader("*"); // 允许所有请求头
+        config.addAllowedMethod("*"); // 允许所有请求方法
+        source.registerCorsConfiguration("/**", config);
+        return new CorsFilter(source);
+    }
+}

+ 28 - 14
src/main/java/com/szwl/controller/TWechatController.java

@@ -8,6 +8,7 @@ import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
 import com.baomidou.mybatisplus.core.toolkit.Wrappers;
 import com.sun.org.apache.regexp.internal.RE;
 import com.szwl.constant.ResponseCodesEnum;
+import com.szwl.model.bo.JsonMessage;
 import com.szwl.model.bo.R;
 //import com.szwl.model.dto.WechatDTO;
 import com.szwl.model.entity.TAdmin;
@@ -24,6 +25,7 @@ import org.apache.commons.lang.StringUtils;
 import org.apache.http.Header;
 import org.apache.http.HttpEntity;
 import org.apache.http.HttpHeaders;
+import org.apache.http.HttpResponse;
 import org.apache.http.client.methods.CloseableHttpResponse;
 import org.apache.http.client.methods.HttpGet;
 import org.apache.http.impl.client.CloseableHttpClient;
@@ -82,11 +84,14 @@ public class TWechatController {
     private String http;
 
     @ApiOperation(value = "绑定微信")
-    @CrossOrigin(value = "https://open.weixin.qq.com/")
-    @GetMapping("/bindWechat")
-    public R bindWechat(@RequestParam Long adminId) throws Exception {
+    @PostMapping("/bindWechat")
+    public Map<String, Object> bindWechat(@RequestBody Map<String, Object> params) throws Exception {
+        Long adminId = (Long) params.get("adminId");
+        Map<String, Object> result = new HashMap<>();
         if (adminId==null) {
-            throw new MyException("参数为空");
+            result.put("code", 400);
+            result.put("msg", "参数为空");
+            return result;
         }
         TAdmin tAdmin = tAdminService.getById(adminId);
         TWechat tWechat = new TWechat();
@@ -115,23 +120,25 @@ public class TWechatController {
         }
 
         // 第一步:用户同意授权,获取code
-        String url = "https://szwltest.sunzee.com.cn/openWeixin/connect/oauth2/authorize?"
+        String url = "http://szwltest.sunzee.com.cn/openWeixin/connect/oauth2/authorize?"
 //        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?"
                 + "appid=" + appid
                 + "&redirect_uri=" + path
                 + "&response_type=code"
                 + "&scope=snsapi_userinfo"
-                + "&state=" + adminId +
-                "#wechat_redirect";
+                + "&state=" + adminId
+                + "#wechat_redirect";
 //        response.sendRedirect(url);
-        return R.ok(url);
+        result.put("code", 200);
+        result.put("msg", "success");
+        result.put("data", url);
+        return result;
     }
 
 
-    // 绑定微信回调
+    @ApiOperation(value = "绑定微信回调")
     @GetMapping("/callback")
-    @CrossOrigin(value = "https://api.weixin.qq.com/")
-    public JSONObject oauthCallback(HttpServletRequest request) throws IOException {
+    public void oauthCallback(HttpServletRequest request, HttpServletResponse response) throws IOException {
         // 获取code
         String code = request.getParameter("code");
         String adminId = request.getParameter("state");
@@ -158,7 +165,8 @@ public class TWechatController {
         TWechat tWechat = tWechatService.getOne(wrapper);
 
         if (Objects.isNull(tWechat)) {
-            return null;
+            response.sendError(HttpServletResponse.SC_NOT_FOUND, "tWechat is null"); // 返回错误状态码和错误信息给前端
+            return;
         }
         String openId = tWechat.getOpenId();
 
@@ -175,8 +183,14 @@ public class TWechatController {
             tWechat.setCreateDate(new Date());
             tWechatService.updateById(tWechat);
         }
-
-        return userInfo;
+        Map<String, Object> result = new HashMap<>();
+        result.put("code", 200);
+        result.put("msg", "success");
+        // 跳转到用户页面
+        String userPageUrl = "http://szwltest.sunzee.com.cn/shenze/#/user";
+        result.put("data", userPageUrl);
+        response.setContentType("application/json;charset=UTF-8");
+        response.getWriter().write(JSON.toJSONString(result));
     }
 
 

+ 65 - 155
src/main/java/com/szwl/controller/WxLoginController.java

@@ -1,5 +1,6 @@
 package com.szwl.controller;
 
+import com.rabbitmq.http.client.domain.UserInfo;
 import com.szwl.model.bo.R;
 import com.szwl.model.bo.ResponseModel;
 import com.szwl.model.bo.UserDetailBO;
@@ -26,6 +27,7 @@ import java.util.*;
 @Api(value = "/WxLoginController", tags = {"微信登录接口"})
 @RestController
 @RequestMapping("/wxLogin")
+@CrossOrigin(origins = {"http://szwltest.sunzee.com.cn", "https://szwl.sunzee.com.cn", "https://sz.sunzee.com.cn"}) // 允许来自 http://xxx 的跨域请求
 public class WxLoginController {
 
     @Autowired
@@ -44,177 +46,85 @@ public class WxLoginController {
     @Value("${oauth.callback.http}")
     private String http;
 
-    @ApiOperation(value = "用户默认授权")
-    @CrossOrigin(value = "https://open.weixin.qq.com/")
+    @ApiOperation(value = "用户默认授权,获取code")
     @GetMapping("/menuOauth")
-    public R menuOauth(HttpServletResponse response) throws IOException {
-        String path = http + "/SZWL-SERVER/wxLogin/callback?";
-//        String path = http + "/wxLogin/callback?";
-
+    public R<String> getOpenid() {
+        String path = http + "/shenze/#/home";
         try {
-            path = URLEncoder.encode(path, "UTF-8");
+            String redirectUrl = URLEncoder.encode(path, "UTF-8");
+            // 第一步:用户静默授权,获取code
+            String authUrl = "http://szwltest.sunzee.com.cn/openWeixin/connect/oauth2/authorize?"
+//            String authUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?"
+                    + "appid=" + appid
+                    + "&redirect_uri=" + redirectUrl
+                    + "&response_type=code"
+                    + "&scope=snsapi_base"
+                    + "&state=STATE"
+                    + "#wechat_redirect";
+            return R.ok(authUrl);
         } catch (UnsupportedEncodingException e) {
-            throw new RuntimeException(e);
+            return R.fail("微信授权失败");
         }
-        // 第一步:用户同意授权,获取code
-        // 静默授权,只能获取用户openid
-        String url = "https://szwltest.sunzee.com.cn/openWeixin/connect/oauth2/authorize?"
-//        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?"
-                + "appid=" + appid
-                + "&redirect_uri=" + path
-                + "&response_type=code"
-                + "&scope=snsapi_base"
-                + "&state=STATE" +
-                "#wechat_redirect";
-        return R.ok(url);
-//        response.sendRedirect(url);
     }
 
-    @ApiOperation(value = "微信登录回调")
-    @CrossOrigin(value = "https://api.weixin.qq.com/")
+    @ApiOperation(value = "微信授权回调,返回openid")
     @GetMapping("/callback")
-    public void callback(HttpServletRequest request) throws IOException {
-        // code 只能用一次,5分钟过期
+    public void callback(HttpServletRequest request, HttpServletResponse response) throws IOException {
+        // 第二步:使用code换取access_token和openid
         String code = request.getParameter("code");
+        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?"
+                + "appid=" + appid
+                + "&secret=" + appsecret
+                + "&code=" + code
+                + "&grant_type=authorization_code";
 
-        // 第二步:通过code换取网页授权access_token
-        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?" +
-                "appid=" + appid +
-                "&secret=" + appsecret +
-                "&code=" + code +
-                "&grant_type=authorization_code";
         JSONObject jsonObject = HttpClientUtils.get(url);
 
         String openid = jsonObject.getString("openid");
-        String accessToken = jsonObject.getString("access_token");
-
-        // snsapi_base式的网页授权流程即到此为止。
-        // 根据 openid 去查找已绑定的用户信息
-        TWechat tWechat = tWechatService.getById(openid);
-        if (Objects.nonNull(tWechat)) {
-            String adminId = tWechat.getAdminId();
-            TAdmin tAdmin = tAdminService.getById(adminId);
-            String username = tAdmin.getUsername();
-            String password = tAdmin.getPassword();
-            // 然后根据 username 和 password 去登录
-            TAdminController tAdminController = new TAdminController();
-            ResponseModel<UserDetailBO> login = tAdminController.login(username, password);
-
-        } else {
-            // 说明未绑定
-
-        }
 
+        // 返回openid给前端
+        response.setContentType("application/json");
+        response.setCharacterEncoding("UTF-8");
+        response.getWriter().write("{\"openid\":\"" + openid + "\"}");
     }
 
-
-    /**
-     * 前往微信开发平台申请,根据 code 获取 openid
-     * @param code
-     * @return
-     * @throws IOException
-     */
-    @CrossOrigin(value = "https://api.weixin.qq.com/")
-    private String getOpenidByCode(String code) throws IOException {
-
-        String grantType = "authorization_code";
-
-        // 拼接请求地址
-        String requestUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?" +
-                "appid=" + appid +
-                "&secret=" + appsecret +
-                "&code=" + code +
-                "&grant_type=" + grantType;
-
-        JSONObject jsonObject = HttpClientUtils.get(requestUrl);
-        String accessToken = jsonObject.getString("access_token");
-        String openId = jsonObject.getString("openid");
-
-        // 拉取用户信息(需scope为 snsapi_userinfo)
-//        String userinfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + accessToken + "&openid=" + openId + "&lang=zh_CN";
-//        JSONObject object = HttpClientUtils.get(userinfoUrl);
-
-
-//        String s = JSON.toJSONString(object);
-        return openId;
-    }
-
-    @ApiOperation(value = "获取微信签名")
-    @GetMapping("/wx/signature")
-    public Map<String, String> getSignature(@RequestParam String url) throws IOException {
-        HashMap<String, String> signatureMap = new HashMap<>();
-
-        String nonceStr = UUID.randomUUID().toString();
-        String timestamp = Long.toString(System.currentTimeMillis() / 1000);
-        String jsapiTicket = getJsapiTicket();
-        String signature = "";
-
-        // 按照微信官方要求构造含有 nonceStr、timestamp、jsapi_ticket 和 url 的字符串
-        String rawString = "jsapi_ticket=" + jsapiTicket +
-                "&noncestr=" + nonceStr +
-                "&timestamp=" + timestamp +
-                "&url=" + url;
-
-        try {
-            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
-            crypt.reset();
-            crypt.update(rawString.getBytes("UTF-8"));
-            signature = byteToHex(crypt.digest());
-        } catch (Exception e) {
-            e.printStackTrace();
-        }
-
-        signatureMap.put("signature", signature);
-        signatureMap.put("appId", appid);
-        signatureMap.put("timestamp", timestamp);
-        signatureMap.put("nonceStr", nonceStr);
-
-        return signatureMap;
-    }
-
-    /**
-     * 获取授权页ticket ticket 有效期,一般为 7200 秒
-     * @return
-     * @throws IOException
-     */
-    @CrossOrigin(value = "https://api.weixin.qq.com/")
-    private String getJsapiTicket() throws IOException {
-        // 获取 jsapi_ticket 的逻辑,向微信服务器发送 GET 请求
-        String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket"
-                + "?access_token=" + getAccessToken()  // 先获取 access_token
-                + "&type=jsapi";  // 指定获取 jsapi_ticket
-
-        JSONObject jsonObject = HttpClientUtils.get(url);
-        String ticket = jsonObject.getString("ticket");
-        // 返回获取到的 jsapi_ticket
-        return ticket;
-    }
-
-    /**
-     * 获取接口调用凭据 token 有效期: 7200s
-     * @return
-     * @throws IOException
-     */
-    @CrossOrigin(value = "https://api.weixin.qq.com/")
-    private String getAccessToken() throws IOException {
-        // 构造 GET 请求,获取 access_token
-        String url = "https://api.weixin.qq.com/cgi-bin/token"
-                + "?grant_type=client_credential"
-                + "&appid=" + appid
-                + "&secret=" + appsecret;
-
-        JSONObject jsonObject = HttpClientUtils.get(url);
-        return jsonObject.getString("access_token");
-    }
-
-    private static String byteToHex(final byte[] hash) {
-        Formatter formatter = new Formatter();
-        for (byte b : hash) {
-            formatter.format("%02x", b);
+    @ApiOperation(value = "微信登录")
+    @GetMapping("/wxLogin")
+    public R<String> wxLogin(@RequestParam("openid") String openid) {
+        // 根据openid获取用户信息
+        TWechat tWechat = tWechatService.lambdaQuery().eq(TWechat::getOpenId, openid).one();
+        if (tWechat != null) {
+            String adminId = tWechat.getAdminId();
+            if (adminId != null) {
+                // 根据adminId获取用户名和密码
+                TAdmin tAdmin = tAdminService.getById(adminId);
+                if (tAdmin != null) {
+                    String username = tAdmin.getUsername();
+                    String password = tAdmin.getPassword();
+                    // 调用已有的登录接口实现登录,使用用户名和密码
+                    TAdminController tAdminController = new TAdminController();
+                    ResponseModel<UserDetailBO> loginResult = tAdminController.login(username, password);
+                    if (loginResult.getCode().equals("00000")) {
+                        // 登录成功
+                        // 解析重定向url参数,并重定向到home页面
+                        String redirectUrl = "http://szwltest.sunzee.com.cn/shenze/#/home";
+                        return R.ok(redirectUrl);
+                    } else {
+                        // 登录失败
+                        return R.fail("登录失败");
+                    }
+                } else {
+                    // 用户信息不存在
+                    return R.fail("用户信息不存在");
+                }
+            } else {
+                // 当前账户未绑定微信
+                return R.fail("当前账户未绑定微信");
+            }
+        } else {
+            // 获取用户信息失败
+            return R.fail("获取用户信息失败");
         }
-        String result = formatter.toString();
-        formatter.close();
-        return result;
     }
 
 }

+ 0 - 1
src/main/resources/MP_verify_zthjeKsyPpYA7KME.txt

@@ -1 +0,0 @@
-zthjeKsyPpYA7KME

+ 3 - 3
src/main/resources/bootstrap.yml

@@ -36,7 +36,7 @@ oauth:
 #    个人测试
 #    http: http://d.freehk.svipss.top
 #    系统测试
-    http: http://szwltest.sunzee.com.cn:49002
+    http: http://szwltest.sunzee.com.cn
 #    正式服务
 #    http: https://szwlh.sunzee.com.cn
 
@@ -72,9 +72,9 @@ eureka:
   client:
     serviceUrl:
       defaultZone: http://120.25.151.99:49001/eureka/
-    register-with-eureka: true
+#    register-with-eureka: true
 #    本地测试的时候改成 false
-#    register-with-eureka: false
+    register-with-eureka: false
 #  instance:
 #    prefer-ip-address: true
 #    ip-address: 112.96.106.247