Browse Source

新增微校通知功能

wangzhengliang 3 years ago
parent
commit
53f7b2658e

+ 118 - 0
src/main/java/com/chuanghai/ihotel/component/WeiXiaoComponent.java

@@ -0,0 +1,118 @@
+package com.chuanghai.ihotel.component;
+
+import com.chuanghai.ihotel.common.exception.BizCodeEnume;
+import com.chuanghai.ihotel.common.exception.RRException;
+import com.chuanghai.ihotel.config.WeixiaoConfig;
+import com.chuanghai.ihotel.constant.RedisKey;
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.data.redis.core.StringRedisTemplate;
+import org.springframework.http.ResponseEntity;
+import org.springframework.stereotype.Component;
+import org.springframework.util.StringUtils;
+import org.springframework.web.client.RestTemplate;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * @Author: codingliang
+ * @Description: 微校相关组件
+ * @Date: 2022-08-23 14:19
+ * @Version: V1.0
+ **/
+@Slf4j
+@Component
+public class WeiXiaoComponent {
+
+    @Autowired
+    private WeixiaoConfig weixiaoConfig;
+    @Autowired
+    private StringRedisTemplate stringRedisTemplate;
+
+    /**
+     * 获取token
+     * @return
+     */
+    public String getApplicationToken() {
+        String token = stringRedisTemplate.opsForValue().get(RedisKey.WEI_XIAO_SERVICE_TOKEN);
+        if (StringUtils.hasText(token)) {
+            return token;
+        } else {
+            Map<String, Object> jsonMap = doGetApplicationToken();
+            String accessToken = jsonMap.get("access_token").toString();
+            String expiresIn = jsonMap.get("expires_in").toString();
+
+            stringRedisTemplate.opsForValue().set(RedisKey.WEI_XIAO_SERVICE_TOKEN, accessToken, Long.valueOf(expiresIn), TimeUnit.SECONDS);
+
+            return accessToken;
+        }
+    }
+
+    /**
+     * 发送通知
+     * @param cards 卡号集合
+     * @param digest 摘要
+     * @param title 通知标题
+     * @param content 通知内容
+     * @param customs 自定义参数,长度为2,分别为提示文案和通知跳转链接
+     */
+    public void sendNotice(List<String> cards, String digest, String title, String content, List<String> customs) {
+        String uri = "https://open.wecard.qq.com/cgi-bin/notice/send?access_token=" + getApplicationToken();
+        Map<String, String> params = new HashMap<>();
+
+        try {
+            ObjectMapper mapper = new ObjectMapper();
+            params.put("cards", mapper.writeValueAsString(cards));
+            params.put("title", title);
+            params.put("content", content);
+            params.put("sender", "智慧公寓");
+            params.put("digest", digest);
+            if (customs != null && customs.size() == 2) {
+                params.put("customs", mapper.writeValueAsString(customs));
+            }
+
+            RestTemplate client = new RestTemplate();
+            ResponseEntity<String> tokenResponse = client.postForEntity(uri, params, String.class);
+            String body = tokenResponse.getBody();
+            log.info("微校发送通知返回结果【{}】", body);
+        } catch (Exception e) {
+            log.error("微校发送通知错误【{}】", e.getMessage());
+        }
+    }
+
+    /**
+     * 获取token
+     * @return
+     */
+    private Map<String, Object> doGetApplicationToken() {
+        String uri = "https://open.wecard.qq.com/cgi-bin/oauth2/token";
+
+        // 构建请求参数
+        Map<String, String> tokenParams = new HashMap<>();
+        tokenParams.put("app_key", weixiaoConfig.getAppKey());
+        tokenParams.put("app_secret", weixiaoConfig.getAppSecret());
+        tokenParams.put("grant_type", "client_credentials");
+        tokenParams.put("scope", "base");
+        tokenParams.put("ocode", weixiaoConfig.getOcode());
+
+        try {
+            RestTemplate client = new RestTemplate();
+            ResponseEntity<String> tokenResponse = client.postForEntity(uri, tokenParams, String.class);
+            String body = tokenResponse.getBody();
+            log.info("微校请求token返回结果【{}】", body);
+            ObjectMapper mapper = new ObjectMapper();
+            Map<String, Object> jsonMap = mapper.readValue(body, new TypeReference<Map<String, Object>>() {});
+
+
+            return jsonMap;
+        } catch (Exception e) {
+            log.error("微校请求token【{}】", e.getMessage());
+            throw new RRException(BizCodeEnume.THIRD_PARTY_SERVICE_CALL_FAILED, "微校请求token异常");
+        }
+    }
+}

