Browse Source

feature 解决无法切库的问题

xiahan 3 weeks ago
parent
commit
5493bfb024

+ 34 - 25
zhsw-wechat-common/src/main/java/com/rongwei/wechat/system/config/ZHSWQuerySqlAdaptationInterceptor.java

@@ -57,39 +57,39 @@ public class ZHSWQuerySqlAdaptationInterceptor implements Interceptor {
         //获取到原始sql语句
         String sql = boundSql.getSql();
         SqlAdaptationUtil sqlAdaptation = new SqlAdaptationUtil();
-        String mSql = sqlAdaptation.modifySql(sqlAdaptation.commonRuleAnalysis(sql),dbType);
+        String mSql = sqlAdaptation.modifySql(sqlAdaptation.commonRuleAnalysis(sql), dbType);
         //通过反射修改sql语句
         Field field = boundSql.getClass().getDeclaredField("sql");
         field.setAccessible(true);
         // dao参数
         Object parObj = statementHandler.getParameterHandler().getParameterObject();
         // SaaS环境下schema切换
-        if("DATASOURCE".equals(saasmode)){
+        if ("DATASOURCE".equals(saasmode)) {
             logger.info("saas切换");
             String schema = null;
-            try{
+            try {
                 schema = this.getSchema();
-            }catch (Exception e){
+            } catch (Exception e) {
                 logger.info("通过上下文对象获取schema失败");
             }
             // 判断是否有参数(appointSchema)指定schema
-            if(parObj instanceof MapperMethod.ParamMap){
-                MapperMethod.ParamMap paramMap = (MapperMethod.ParamMap)parObj;
-                if(paramMap.containsKey("appointSchema") && paramMap.get("appointSchema") != null){
+            if (parObj instanceof MapperMethod.ParamMap) {
+                MapperMethod.ParamMap paramMap = (MapperMethod.ParamMap) parObj;
+                if (paramMap.containsKey("appointSchema") && paramMap.get("appointSchema") != null) {
                     String appointSchema = paramMap.get("appointSchema").toString();
                     schema = appointSchema;
                 }
             }
-            logger.info("schema:"+schema);
-            if(StringUtils.isNotBlank(schema)){
+            logger.info("schema:" + schema);
+            if (StringUtils.isNotBlank(schema)) {
                 // 多租户schema切换方案一:通过 USE databaseName; 实现切换
                 mSql = "USE " + schema + ";" + mSql;
-                logger.info("mSql:"+mSql);
+                logger.info("mSql:" + mSql);
                 // 多租户schema切换方案二:直接获取Connection设置schema
                 /*Object[] objs = invocation.getArgs();
                 Connection conn = (Connection)objs[0];
                 conn.setSchema(schema);*/
-            }else{
+            } else {
 //                throw new Exception("SaaS模式下查不到相应schema");
                 logger.warn("SaaS模式下查不到相应schema");
             }
@@ -118,35 +118,43 @@ public class ZHSWQuerySqlAdaptationInterceptor implements Interceptor {
 
     /**
      * SaaS模式下获取当前租户的数据库名
+     *
      * @return
      * @throws Exception
      */
-    private String getSchema() throws Exception{
+    private String getSchema() throws Exception {
         Long startTime = System.currentTimeMillis();
         String schema = null;
         schema = ContextHolder.getValue("dsKey");
-        if(StringUtils.isNotBlank(schema)){
+        if (StringUtils.isNotBlank(schema)) {
+            logger.info("通过上下文对象ContextHolder获取到的schema:" + schema);
             return schema;
         }
 
         ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
-        if(attributes == null){
+        if (attributes == null) {
             logger.error("ServletRequestAttributes为null");
             throw new Exception("ServletRequestAttributes为null");
         }
         HttpServletRequest request = attributes.getRequest();
-        if(request == null){
+        if (request == null) {
             logger.error("HttpServletRequest为null");
             throw new Exception("HttpServletRequest为null");
         }
 
         schema = request.getHeader("schema");
-        if(StringUtils.isNotBlank(schema)) {
+        if (StringUtils.isNotBlank(schema)) {
+            logger.info("通过请求头获取到的schema:" + schema);
+            return schema;
+        }
+        Object attributeSchema = request.getAttribute("schema");
+        if (attributeSchema != null && StringUtils.isNotBlank(attributeSchema.toString())) {
+            schema = (String) attributeSchema;
+            logger.info("通过请求属性获取到的schema:" + schema);
             return schema;
         }
-
         String token = request.getHeader("token");
-        logger.info("token:"+token);
+        logger.info("token:" + token);
 //        if(StringUtils.isBlank(token)){
 //            String incontrolToken = request.getHeader("incontrol-token");
 //            Object tokenDskey = request.getAttribute(Constants.SAAS_LOGIN_TOKEN);
@@ -171,29 +179,30 @@ public class ZHSWQuerySqlAdaptationInterceptor implements Interceptor {
 //            System.out.println("Dskey:"+schema);
 //        }
         Object tokenDskey = request.getAttribute(Constants.SAAS_LOGIN_TOKEN);
-        if(tokenDskey != null && StringUtils.isNotBlank(tokenDskey.toString())){
+        if (tokenDskey != null && StringUtils.isNotBlank(tokenDskey.toString())) {
             schema = (String) tokenDskey;
-        }else {
+        } else {
             schema = getSchemaByToken(token);
         }
-        System.out.println("Dskey:"+schema);
+        System.out.println("Dskey:" + schema);
         Long endTime = System.currentTimeMillis();
-        System.out.println("查找schema时间为:"+(endTime-startTime));
+        System.out.println("查找schema时间为:" + (endTime - startTime));
         return schema;
     }
 
     /**
      * 根据token获取多租户模式的schema
+     *
      * @param token
      * @return
      */
-    private String getSchemaByToken(String token){
+    private String getSchemaByToken(String token) {
         SysUserVo currUser = null;
-        if(StringUtils.isNotEmpty(token)){
+        if (StringUtils.isNotEmpty(token)) {
             currUser = redisService.getLoginUser(token);
         }
         String schema = null;
-        if(currUser != null){
+        if (currUser != null) {
             schema = currUser.getTenantDo().getDskey();
         }
         return schema;

+ 1 - 0
zhsw-wechat-common/src/main/java/com/rongwei/wechat/system/utils/SaveConstans.java

@@ -159,6 +159,7 @@ public class SaveConstans {
 
         public static final String SUCCESS = "success";
         public static final String CANCEL = "cancel";
+        public static final String FAIL = "fail";
     }
 
     public static final List<String> MONTH_ENG = new ArrayList<String>() {{

+ 3 - 1
zhsw-wechat-common/src/main/java/com/rongwei/wechat/system/wechat/PayMentService.java

@@ -5,6 +5,7 @@ import com.rongwe.wechat.system.vo.WxPrepayOrderVo;
 import com.rongwei.rwcommon.base.R;
 import org.springframework.http.ResponseEntity;
 
+import javax.servlet.http.HttpServletRequest;
 import java.io.IOException;
 import java.math.BigDecimal;
 
@@ -17,7 +18,8 @@ import java.math.BigDecimal;
 public interface PayMentService {
     R paymentInitiation(WxPrepayOrderVo vo);
 
-    ResponseEntity<String> prepayNotice(PrepayNoticeVo prepayNoticeVo, String dskey, BigDecimal amount, String userNum) throws IOException;
+    ResponseEntity<String> prepayNotice(PrepayNoticeVo prepayNoticeVo, String dskey, BigDecimal amount,
+                                        String userNum, HttpServletRequest httpServletRequest) throws IOException;
 
     R cancel(String orderNo, String type);
 }

+ 37 - 19
zhsw-wechat-common/src/main/java/com/rongwei/wechat/system/wechat/impl/PayMentServiceImpl.java

@@ -38,6 +38,7 @@ import org.springframework.stereotype.Service;
 import javax.crypto.Cipher;
 import javax.crypto.spec.GCMParameterSpec;
 import javax.crypto.spec.SecretKeySpec;
+import javax.servlet.http.HttpServletRequest;
 import java.io.IOException;
 import java.math.BigDecimal;
 import java.math.RoundingMode;
@@ -187,24 +188,30 @@ public class PayMentServiceImpl implements PayMentService {
      * @return
      */
     @Override
-    public ResponseEntity<String> prepayNotice(PrepayNoticeVo prepayNoticeVo, String dskey, BigDecimal amount, String userNum) {
+    public ResponseEntity<String> prepayNotice(PrepayNoticeVo prepayNoticeVo, String dskey, BigDecimal amount,
+                                               String userNum, HttpServletRequest httpServletRequest) {
         log.info("获取到的支付成功的回调:{},dskey:{},amount:{},userNum:{}", prepayNoticeVo, dskey, amount, userNum);
         // 传来的数据为整数 所以需要除以100
         amount = amount.divide(new BigDecimal(100), 2, RoundingMode.HALF_UP);
-        List<String> dsKeys;
-        if (StringUtils.isBlank(dskey)) {
-            List<TenantDo> tenantList = (List<TenantDo>) redisService.getRedisCatchObj("allTenants");
-            // 获取 所有的主库信息
-            dsKeys = tenantList.stream().map(TenantDo::getDskey).collect(Collectors.toList());
-        } else {
-            dsKeys = Collections.singletonList(dskey);
-        }
+        // List<String> dsKeys;
+        // if (StringUtils.isBlank(dskey)) {
+        //     List<TenantDo> tenantList = (List<TenantDo>) redisService.getRedisCatchObj("allTenants");
+        //     // 获取 所有的主库信息
+        //     dsKeys = tenantList.stream().map(TenantDo::getDskey).collect(Collectors.toList());
+        // } else {
+        //     dsKeys = Collections.singletonList(dskey);
+        // }
         R error = R.error("失败");
-        dsKeys.remove("incontrol");
+        // dsKeys.remove("incontrol");
+        httpServletRequest.setAttribute("schema",dskey);
         // 获取所有商户的密钥
-        List<SwEnterpriseConfigInfoDo> secretKeyList = commonBusinessDao.getSecretKey(dsKeys);
+        List<SwEnterpriseConfigInfoDo> secretKeyList = commonBusinessDao.getSecretKey(Collections.singletonList(dskey));
         String analysisStr = null;
-        String deKey = null;
+        // String deKey = null;
+        if(secretKeyList.isEmpty()) {
+            log.error("无法根据:{}找到到对应的商户信息",dskey);
+            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error.toString());
+        }
         for (SwEnterpriseConfigInfoDo swEnterpriseConfigInfoDo : secretKeyList) {
             try {
                 byte[] apiV3Key = swEnterpriseConfigInfoDo.getMerchantsecretkey().getBytes("UTF8");
@@ -217,7 +224,7 @@ public class PayMentServiceImpl implements PayMentService {
                 cipher.init(Cipher.DECRYPT_MODE, key, spec);
                 cipher.updateAAD(associatedData);
                 analysisStr = new String(cipher.doFinal(Base64.getDecoder().decode(ciphertext)), "utf-8");
-                deKey = swEnterpriseConfigInfoDo.getTenantid();
+                // deKey = swEnterpriseConfigInfoDo.getTenantid();
                 log.debug("解析成功");
                 if (StringUtils.isNotBlank(analysisStr)) {
                     break;
@@ -240,22 +247,25 @@ public class PayMentServiceImpl implements PayMentService {
             log.error("JSON转换异常");
             return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error.toString());
         }
+        // 商户号
+        String outTradeNo = transaction.getOutTradeNo();
+        SwPaymentInitRecordDo paymentInitRecordDo = swPaymentInitRecordService.getOne(new LambdaQueryWrapper<SwPaymentInitRecordDo>()
+                .eq(BaseDo::getDeleted, "0")
+                .eq(SwPaymentInitRecordDo::getOrderno, outTradeNo), false);
         try {
             // 微信订单号
             String transactionId = transaction.getTransactionId();
-            // 商户号
-            String outTradeNo = transaction.getOutTradeNo();
+
             Date successTime = transaction.getSuccessTime();
             log.debug("支付回调:{}", transaction);
             /******************创建缴费记录***************************/
 
-            ContextHolder.setValue("dskey", dskey);
+            // ContextHolder.setValue("dskey", dskey);
             CreatePaymentRecordVo createPaymentRecordVo = new CreatePaymentRecordVo();
             createPaymentRecordVo.setOrderNo(outTradeNo);
             createPaymentRecordVo.setPaymentAmount(amount);
-            SwPaymentInitRecordDo paymentInitRecordDo = swPaymentInitRecordService.getOne(new LambdaQueryWrapper<SwPaymentInitRecordDo>()
-                    .eq(BaseDo::getDeleted, "0")
-                    .eq(SwPaymentInitRecordDo::getOrderno, outTradeNo), false);
+
+            log.info("根据商户订单号:{}获取到的下单信息为:{}",outTradeNo,paymentInitRecordDo);
             String zdIds = null;
             if (paymentInitRecordDo != null) {
                 zdIds = StringUtils.isBlank(paymentInitRecordDo.getBillid()) ? null : paymentInitRecordDo.getBillid();
@@ -276,6 +286,14 @@ public class PayMentServiceImpl implements PayMentService {
             log.error("开始创建缴费记录:{}", createPaymentRecordVo);
             paymentRecordService.createRecord(createPaymentRecordVo);
         } catch (Exception e) {
+            if (paymentInitRecordDo != null) {
+                swPaymentInitRecordService.update(new LambdaUpdateWrapper<SwPaymentInitRecordDo>()
+                        .eq(SwPaymentInitRecordDo::getId, paymentInitRecordDo.getId())
+                        .set(SwPaymentInitRecordDo::getState, FAIL)
+                        .set(SwPaymentInitRecordDo::getCallbackcontent, transaction.toString())
+                        .set(BaseDo::getModifydate, new Date())
+                );
+            }
             return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error.toString());
         } finally {
             ContextHolder.clear();

+ 4 - 2
zhsw-wechat-server/src/main/java/com/rongwei/wechat/system/controller/weChat/PayMentController.java

@@ -13,6 +13,7 @@ import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.http.ResponseEntity;
 import org.springframework.web.bind.annotation.*;
 
+import javax.servlet.http.HttpServletRequest;
 import java.math.BigDecimal;
 
 @RestController
@@ -74,7 +75,8 @@ public class PayMentController {
      */
     @PostMapping("/prepay/notice/{dskey}/{amount}/{userNum}")
     public ResponseEntity<String> prepayNotice(@RequestBody PrepayNoticeVo prepayNoticeVo, @PathVariable("dskey") String dskey,
-                                               @PathVariable("amount") BigDecimal amount, @PathVariable("userNum") String userNum) {
-        return payMentService.prepayNotice(prepayNoticeVo, dskey, amount, userNum);
+                                               @PathVariable("amount") BigDecimal amount, @PathVariable("userNum") String userNum,
+                                               HttpServletRequest httpServletRequest) {
+        return payMentService.prepayNotice(prepayNoticeVo, dskey, amount, userNum,httpServletRequest);
     }
 }