Bläddra i källkod

fixed: 多设备绑定/小程序跳转问题.

orgycat 3 år sedan
förälder
incheckning
7f6519ad4c

+ 64 - 6
src/main/java/com/care/client/controller/WxMsgController.java

@@ -130,9 +130,67 @@ public class WxMsgController {
             String eventType = ObjectUtils.toString(map.get("Event"));//事件类型
 //            String nickName = getUserNickName(fromUserName);
             if(MessageUtil.MSGTYPE_EVENT.equals(msgType)){//如果为事件类型
-                if(MessageUtil.SUBSCIBE_EVENT.equals(eventType)){//处理订阅事件
+                if(MessageUtil.SCAN_EVENT.equalsIgnoreCase(eventType)) {// 扫描事件
                     JSONObject parseUnionObject = WxTemplateUtil.parseWxOpenIdBySubscribe(wxAccessTokenVO.getAccessToken(), fromUserName);
-                    System.out.println("parseUnionObject:" + parseUnionObject.toString());
+                    System.out.println("scan parseUnionObject:" + parseUnionObject.toString());
+
+                    String eventKey = ObjectUtils.toString(map.get("EventKey"));
+                    Object obj = redisUtil.get(RedisKeyConstant.YUANSERVICE_QRCODE + ":" + eventKey);
+                    log.info("用户扫描: " + fromUserName + ": " + ObjectUtils.toString(map.get("EventKey")));
+                    if (obj == null) {
+                        return "failure";
+                    }
+                    String[] arrs = Objects.toString(obj).split(":");
+                    if (arrs == null || arrs.length != 2) {
+                        return "failure";
+                    }
+                    CareDevice careDevice = careDeviceService.getById(arrs[0]);
+                    if (careDevice == null) {
+                        log.info("设备不存在: " + arrs[0]);
+                        return "failure";
+                    }
+                    if (parseUnionObject != null) {
+                        HouseContactVO houseContactVO = new HouseContactVO();
+                        houseContactVO.setContactName(parseUnionObject.getStr("nickname"));
+                        houseContactVO.setCreateTime(new Date());
+                        String gender = "";
+                        if ("0".equalsIgnoreCase(parseUnionObject.getStr("sex"))) {
+                            gender = "M";
+                        } else if ("1".equalsIgnoreCase(parseUnionObject.getStr("sex"))) {
+                            gender = "W";
+                        }
+                        houseContactVO.setGender(gender);
+                        houseContactVO.setOpenId(fromUserName);
+                        houseContactVO.setMemberId(NumberUtils.toLong(arrs[1]));
+                        boolean saved = pinanbaoContactService.createOrUpdateMyContact(NumberUtils.toLong(arrs[0]), houseContactVO);
+                        if (!saved) {
+                            log.error("保存订阅用户出现错误: " + JSONUtil.toJsonStr(houseContactVO));
+                            return "failure";
+                        }
+
+                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+                        // 正式环境
+                        String templateId = "W7tT8QGmrBQNVimt6l6w55DBwSH5MBUiFgJxf3gjIV4";
+                        // 测试环境
+//                        String templateId = "gvJ1g3JOThT5IuQc1In6D2cwKwmKz9MBIkGdkXtXOTI";
+
+                        Map<String, TemplateDataDTO> data = new HashMap<>();
+                        data.put("first", new TemplateDataDTO("您已关联该监护人", "#459ae9"));
+                        data.put("keyword1", new TemplateDataDTO(careDevice.getDevName(), "#459ae9"));
+                        data.put("keyword2", new TemplateDataDTO(simpleDateFormat.format(new Date()), "#459ae9"));
+                        data.put("remark", new TemplateDataDTO("请补全您的联系信息, 便于能及时收到事件通知", "#459ae9"));
+
+                        String openId = fromUserName;
+                        log.info("生成小程序跳转URL: " + "pages/supplement/index?memberId=" + arrs[1] + "&openId=" + fromUserName);
+                        boolean flag = wxTemplateService.sendTemplateMsgOriginal(openId, templateId, "wxda02870032b8f928", "pages/supplement/index?memberId=" + arrs[1] + "&openId=" + openId, data);
+                        log.info("发送消息模板: openId: " + openId + ", templateId: " + templateId + " 状态: " + flag);
+
+                        return "success";
+                    }
+
+                } else if (MessageUtil.SUBSCIBE_EVENT.equals(eventType)) {//处理订阅事件
+                    JSONObject parseUnionObject = WxTemplateUtil.parseWxOpenIdBySubscribe(wxAccessTokenVO.getAccessToken(), fromUserName);
+                    System.out.println("subscibe parseUnionObject:" + parseUnionObject.toString());
 //                    parseUnionObject.set("unionid", "oyVYT6Ox9b88n_33lgKWRj5uFbUY");
 
                     String eventKey = ObjectUtils.toString(map.get("EventKey"));
@@ -191,7 +249,7 @@ public class WxMsgController {
                         // 正式环境
                         String templateId = "W7tT8QGmrBQNVimt6l6w55DBwSH5MBUiFgJxf3gjIV4";
                         // 测试环境
-//                    String templateId = "gvJ1g3JOThT5IuQc1In6D2cwKwmKz9MBIkGdkXtXOTI";
+//                        String templateId = "gvJ1g3JOThT5IuQc1In6D2cwKwmKz9MBIkGdkXtXOTI";
 
                         Map<String, TemplateDataDTO> data = new HashMap<>();
                         data.put("first", new TemplateDataDTO("您已关联该监护人", "#459ae9"));
@@ -200,8 +258,8 @@ public class WxMsgController {
                         data.put("remark", new TemplateDataDTO("请补全您的联系信息, 便于能及时收到事件通知", "#459ae9"));
 
                         String openId = fromUserName;
-                        log.info("生成小程序跳转URL: " + "/pages/supplement/index?memberId=" + arrs[1] + "&openId=" + fromUserName);
-                        boolean flag = wxTemplateService.sendTemplateMsgOriginal(openId, templateId, "wxda02870032b8f928", "/pages/supplement/index?memberId=" + arrs[1] + "&openId=" + openId, data);
+                        log.info("生成小程序跳转URL: " + "pages/supplement/index?memberId=" + arrs[1] + "&openId=" + fromUserName);
+                        boolean flag = wxTemplateService.sendTemplateMsgOriginal(openId, templateId, "wxda02870032b8f928", "pages/supplement/index?memberId=" + arrs[1] + "&openId=" + openId, data);
                         log.info("发送消息模板: openId: " + openId + ", templateId: " + templateId + " 状态: " + flag);
 
 //                        String eventKey = ObjectUtils.toString(map.get("EventKey"));
@@ -223,7 +281,7 @@ public class WxMsgController {
 //                        data.put("remark", new TemplateDataDTO("请尽快补全您的联系信息, 便于能及时通知您", "#ff5200"));
 //
 //                        String openId = parseUnionObject.getStr("openid");
-//                        boolean flag = wxTemplateService.sendTemplateMsg(parseUnionObject.getStr("openid"), templateId, "wxda02870032b8f928", "/pages/supplement/index", data);
+//                        boolean flag = wxTemplateService.sendTemplateMsg(parseUnionObject.getStr("openid"), templateId, "wxda02870032b8f928", "pages/supplement/index", data);
 //                        log.info("发送消息模板: openId: " + openId + ", templateId: " + templateId + " 状态: " + flag);
 
 //                        careHouseContactService.save();

+ 48 - 27
src/main/java/com/care/client/service/PinanbaoContactService.java

@@ -3,6 +3,7 @@ package com.care.client.service;
 import cn.hutool.core.bean.BeanUtil;
 import cn.hutool.core.collection.CollUtil;
 import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
+import com.care.client.vo.DeviceVO;
 import com.care.client.vo.HouseContactVO;
 import com.care.common.entity.*;
 import com.care.common.enums.OrderStatusEnum;
@@ -21,6 +22,8 @@ import org.springframework.transaction.annotation.Transactional;
 import javax.annotation.Resource;
 import java.util.Date;
 import java.util.List;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReentrantLock;
 
 
 /**
@@ -41,6 +44,8 @@ public class PinanbaoContactService {
     @Resource
     private PinanbaoDeviceService pinanbaoDeviceService;
 
+    private final Lock lock = new ReentrantLock();
+
     /**
      * 查询紧急联系人
      * @param memberId
@@ -107,35 +112,51 @@ public class PinanbaoContactService {
      */
     @Transactional(rollbackFor = Exception.class)
     public Boolean createOrUpdateMyContact(Long devId, HouseContactVO vo) {
-        QueryWrapper<CareHouseContact> queryWrapper = new QueryWrapper<>();
-        queryWrapper.lambda().eq(CareHouseContact::getMemberId, vo.getMemberId()).and(wrapper->
-                wrapper.eq(StringUtils.isNotBlank(vo.getContactPhone()), CareHouseContact::getContactPhone, vo.getContactPhone())
-                    .or().eq(StringUtils.isNotBlank(vo.getOpenId()), CareHouseContact::getOpenId, vo.getOpenId()));
-        List<CareHouseContact> contactList = careHouseContactService.list(queryWrapper);
-        if (CollectionUtils.isEmpty(contactList)) {
-            //保存被监护人
-            CareHouseContact careContact = new CareHouseContact();
-            BeanUtil.copyProperties(vo,careContact);
-            careContact.setMemberId(vo.getMemberId());
-            careContact.setCreateTime(new Date());
-            boolean saved = this.careHouseContactService.save(careContact);
-            if (saved) {
-                boolean childSaved = pinanbaoDeviceService.bindHouseContact(devId, careContact.getId());
-                if (childSaved == false) {
-                    throw new BDException("该设备绑定联系人出错");
+        lock.lock();
+        try {
+            QueryWrapper<CareHouseContact> queryWrapper = new QueryWrapper<>();
+            queryWrapper.lambda().eq(CareHouseContact::getMemberId, vo.getMemberId()).and(wrapper->
+                    wrapper.eq(StringUtils.isNotBlank(vo.getContactPhone()), CareHouseContact::getContactPhone, vo.getContactPhone())
+                            .or().eq(StringUtils.isNotBlank(vo.getOpenId()), CareHouseContact::getOpenId, vo.getOpenId()));
+            List<CareHouseContact> contactList = careHouseContactService.list(queryWrapper);
+            if (CollectionUtils.isEmpty(contactList)) {
+                //保存被监护人
+                CareHouseContact careContact = new CareHouseContact();
+                BeanUtil.copyProperties(vo,careContact);
+                careContact.setMemberId(vo.getMemberId());
+                careContact.setCreateTime(new Date());
+                boolean saved = this.careHouseContactService.save(careContact);
+                if (saved) {
+                    boolean childSaved = pinanbaoDeviceService.bindHouseContact(devId, careContact.getId());
+                    if (childSaved == false) {
+                        throw new BDException("该设备绑定联系人出错");
+                    }
+                }
+                return saved;
+            } else {
+                //修改被监护人
+                CareHouseContact careContact = contactList.get(0);
+                careContact.setContactName(vo.getContactName());
+                careContact.setContactPhone(vo.getContactPhone());
+                careContact.setAddr(vo.getAddr());
+                careContact.setLatitude(vo.getLatitude());
+                careContact.setLongitude(vo.getLongitude());
+                careContact.setRelationType(vo.getRelationType());
+                boolean updated = this.careHouseContactService.updateById(careContact);
+
+                List<CareHouseContactRel> relVos = pinanbaoDeviceService.queryMyContactRelListByDeviceId(devId);
+                if (updated && (relVos == null || relVos.stream().filter(v -> careContact.getId() == v.getContactId()).count() <= 0)) {
+                    boolean childSaved = pinanbaoDeviceService.bindHouseContact(devId, careContact.getId());
+                    if (childSaved == false) {
+                        throw new BDException("修改紧急联系人, 对该设备绑定联系人出错");
+                    }
                 }
+                return updated;
             }
-            return saved;
-        } else {
-            //修改被监护人
-            CareHouseContact careContact = contactList.get(0);
-            careContact.setContactName(vo.getContactName());
-            careContact.setContactPhone(vo.getContactPhone());
-            careContact.setAddr(vo.getAddr());
-            careContact.setLatitude(vo.getLatitude());
-            careContact.setLongitude(vo.getLongitude());
-            careContact.setRelationType(vo.getRelationType());
-            return this.careHouseContactService.updateById(careContact);
+        } catch (Exception e) {
+            throw new BDException(e.getMessage());
+        } finally {
+            lock.unlock();
         }
     }
 

+ 15 - 0
src/main/java/com/care/client/service/PinanbaoDeviceService.java

@@ -193,6 +193,21 @@ public class PinanbaoDeviceService {
     }
 
 
+    /**
+     * 查询我的设备关联数据
+     * @param devId
+     * @return
+     */
+    public List<CareHouseContactRel> queryMyContactRelListByDeviceId(Long devId){
+        CareDevice careDevice = this.careDeviceService.getById(devId);
+        if(careDevice == null){
+            return Lists.newArrayList();
+        }
+        QueryWrapper<CareHouseContactRel> queryWrapper = new QueryWrapper<>();
+        queryWrapper.lambda().eq(CareHouseContactRel::getHouseId, careDevice.getHouseId());
+        return this.careHouseContactRelService.list(queryWrapper);
+    }
+
     /**
      * 查询我的设备拥有的紧急联系人列表
      * @param devId

+ 2 - 2
src/main/java/com/care/common/service/impl/WxTemplateServiceImpl.java

@@ -141,7 +141,7 @@ public class WxTemplateServiceImpl implements WxTemplateService {
         Map<String, String> miniprogramMap = Maps.newHashMap();
         if (StringUtils.isNotBlank(miniprogramAppid)) {
             miniprogramMap.put("appid", miniprogramAppid);
-            miniprogramMap.put("page", miniprogramPage);
+            miniprogramMap.put("pagepath", miniprogramPage);
         }
         mpTemplateMsgOriginalDTO.setMiniprogram(miniprogramMap);
 
@@ -190,7 +190,7 @@ public class WxTemplateServiceImpl implements WxTemplateService {
 
         Map<String, String> miniprogramMap = Maps.newHashMap();
         miniprogramMap.put("appid", miniprogramAppid);
-        miniprogramMap.put("page", miniprogramPage);
+        miniprogramMap.put("pagepath", miniprogramPage);
         mpTemplateMsgDTO.setMiniprogram(miniprogramMap);
 
         wxUniformTemplateDTO.setMp_template_msg(mpTemplateMsgDTO);

+ 2 - 0
src/main/java/com/care/common/util/MessageUtil.java

@@ -8,4 +8,6 @@ public interface MessageUtil {
 
     String UNSUBSCIBE_EVENT = "unsubscribe";
 
+    String SCAN_EVENT = "scan";
+
 }

+ 5 - 0
src/main/java/com/care/common/util/WxTemplateUtil.java

@@ -6,6 +6,7 @@ import com.care.client.dto.MpTemplateMsgOriginalDTO;
 import com.care.client.dto.WxTemplateDTO;
 import com.care.client.dto.WxUniformTemplateDTO;
 import com.care.client.vo.WxAccessTokenVO;
+import lombok.extern.slf4j.Slf4j;
 import org.apache.commons.lang3.StringUtils;
 import org.springframework.web.bind.annotation.RequestMethod;
 
@@ -24,6 +25,7 @@ import java.security.SecureRandom;
 /**
  * 微信接口访问工具封装
  */
+@Slf4j
 public class WxTemplateUtil {
 
     /**
@@ -121,6 +123,9 @@ public class WxTemplateUtil {
         JSONObject jsonObject = httpRequest(requestUrl, "GET", null);
         // 如果请求成功
         if (null != jsonObject) {
+            if (StringUtils.isNotBlank(jsonObject.getStr("errmsg"))) {
+                log.error("获取AccessToken出现错误: " + jsonObject.getStr("errmsg"));
+            }
             try {
                 wxAccessTokenVO = new WxAccessTokenVO();
                 wxAccessTokenVO.setAccessToken(jsonObject.getStr("access_token"));