+ 1 - 0
src/main/java/com/chuanghai/ihotel/config/WeixiaoConfig.java

@@ -17,4 +17,5 @@ public class WeixiaoConfig {
 
     private String appKey;
     private String appSecret;
+    private String ocode;
 }

+ 7 - 0
src/main/java/com/chuanghai/ihotel/constant/RedisKey.java

@@ -18,5 +18,12 @@ public class RedisKey {
      * 锁定房源
      */
     public static final String LOCK_ROOM_BY_ROOM_TYPE = "lock:room:roomType:%s";
+    /**
+     * 水电服务token
+     */
     public static final String WATER_AND_ELECTRIC_SERVICE_TOKEN = "cache:water-electric-token";
+    /**
+     * 微校token
+     */
+    public static final String WEI_XIAO_SERVICE_TOKEN = "cache:weixiao";
 }

+ 10 - 1
src/main/java/com/chuanghai/ihotel/controller/TestController.java

@@ -2,6 +2,7 @@ package com.chuanghai.ihotel.controller;
 
 import com.chuanghai.ihotel.component.DoorLockComponent;
 import com.chuanghai.ihotel.component.WaterElectricComponent;
+import com.chuanghai.ihotel.component.WeiXiaoComponent;
 import com.chuanghai.ihotel.dto.DoorLockAddPasswordRequestDTO;
 import com.chuanghai.ihotel.service.HotelOrderService;
 import org.springframework.beans.factory.annotation.Autowired;
@@ -11,6 +12,7 @@ import org.springframework.web.bind.annotation.RestController;
 
 import java.time.LocalDateTime;
 import java.time.ZoneOffset;
+import java.util.Arrays;
 
 /**
  * 测试接口
@@ -30,6 +32,8 @@ public class TestController {
     DoorLockComponent doorLockComponent;
     @Autowired
     private HotelOrderService orderService;
+    @Autowired
+    private WeiXiaoComponent weiXiaoComponent;
 
     @GetMapping("test1")
     public void test1() {
@@ -74,7 +78,12 @@ public class TestController {
     }
 
     @GetMapping("test7")
-    private void test7(Long orderId, String realAmount) {
+    public void test7(Long orderId, String realAmount) {
         orderService.orderPaySuccess(orderId, null, realAmount, null);
     }
+
+    @GetMapping("test8")
+    public void test8() {
+        weiXiaoComponent.sendNotice(Arrays.asList("123456"), "公寓预定成功通知", "公寓预定成功", "你好,你的公寓预定成功,你好,你的公寓预定成功,你好,你的公寓预定成功,你好,你的公寓预定成功。", null);
+    }
 }

+ 8 - 0
src/main/java/com/chuanghai/ihotel/entity/HotelUserEntity.java

@@ -36,6 +36,14 @@ public class HotelUserEntity implements Serializable {
 	 */
 	private String name;
 	/**
+	 * 手机号码
+	 */
+	private String telPhone;
+	/**
+	 * 头像
+	 */
+	private String headImage;
+	/**
 	 * 身份类型 0其他、1学生、4教职工、5校友
 	 */
 	private String identityType;

+ 13 - 3
src/main/java/com/chuanghai/ihotel/service/impl/HotelUserServiceImpl.java

