张延森 4 years ago
parent
commit
ad6ded2500

+ 6
- 1
pom.xml View File

@@ -9,7 +9,7 @@
9 9
 		<relativePath/> <!-- lookup parent from repository -->
10 10
 	</parent>
11 11
 	<groupId>com.shigongli</groupId>
12
-	<artifactId>serivce</artifactId>
12
+	<artifactId>shigongli</artifactId>
13 13
 	<version>0.0.1</version>
14 14
 	<name>shigongli</name>
15 15
 	<description>ShiGongli Service</description>
@@ -109,6 +109,11 @@
109 109
 			<version>3.8.0</version>
110 110
 		</dependency>
111 111
 		<!--weixin-miniapp start-->
112
+		<dependency>
113
+			<groupId>com.github.binarywang</groupId>
114
+			<artifactId>weixin-java-mp</artifactId>
115
+			<version>3.8.0</version>
116
+		</dependency>
112 117
 
113 118
 		<!--lombok start-->
114 119
 		<dependency>

+ 27
- 12
src/main/java/com/shigongli/common/WxUtils.java View File

@@ -4,31 +4,46 @@ import cn.binarywang.wx.miniapp.api.WxMaService;
4 4
 import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
5 5
 import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
6 6
 import com.shigongli.config.WeixinConfig;
7
+import lombok.Data;
8
+import lombok.Getter;
9
+import me.chanjar.weixin.mp.api.WxMpService;
10
+import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
11
+import me.chanjar.weixin.mp.config.impl.WxMpDefaultConfigImpl;
7 12
 import org.springframework.beans.factory.annotation.Autowired;
8 13
 import org.springframework.stereotype.Component;
9 14
 
15
+@Getter
10 16
 @Component