@@ -65,16 +65,18 @@ public class HotelUserServiceImpl extends ServiceImpl<HotelUserDao, HotelUserEnt
             userInfoParam.put("access_token", accessToken);
             ResponseEntity<String> userInfoResponse = client.postForEntity(userInfoUrl, userInfoParam, String.class);
             String userInfoResponseBody = userInfoResponse.getBody();
-            log.info("微校token换用户信息返回结果【{}】", body);
+            log.info("微校token换用户信息返回结果【{}】", userInfoResponseBody);
 
             // 解析用户信息
             Map<String, Object> userInfoMap = mapper.readValue(userInfoResponseBody, new TypeReference<Map<String, Object>>() {});
             String cardNumber = userInfoMap.get("card_number").toString();
             String name = userInfoMap.get("name").toString();
             String identityType = userInfoMap.get("identity_type").toString();
+            String telephone = userInfoMap.get("telephone").toString();
+            String headImage = userInfoMap.get("head_image").toString();
 
             // 用户信息生成token返回
-            return generateToken(cardNumber, name, identityType);
+            return generateToken(cardNumber, name, identityType, telephone, headImage);
         } catch (Exception e) {
             log.error("微校授权失败【{}】", e.getMessage());
             return null;
@@ -86,9 +88,11 @@ public class HotelUserServiceImpl extends ServiceImpl<HotelUserDao, HotelUserEnt
      * @param cardNumber
      * @param name
      * @param identityType
+     * @param telephone
+     * @param headImage
      * @return
      */
-    private LoginUserVO generateToken(String cardNumber, String name, String identityType) {
+    private LoginUserVO generateToken(String cardNumber, String name, String identityType, String telephone, String headImage) {
         HotelUserEntity hotelUser = findByCardNumber(cardNumber);
         if (hotelUser == null) {
             hotelUser = new HotelUserEntity();
@@ -96,11 +100,15 @@ public class HotelUserServiceImpl extends ServiceImpl<HotelUserDao, HotelUserEnt
             hotelUser.setCardNumber(cardNumber);
             hotelUser.setIdentityType(identityType);
             hotelUser.setStatu("1");
+            hotelUser.setTelPhone(telephone);
+            hotelUser.setHeadImage(headImage);
 
             this.save(hotelUser);
         } else {
             hotelUser.setName(name);
             hotelUser.setIdentityType(identityType);
+            hotelUser.setTelPhone(telephone);
+            hotelUser.setHeadImage(headImage);
 
             this.updateById(hotelUser);
         }
@@ -116,6 +124,8 @@ public class HotelUserServiceImpl extends ServiceImpl<HotelUserDao, HotelUserEnt
                 .userType("2")
                 .userName(name)
                 .userIdentity(identityType)
+                .telPhone(telephone)
+                .headImage(headImage)
                 .build();
     }
 }

+ 8 - 0
src/main/java/com/chuanghai/ihotel/vo/LoginUserVO.java

@@ -26,6 +26,14 @@ public class LoginUserVO {
      */
     private String userIdentity;
     /**
+     * 手机号码
+     */
+    private String telPhone;
+    /**
+     * 头像
+     */
+    private String headImage;
+    /**
      * 用户token
      */
     private String token;

+ 2 - 1
src/main/resources/application.yml

@@ -100,4 +100,5 @@ door-lock:
 # 微校相关配置
 weixiao:
   app-key: 4FD5599032819781
-  app-secret: 0174DFB98063A612526C6B69F941E14A
+  app-secret: 0174DFB98063A612526C6B69F941E14A
+  ocode: 1015730314

+ 2 - 0
src/main/resources/mapper/ihotel/HotelUserDao.xml

@@ -9,6 +9,8 @@
         <result property="cardNumber" column="card_number"/>
         <result property="name" column="name"/>
         <result property="identityType" column="identity_type"/>
+        <result property="telPhone" column="tel_phone"/>
+        <result property="headImage" column="head_image"/>
         <result property="statu" column="statu"/>
     </resultMap>
 </mapper>