11 17
 public class WxUtils {
12
-    private static WxMaService service;
18
+    private WxMaService maService;
19
+    private WxMpService mpService;
13 20
 
14 21
     @Autowired
15 22
     public WxUtils(WeixinConfig config) {
16
-        setService(config);
23
+        initMaService(config);
24
+        initMpService(config);
17 25
     }
18 26
 
19
-    private void setService(WeixinConfig config) {
27
+    private void initMaService(WeixinConfig config) {
20 28
         WxMaDefaultConfigImpl conf = new WxMaDefaultConfigImpl();
21
-        conf.setAppid(config.getMiniapp().getAppid());
22
-        conf.setSecret(config.getMiniapp().getSecret());
23
-        conf.setToken(config.getMiniapp().getToken());
24
-        conf.setAesKey(config.getMiniapp().getAesKey());
25
-        conf.setMsgDataFormat(config.getMiniapp().getMsgDataFormat());
29
+        conf.setAppid(config.getMa().getAppid());
30
+        conf.setSecret(config.getMa().getSecret());
31
+        conf.setToken(config.getMa().getToken());
32
+        conf.setAesKey(config.getMa().getAesKey());
33
+        conf.setMsgDataFormat(config.getMa().getMsgDataFormat());
26 34
 
27
-        WxMaService service = new WxMaServiceImpl();
28
-        service.setWxMaConfig(conf);
35
+        maService = new WxMaServiceImpl();
36
+        maService.setWxMaConfig(conf);
29 37
     }
30 38
 
31
-    public WxMaService getService() {
32
-        return service;
39
+    private void initMpService(WeixinConfig config) {
40
+        WxMpDefaultConfigImpl conf = new WxMpDefaultConfigImpl();
41
+        conf.setAppId(config.getMp().getAppid());
42
+        conf.setSecret(config.getMp().getSecret());
43
+        conf.setToken(config.getMp().getToken());
44
+        conf.setAesKey(config.getMp().getAesKey());
45
+
46
+        mpService = new WxMpServiceImpl();
47
+        mpService.setWxMpConfigStorage(conf);
33 48
     }
34 49
 }

+ 13
- 2
src/main/java/com/shigongli/config/WeixinConfig.java View File

@@ -11,14 +11,25 @@ import org.springframework.stereotype.Component;
11 11
 public class WeixinConfig {
12 12
 
13 13
     @NestedConfigurationProperty
14
-    private Miniapp miniapp = new Miniapp();
14
+    private Ma ma = new Ma();
15
+
16
+    @NestedConfigurationProperty
17
+    private Mp mp = new Mp();
15 18
 
16 19
     @Data
17
-    public static class Miniapp {
20
+    public static class Ma {
18 21
         private String appid;
19 22
         private String secret;
20 23
         private String token;
21 24
         private String aesKey;
22 25
         private String msgDataFormat;
23 26
     }
27
+
28
+    @Data
29
+    public static class Mp {
30
+        private String appid;
31
+        private String secret;
32
+        private String token;
33
+        private String aesKey;
34
+    }
24 35
 }

+ 7
- 0
src/main/java/com/shigongli/constants/StatusConstant.java View File

@@ -0,0 +1,7 @@
1
+package com.shigongli.constants;
2
+
3
+public class StatusConstant {
4
+    public final static Integer DELETE = -1;
5
+    public final static Integer READY = 0;
6
+    public final static Integer NORMAL = 1;
7
+}

+ 44
- 47
src/main/java/com/shigongli/controller/LoginController.java View File

@@ -1,69 +1,66 @@
1 1
 package com.shigongli.controller;
2 2
 
3
-import com.shigongli.common.BaseController;
4
-import com.shigongli.common.EncryptUtils;
5
-import com.shigongli.common.ResponseBean;
6
-//import com.yunzhi.niucai.entity.SysUser;
7
-//import com.yunzhi.niucai.service.ISysUserService;
8
-//import org.springframework.beans.factory.annotation.Autowired;
3
+import com.shigongli.common.*;
4
+import com.shigongli.entity.SysUser;
5
+import com.shigongli.service.ISysUserService;
6
+import me.chanjar.weixin.mp.api.WxMpService;
7
+import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
8
+import me.chanjar.weixin.mp.bean.result.WxMpUser;
9
+import org.springframework.beans.factory.annotation.Autowired;
9 10
 import com.shigongli.vo.LoginParam;
10 11
 import io.swagger.annotations.Api;
11 12
 import io.swagger.annotations.ApiOperation;
12 13
 import io.swagger.annotations.ApiParam;
13 14
 import org.springframework.web.bind.annotation.PostMapping;
14 15
 import org.springframework.web.bind.annotation.RequestBody;
16
+import org.springframework.web.bind.annotation.RequestParam;
15 17
 import org.springframework.web.bind.annotation.RestController;
16 18
 
17
-//import java.util.HashMap;
19
+import java.util.HashMap;
20
+import java.util.Map;
18 21
 
19 22
 
20 23
 @Api(tags = "登入/登出")
21 24
 @RestController
22 25
 public class LoginController extends BaseController {
23 26
 
24
-//    @Autowired
25
-//    ISysUserService iSysUserService;
27
+    @Autowired
28
+    ISysUserService iSysUserService;
26 29
 
30
+    @Autowired
31
+    WxUtils wxUtils;
32
+
33
+    /**
34
+     * 公众号登录
35
+     * @param code
36
+     * @return
37
+     * @throws Exception
38
+     */
27 39
     @PostMapping("/mp/login")
28 40
     @ApiOperation(value="登录", notes = "登录", httpMethod = "POST", response = ResponseBean.class)
29
-    public ResponseBean login(@ApiParam("登录参数") @RequestBody LoginParam loginParam) throws Exception {
30
-//        if (null == loginParam) {
31
-//            return ResponseBean.error("账户或密码不能为空", ResponseBean.ERROR_ILLEGAL_PARAMS);
32
-//        }
33
-//
34
-//        String userName = loginParam.get("userName");
35
-//        String password = loginParam.get("password");
36
-//
37
-//        if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(password)) {
38
-//            return ResponseBean.error("账户或密码不能为空", ResponseBean.ERROR_ILLEGAL_PARAMS);
39
-//        }
40
-//
41
-//        SysUser sysUser = iSysUserService.getLoginUser(userName);
42
-//        if (null == sysUser) {
43
-//            return ResponseBean.error("账户或密码不正确", ResponseBean.ERROR_ILLEGAL_PARAMS);
44
-//        }
45
-//
46
-//        if (!checkPassword(password, sysUser.getPassword(), sysUser.getUserId().toString())) {
47
-//            return ResponseBean.error("账户或密码不正确", ResponseBean.ERROR_ILLEGAL_PARAMS);
48
-//        }
49
-//
50
-//        if (!iSysUserService.checkStatus(sysUser)) {
51
-//            return ResponseBean.error("用户状态不正确, 请联系管理人员", ResponseBean.ERROR_UNAVAILABLE);
52
-//        }
53
-//
54
-//        // 生成 token
55
-//        Map<String, Object> claims = new HashMap<String, Object>(){{
56
-//            put("userId", sysUser.getUserId());
57
-//        }};
58
-//        String jws = JWTUtils.encode(claims);
59
-//        sysUser.setPassword(null);
60
-//        sysUser.setToken(jws);
61
-//
62
-//        return ResponseBean.success(sysUser);
63
-        return ResponseBean.success("");
64
-    }
41
+    public ResponseBean login(@ApiParam("登录参数") @RequestParam("code") String code) throws Exception {
42
+        WxMpService mpService = wxUtils.getMpService();
43
+        WxMpOAuth2AccessToken wxMpOAuth2AccessToken = mpService.oauth2getAccessToken(code);
44
+        WxMpUser wxMpUser = mpService.oauth2getUserInfo(wxMpOAuth2AccessToken, null);
45
+
46
+        SysUser sysUser = iSysUserService.getByOpenId(wxMpOAuth2AccessToken.getOpenId());
47
+        if (null == sysUser) {
48
+            sysUser = new SysUser();
49
+            sysUser.setName(wxMpUser.getNickname());
50
+            sysUser.setOpenid(wxMpUser.getOpenId());
51
+            iSysUserService.save(sysUser);
52
+        }
53
+
54
+        if (StringUtils.isEmpty(sysUser.getPhone())) {
55
+            return ResponseBean.error("请先联系管理员进行授权操作", ResponseBean.ERROR_ILLEGAL_PARAMS);
56
+        }
57
+
58
+        // 生成 token
59
+        Map<String, Object> claims = new HashMap<>();
60
+        claims.put("userId", sysUser.getUserId());
61
+        String jws = JWTUtils.encode(claims);
62
+        sysUser.setToken(jws);
65 63
 
66
-    private boolean checkPassword(String src, String targ, String salt) {
67
-        return EncryptUtils.md5(src, salt).equals(targ);
64
+        return ResponseBean.success(sysUser);
68 65
     }
69 66
 }

+ 81
- 0
src/main/java/com/shigongli/controller/WxPortalController.java View File

@@ -0,0 +1,81 @@
1
+package com.shigongli.controller;
2
+
3
+import com.shigongli.common.BaseController;
4
+import com.shigongli.common.WxUtils;
5
+import lombok.extern.slf4j.Slf4j;
6
+import me.chanjar.weixin.common.api.WxConsts;
7
+import me.chanjar.weixin.mp.api.WxMpService;
8
+import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
9
+import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
10
+import org.springframework.beans.factory.annotation.Autowired;
11
+import org.springframework.web.bind.annotation.*;
12
+
13
+@Slf4j
14
+@RestController
15
+@RequestMapping("/mp/portal/{appid}")
16
+public class WxPortalController extends BaseController {
17
+
18
+    @Autowired
19
+    WxUtils wxUtils;
20
+
21
+    /**
22
+     * 微信公众号接入
23
+     * @param appid
24
+     * @param signature
25
+     * @param timestamp
26
+     * @param nonce
27
+     * @param echostr
28
+     * @return
29
+     */
30
+    @GetMapping(produces = "text/plain;charset=utf-8")
31
+    public String authGet(@PathVariable String appid,
32
+                          @RequestParam(name = "signature", required = false) String signature,
33
+                          @RequestParam(name = "timestamp", required = false) String timestamp,
34
+                          @RequestParam(name = "nonce", required = false) String nonce,
35
+                          @RequestParam(name = "echostr", required = false) String echostr) {
36
+        return echostr;
37
+    }
38
+
39
+    @PostMapping(produces = "application/xml; charset=UTF-8")
40
+    public String post(@PathVariable String appid,
41
+                       @RequestBody String requestBody,
42
+                       @RequestParam("signature") String signature,
43
+                       @RequestParam("timestamp") String timestamp,
44
+                       @RequestParam("nonce") String nonce,
45
+                       @RequestParam("openid") String openid,
46
+                       @RequestParam(name = "encrypt_type", required = false) String encType,
47
+                       @RequestParam(name = "msg_signature", required = false) String msgSignature) {
48
+
49
+        log.info("\n接收微信请求:[openid=[{}], [signature=[{}], encType=[{}], msgSignature=[{}],"
50
+                        + " timestamp=[{}], nonce=[{}], requestBody=[\n{}\n] ",
51
+                openid, signature, encType, msgSignature, timestamp, nonce, requestBody);
52
+
53
+        WxMpService mpService = wxUtils.getMpService().switchoverTo(appid);
54
+        if (null == mpService) {
55
+            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置,请核实!", appid));
56
+        }
57
+
58
+        if (!mpService.checkSignature(timestamp, nonce, signature)) {
59
+            throw new IllegalArgumentException("非法请求,可能属于伪造的请求!");
60
+        }
61
+
62
+        WxMpXmlMessage inMessage = null;
63
+        WxMpXmlOutMessage outMessage = null;
64
+        if (encType == null) {
65
+            // 明文传输的消息
66
+            inMessage = WxMpXmlMessage.fromXml(requestBody);
67
+        } else if ("aes".equalsIgnoreCase(encType)) {
68
+            // aes加密的消息
69
+            inMessage = WxMpXmlMessage.fromEncryptedXml(requestBody, mpService.getWxMpConfigStorage(),
70
+                    timestamp, nonce, msgSignature);
71
+            log.debug("\n消息解密后内容为:\n{} ", inMessage.toString());
72
+        }
73
+
74
+        // 关注公众号
75
+        if (inMessage.getMsgType().equals(WxConsts.XmlMsgType.EVENT) && inMessage.getEvent().equals(WxConsts.EventType.SUBSCRIBE)) {
76
+            // todo
77
+        }
78
+
79
+        return "";
80
+    }
81
+}

+ 5
- 2
src/main/java/com/shigongli/entity/SysUser.java View File

@@ -2,6 +2,8 @@ package com.shigongli.entity;
2 2
 
3 3
 import com.baomidou.mybatisplus.annotation.IdType;
4 4
 import java.time.LocalDateTime;
5
+
6
+import com.baomidou.mybatisplus.annotation.TableField;
5 7
 import com.baomidou.mybatisplus.annotation.TableId;
6 8
 import java.io.Serializable;
7 9
 import io.swagger.annotations.ApiModel;
@@ -27,7 +29,7 @@ public class SysUser implements Serializable {
27 29
     private static final long serialVersionUID = 1L;
28 30
 
29 31
     @ApiModelProperty(value = "系统ID")
30
-    @TableId(value = "user_id", type = IdType.INPUT)
32
+    @TableId(value = "user_id", type = IdType.UUID)
31 33
     private String userId;
32 34
 
33 35
     @ApiModelProperty(value = "用户名")
@@ -45,5 +47,6 @@ public class SysUser implements Serializable {
45 47
     @ApiModelProperty(value = "创建时间")
46 48
     private LocalDateTime createDate;
47 49
 
48
-
50
+    @TableField(exist = false)
51
+    private String token;
49 52
 }

+ 3
- 0
src/main/java/com/shigongli/service/ISysUserService.java View File

@@ -13,4 +13,7 @@ import com.baomidou.mybatisplus.extension.service.IService;
13 13
  */
14 14
 public interface ISysUserService extends IService<SysUser> {
15 15
 
16
+    SysUser getByOpenId(String openId);
17
+
18
+    SysUser getByPhone(String phone);
16 19
 }

+ 19
- 0
src/main/java/com/shigongli/service/impl/SysUserServiceImpl.java View File

@@ -1,5 +1,7 @@
1 1
 package com.shigongli.service.impl;
2 2
 
3
+import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
4
+import com.shigongli.constants.StatusConstant;
3 5
 import com.shigongli.entity.SysUser;
4 6
 import com.shigongli.mapper.SysUserMapper;
5 7
 import com.shigongli.service.ISysUserService;
@@ -17,4 +19,21 @@ import org.springframework.stereotype.Service;
17 19
 @Service
18 20
 public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {
19 21
 
22
+    @Override
23
+    public SysUser getByOpenId(String openId) {
24
+        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<SysUser>()
25
+                .eq("openid", openId)
26
+                .eq("status", StatusConstant.NORMAL)
27
+                .last("limit 1");
28
+        return getOne(queryWrapper);
29
+    }
30
+
31
+    @Override
32
+    public SysUser getByPhone(String phone) {
33
+        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<SysUser>()
34
+                .eq("phone", phone)
35
+                .eq("status", StatusConstant.NORMAL)
36
+                .last("limit 1");
37
+        return getOne(queryWrapper);
38
+    }
20 39
 }

+ 18
- 10
src/main/resources/application.yml View File

@@ -1,6 +1,6 @@
1 1
 ###
2 2
 server:
3
-  port: 8080
3
+  port: 8091
4 4
   servlet:
5 5
     context-path: /api
6 6
 
@@ -10,8 +10,8 @@ interceptor:
10 10
     enable: true
11 11
     include-paths: /**
12 12
     exclude-paths:
13
-      - /login
14
-      - /logout
13
+      - /mp/login
14
+      - /ma/login
15 15
       - /swagger-ui/**
16 16
       - /swagger-resources/**
17 17
       - /v2/**
@@ -25,12 +25,12 @@ mybatis-plus:
25 25
 
26 26
 ###
27 27
 aliyun:
28
-  accessKeyId: LTAI4FdMQNh1xUoiqqbKJ15J
29
-  accessKeySecret: F7vmuXBu8IrhouQYYhFMLRhIRivIzb
28
+  accessKeyId: LTAIGQtIi28MfXms
29
+  accessKeySecret: b6maakcdzEywmkhcK15rStx54hOiIA
30 30
   oss:
31 31
     endpoint: oss-cn-shanghai.aliyuncs.com
32
-    bucketName: njcj
33
-    bucketURL: https://njcj.oss-cn-shanghai.aliyuncs.com
32
+    bucketName: zhiyun-image
33
+    bucketURL: https://zhiyun-image.oss-accelerate.aliyuncs.com
34 34
   sms:
35 35
     captcha:
36 36
       code: SMS_195585471
@@ -38,12 +38,20 @@ aliyun:
38 38
 
39 39
 ###
40 40
 weixin:
41
-  miniapp:
42
-    appid: wxd6f47a9bb3052175
43
-    secret: 28f33b6bbc0f778c11a0bb234a7d6d4e
41
+  # 小程序
42
+  ma:
43
+    appid: wx06a7372d48d56843
44
+    secret: ead0c7b1dd40ce828b1fd9bf18183584
44 45
     token:
45 46
     aesKey:
46 47
     msgDataFormat: JSON
48
+  # 公众号
49
+  mp:
50
+    appid: wx74db171e5f6524ad
51
+    secret: 01257197628a0b8553d7ef54f1252a06
52
+    token: yansenisahero
53
+    aesKey: oz3KPVpLL1yWPWUKEv1JLIE23yB8wIPA9OkdhKKK0UB
54
+
47 55
 
48 56
 ###
49 57
 spring: