Browse Source

合利宝退款

zhijiezhao 3 years ago
parent
commit
300ce3cffd

+ 2 - 0
src/main/java/com/caimei/modules/order/dao/CmReceiptOrderRelationDao.java

@@ -38,4 +38,6 @@ public interface CmReceiptOrderRelationDao extends CrudDao<CmReceiptOrderRelatio
     String findUserId(Integer orderId);
 
     void insertOnlineRefund(OnlineRefundVo onlineRefundVo);
+
+    List<CmReceiptOrderRelation> findByShopOrderIds(@Param("shopOrderIds")List<Integer> shopOrderIds);
 }

+ 4 - 0
src/main/java/com/caimei/modules/order/dao/CmReturnedPurchaseDao.java

@@ -26,4 +26,8 @@ public interface CmReturnedPurchaseDao extends CrudDao<CmReturnedPurchase> {
     List<CmReturnedPurchase>  findListBuySuccess(CmReturnedPurchase item);
 
     Double refundTotalMoney(Integer orderID);
+
+    List<Integer> findReturnedShopOrder(Integer orderID);
+
+    String findSplitCode(Integer shopOrderId);
 }

+ 12 - 0
src/main/java/com/caimei/modules/order/entity/CmReceiptOrderRelation.java

@@ -27,6 +27,10 @@ public class CmReceiptOrderRelation extends DataEntity<CmReceiptOrderRelation> {
      * 抹平备注(目前适用后台直接抹平账户操作)
      */
     private String balanceAccountsRemark;
+    /**
+     * 子订单Id
+     */
+    private Integer shopOrderId;
 
     /**
      * 米花科技平台唯一流水号
@@ -75,6 +79,14 @@ public class CmReceiptOrderRelation extends DataEntity<CmReceiptOrderRelation> {
         this.balanceAccountsRemark = balanceAccountsRemark;
     }
 
+    public Integer getShopOrderId() {
+        return shopOrderId;
+    }
+
+    public void setShopOrderId(Integer shopOrderId) {
+        this.shopOrderId = shopOrderId;
+    }
+
     public CmReceiptOrderRelation() {
         super();
     }

+ 2 - 2
src/main/java/com/caimei/modules/order/entity/OnlineRefundData.java

@@ -15,8 +15,8 @@ public class OnlineRefundData  implements Serializable {
     private String rt7_amount;
     private String rt8_orderStatus;
     private String sign;
-    public static final Set<String> NEED_SIGN_PARAMS = ImmutableSet.of("rt1_bizType", "rt2_retCode", "rt4_customerNumber",
-            "rt5_orderId", "rt6_refundOrderNum", "rt7_serialNumber", "rt8_amount");
+    public static final Set<String> NEED_SIGN_PARAMS = ImmutableSet.of("rt1_bizType", "rt2_retCode","rt3_retMsg", "rt4_customerNumber",
+            "rt5_orderId", "rt6_refundOrderNum", "rt7_amount", "rt8_orderStatus");
 
     public OnlineRefundData() {
     }

+ 135 - 84
src/main/java/com/caimei/modules/order/service/CmReturnedPurchaseService.java

@@ -1,5 +1,6 @@
 package com.caimei.modules.order.service;
 
+import com.alibaba.fastjson.JSON;
 import com.alibaba.fastjson.JSONObject;
 import com.caimei.modules.coupon.dao.CmCouponClubDao;
 import com.caimei.modules.coupon.entity.CmCouponClub;
@@ -26,6 +27,10 @@ import com.thinkgem.jeesite.common.persistence.Page;
 import com.thinkgem.jeesite.common.service.CrudService;
 import com.thinkgem.jeesite.common.utils.StringUtils;
 import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
+import okhttp3.FormBody;
+import okhttp3.OkHttpClient;
+import okhttp3.Request;
+import okhttp3.Response;
 import org.apache.commons.collections.CollectionUtils;
 import org.apache.commons.lang.ArrayUtils;
 import org.springframework.beans.factory.annotation.Autowired;
@@ -36,9 +41,11 @@ import org.apache.commons.httpclient.HttpStatus;
 import javax.annotation.Resource;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
 import java.math.BigDecimal;
 import java.text.SimpleDateFormat;
 import java.util.*;
+import java.util.concurrent.TimeUnit;
 
 import static com.caimei.modules.miniprogram.utils.UploadPicUtils.saveImageToServer;
 
@@ -52,6 +59,11 @@ import static com.caimei.modules.miniprogram.utils.UploadPicUtils.saveImageToSer
 @Transactional(readOnly = true)
 public class CmReturnedPurchaseService extends CrudService<CmReturnedPurchaseDao, CmReturnedPurchase> {
 
+    public static OkHttpClient client = new OkHttpClient.Builder()
+            .connectTimeout(3, TimeUnit.SECONDS)
+            .readTimeout(20, TimeUnit.SECONDS)
+            .build();
+
     @Resource
     private CmReturnedPurchaseDao cmReturnedPurchaseDao;
     @Resource
@@ -456,7 +468,7 @@ public class CmReturnedPurchaseService extends CrudService<CmReturnedPurchaseDao
         return newOrder;
     }
 
-    @Transactional(readOnly = false)
+    @Transactional(readOnly = false,rollbackFor = Exception.class)
     public void confirmApply(CmReturnedPurchase cmReturnedPurchase, HttpServletRequest request) throws Exception {
         CmReturnedPurchase returnedPurchase = cmReturnedPurchaseDao.get(cmReturnedPurchase);
         if (returnedPurchase == null) {
@@ -592,7 +604,12 @@ public class CmReturnedPurchaseService extends CrudService<CmReturnedPurchaseDao
 
             //判断是否有线上退款
             if (returnedPurchase.getReturnedWay().equals("1") && returnedPurchase.getRefundOnlineFee() > 0) {
-                theOnlineRefund(returnedPurchase.getOrderID());
+                List<Integer> shopOrderIds=cmReturnedPurchaseDao.findReturnedShopOrder(returnedPurchase.getOrderID());
+                if(null==shopOrderIds||0==shopOrderIds.size()){
+                    throw new Exception("子订单信息错误!");
+                    return;
+                }
+                theOnlineRefund(shopOrderIds);
             }
 
             //二手订单交易全退,标记未售
@@ -732,33 +749,32 @@ public class CmReturnedPurchaseService extends CrudService<CmReturnedPurchaseDao
     /**
      * 第三方线上退款
      *
-     * @param orderId
+     * @param shopOrderIds
      */
-    private void theOnlineRefund(Integer orderId) throws Exception {
-        List<CmReceiptOrderRelation> relationList = cmReceiptOrderRelationDao.findByOrderID(orderId.toString());
+    private void theOnlineRefund(List<Integer> shopOrderIds) throws Exception {
+        List<CmReceiptOrderRelation> relationList = cmReceiptOrderRelationDao.findByShopOrderIds(shopOrderIds);
         if (null != relationList && relationList.size() > 0) {
             for (CmReceiptOrderRelation orderRelation : relationList) {
                 //cdr表payway为1纯线上收款
                 if ("1".equals(orderRelation.getPayWay())) {
                     //不同产品区分
-                    String payType = cmReceiptOrderRelationDao.findPayType(orderId);
-                    if ("12".equals(payType) || "17".equals(payType)) {
+                    if ("12".equals(orderRelation.getPayType()) || "17".equals(orderRelation.getPayType())) {
                         //网银
-                        onlinePay(orderRelation.getOrderRequestNo(), orderRelation.getAssociateAmount(), orderId, "1");
+                        unionRefund(orderRelation.getOrderRequestNo(), orderRelation.getAssociateAmount(), orderRelation.getShopOrderId());
                     } else {
                         //扫码
-                        unionRefund(orderRelation.getOrderRequestNo(), orderRelation.getAssociateAmount(), orderId, "1");
+                        onlinePay(orderRelation.getOrderRequestNo(), orderRelation.getAssociateAmount(), orderRelation.getShopOrderId());
                     }
                 }
             }
         }
     }
 
-    void onlinePay(String orderRequestNo, String money, Integer orderId, String type) throws Exception {
+    void onlinePay(String orderRequestNo, String money, Integer shopOrderId) throws Exception {
         AppPayRefundOrderVo orderVo = new AppPayRefundOrderVo();
         orderVo.setP1_bizType("AppPayRefund");
-        //todo 暂用本商户  E1807062884 网络
-        orderVo.setP3_customerNumber("E1807062884");
+        String splitCode=cmReturnedPurchaseDao.findSplitCode(shopOrderId);
+        orderVo.setP3_customerNumber(splitCode);
         //退款原单号
         orderVo.setP2_orderId(orderRequestNo);
         //自定义退款单号
@@ -766,92 +782,127 @@ public class CmReturnedPurchaseService extends CrudService<CmReturnedPurchaseDao
         orderVo.setP4_refundOrderId("TK" + tk +orderRequestNo);
         //退款金额
         orderVo.setP5_amount(money);
-        Map<String, String> map = MyBeanUtils.convertBean(orderVo, new LinkedHashMap());
-        String oriMessage = MyBeanUtils.getSignedByPresetParameter(map, AppPayRefundOrderVo.NEED_SIGN_PARAMS);
-        //网银产品密钥
-        oriMessage += "1iHnZaalUNAVcfcbKdh6n86Z0yUHtM6f";
-        logger.info("签名原文串:" + oriMessage);
-        String sign = Disguiser.disguiseMD5(oriMessage.trim());
-        logger.info("签名串:" + sign);
-        map.put("sign", sign);
-        logger.info("发送参数:" + map);
-        Map<String, Object> resultMap = HttpClientService.getHttpResp(map, "http://pay.trx.helipay.com/trx/app/interface.action");
-        logger.info("响应结果:" + resultMap);
-        if ((Integer) resultMap.get("statusCode") == HttpStatus.SC_OK) {
-            String resultMsg = (String) resultMap.get("response");
-            AppPayRefundOrderResponseVo orderResponseVo = JSONObject.parseObject(resultMsg, AppPayRefundOrderResponseVo.class);
-            String assemblyRespOriSign = MyBeanUtils.getSignedByPresetParameter(orderResponseVo, AppPayRefundOrderResponseVo.NEED_SIGN_PARAMS);
-            //密钥区分
-            assemblyRespOriSign += "CZiCbGrgFYQMldVkQnzbFQeQkn6mp25w";
-            logger.info("组装返回结果签名串:" + assemblyRespOriSign);
-            String responseSign = orderResponseVo.getSign();
-            logger.info("响应签名:" + responseSign);
-            String checkSign = Disguiser.disguiseMD5(assemblyRespOriSign.trim());
-            if (checkSign.equals(responseSign)) {
-                if ("0001".equals(orderResponseVo.getRt2_retCode())) {
-                    logger.info("第三方退款成功>>>>>>>orderId>>>" + orderId);
+        try {
+            Map<String, String> map = MyBeanUtils.convertBean(orderVo, new LinkedHashMap());
+            String oriMessage = MyBeanUtils.getSignedByPresetParameter(map, AppPayRefundOrderVo.NEED_SIGN_PARAMS);
+            oriMessage+=Constant.SAOMA;
+            String sign = Disguiser.disguiseMD5(oriMessage.trim());
+            logger.info("签名串:" + sign);
+            map.put("sign", sign);
+            logger.info("发送参数:" + map);
+            Map<String, Object> resultMap = HttpClientService.getHttpResp(map, Constant.REQUEST_URL);
+            logger.info("响应结果:" + resultMap);
+            if ((Integer) resultMap.get("statusCode") == HttpStatus.SC_OK) {
+                String resultMsg = (String) resultMap.get("response");
+                AppPayRefundOrderResponseVo orderResponseVo = JSONObject.parseObject(resultMsg, AppPayRefundOrderResponseVo.class);
+                //String[] excludes = {"rt3_retMsg"};
+                String assemblyRespOriSign = MyBeanUtils.getSignedByPresetParameter(orderResponseVo, AppPayRefundOrderResponseVo.NEED_SIGN_PARAMS);
+                assemblyRespOriSign+=Constant.SAOMA;
+                logger.info("组装返回结果签名串:" + assemblyRespOriSign);
+                String responseSign = orderResponseVo.getSign();
+                logger.info("响应签名:" + responseSign);
+                String checkSign = Disguiser.disguiseMD5(assemblyRespOriSign.trim());
+                if (checkSign.equals(responseSign)) {
+                    if ("0001".equals(orderResponseVo.getRt2_retCode())) {
+                        logger.info("第三方退款成功>>>>>>>shopOrderId>>>" + shopOrderId);
+                    } else {
+                        logger.error("退款失败========================" + orderResponseVo.getRt5_orderId() + "-" + orderResponseVo.getRt3_retMsg());
+                        throw new Exception("第三方退款失败!");
+                    }
                 } else {
-                    logger.error("退款失败========================" + orderResponseVo.getRt5_orderId() + "-" + orderResponseVo.getRt3_retMsg());
-                    throw new Exception("第三方退款失败!");
+                    logger.error("退款验签失败");
+                    throw new Exception("第三方退款验签失败!");
                 }
             } else {
-                logger.error("退款验签失败");
-                throw new Exception("第三方退款验签失败!");
+                logger.error("退款请求失败");
+                throw new Exception("第三方退款请求失败!");
             }
-        } else {
-            logger.error("退款请求失败");
-            throw new Exception("第三方退款请求失败!");
+        } catch (Exception e) {
+            e.printStackTrace();
         }
     }
     //todo 网银退款不退手续费,
     //1.本方法内转账手续费等待到账再发起退款请求
     //2.异步
     //3.回调
-    void unionRefund(String orderRequestNo,String money,Integer orderId,String type) throws Exception{
-        OnlineVo onlineVo = new OnlineVo();
-        onlineVo.setP1_bizType("OnlineRefund");
-        onlineVo.setP2_orderId(orderRequestNo);
-        onlineVo.setP3_customerNumber("E1807062884");
-        onlineVo.setP4_refundAmount(money);
-        onlineVo.setP5_refundOrderId("TK" +orderRequestNo);
-        //暂时不设置备注和回调
-        //onlineVo.setP6_desc("");
-        //onlineVo.setP7_serverCallbackUrl("");
-        Map<String, String> map = MyBeanUtils.convertBean(onlineVo, new LinkedHashMap());
-        String oriMessage = MyBeanUtils.getSignedByPresetParameter(map, OnlineVo.NEED_SIGN_PARAMS);
-        oriMessage += "CZiCbGrgFYQMldVkQnzbFQeQkn6mp25w";
-        logger.info("签名原文串:" + oriMessage);
-        String sign = Disguiser.disguiseMD5(oriMessage.trim());
-        logger.info("签名串:" + sign);
-        map.put("sign", sign);
-        logger.info("发送参数:" + map);
-        Map<String, Object> resultMap = HttpClientService.getHttpResp(map, "http://pay.trx.helipay.com/trx/online/interface.action");
-        logger.info("响应结果:" + resultMap);
-        if ((Integer) resultMap.get("statusCode") == HttpStatus.SC_OK) {
-            String resultMsg = (String) resultMap.get("response");
-            OnlineRefundData onlineRefund = JSONObject.parseObject(resultMsg, OnlineRefundData.class);
-            String assemblyRespOriSign = MyBeanUtils.getSignedByPresetParameter(onlineRefund, OnlineRefundData.NEED_SIGN_PARAMS);
-            //密钥区分
-            assemblyRespOriSign += "CZiCbGrgFYQMldVkQnzbFQeQkn6mp25w";
-            logger.info("组装返回结果签名串:" + assemblyRespOriSign);
-            String responseSign = onlineRefund.getSign();
-            logger.info("响应签名:" + responseSign);
-            String checkSign = Disguiser.disguiseMD5(assemblyRespOriSign.trim());
-            if (checkSign.equals(responseSign)) {
-                if ("0000".equals(onlineRefund.getRt2_retCode())) {
-                    logger.info("第三方退款成功>>>>>>>orderId>>>" + orderId);
-                } else {
-                    logger.error("退款失败========================" + onlineRefund.getRt5_orderId() + "-" + onlineRefund.getRt3_retMsg());
+    void unionRefund(String orderRequestNo,String money,Integer shopOrderId) throws Exception{
+        Map<String, String> sPara = new HashMap<String, String>();
+        sPara.put("P1_bizType", "OnlineRefund");
+        sPara.put("P2_orderId", orderRequestNo);
+        String splitCode=cmReturnedPurchaseDao.findSplitCode(shopOrderId);
+        sPara.put("P3_customerNumber", splitCode);
+        sPara.put("P4_refundAmount",money);
+        sPara.put("P5_refundOrderId","TK" +orderRequestNo);
+        sPara.put("P6_desc","无");
+        sPara.put("P7_serverCallbackUrl","");
+        StringBuffer sb = new StringBuffer();
+        sb.append("&").append("OnlineRefund").append("&").append(orderRequestNo).append("&").append(splitCode).append("&").
+                append(money).append("&").append("TK" +orderRequestNo).append("&").append("无").append("&").append("&").append(Constant.WANGYIN);
+        String sign = Disguiser.disguiseMD5(sb.toString());
+        sPara.put("sign", sign);
+        try {
+            OnlineRefundData on = postForm(sPara, Constant.YL, sign, OnlineRefundData.class);
+            JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(on), JSONObject.class);
+            if (!"0000".equals(on.getRt2_retCode())) {
+                logger.info("退款失败:" + on.toString());
+                throw new Exception("退款失败");
+            } else {
+                String assemblyRespOriSign = MyBeanUtils.getSignedByPresetParameter(on, OnlineRefundData.NEED_SIGN_PARAMS);
+                logger.info("组装返回结果签名串:" + assemblyRespOriSign);
+                assemblyRespOriSign += Constant.SPLIT + Constant.WANGYIN;
+                String checkSign = Disguiser.disguiseMD5(assemblyRespOriSign.trim());
+                if (!checkSign.equals(on.getSign())) {
+                    logger.error("验签失败========================" +on.getRt3_retMsg());
                     throw new Exception("第三方退款失败!");
+                } else {
+                    logger.info("第三方退款成功");
                 }
-            } else {
-                logger.error("退款验签失败");
-                throw new Exception("第三方退款验签失败!");
             }
-        } else {
-            logger.error("退款请求失败");
-            throw new Exception("第三方退款请求失败!");
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+    }
+
+    private <T> T postForm(Map<String, String> params, String url, String sign, Class<T> clazz) {
+        FormBody.Builder builder = new FormBody.Builder();
+        for (Map.Entry<String, String> entry : params.entrySet()) {
+            builder.add(entry.getKey(), entry.getValue());
+        }
+        builder.add("sign", sign);
+
+        Request request = new Request.Builder() // okHttp post
+                .url(url)
+                .post(builder.build())
+                .build();
+
+        Response response = null;
+        try {
+            response = client.newCall(request).execute();
+        } catch (IOException e) {
+            throw new IllegalStateException("请求出错", e);
+        }
+        if (!response.isSuccessful()) {
+            try {
+                logger.info(response.body().string());
+            } catch (IOException e) {
+                e.printStackTrace();
+            }
+            throw new RuntimeException("请求失败了: http response code: " + response.code());
+        }
+
+        okhttp3.ResponseBody body = response.body();
+        String content = null;
+        try {
+            content = body.string();
+        } catch (IOException e) {
+            throw new IllegalStateException("IO异常", e);
+        }
+        JSONObject res = JSON.parseObject(content);
+        if ("0000".equals(res.getString("rt2_retCode"))) {
+            logger.info("退款申请发起成功------->"+res.toString());
         }
+        /** rt4_success 为 true,需验签  **/
+        return res.toJavaObject(clazz);
     }
 
     @Transactional(readOnly = false)

+ 2 - 5
src/main/java/com/caimei/modules/order/service/SplitAccountService.java

@@ -9,6 +9,7 @@ import com.caimei.modules.order.utils.PayUtil;
 import com.caimei.redis.RedisService;
 import com.caimei.utils.MathUtil;
 import com.thinkgem.jeesite.common.persistence.Page;
+import com.thinkgem.jeesite.common.service.BaseService;
 import okhttp3.*;
 import org.apache.commons.lang3.StringUtils;
 import org.slf4j.Logger;
@@ -27,16 +28,12 @@ import java.util.stream.Collectors;
 
 @Service
 @Transactional(readOnly = true)
-public class SplitAccountService {
+public class SplitAccountService extends BaseService {
 
     public static OkHttpClient client = new OkHttpClient.Builder()
             .connectTimeout(3, TimeUnit.SECONDS)
             .readTimeout(20, TimeUnit.SECONDS)
             .build();
-    /**
-     * 日志对象
-     */
-    private static Logger logger = LoggerFactory.getLogger(Logger.class);
 
     @Resource
     private NewOrderDao newOrderDao;

+ 21 - 1
src/main/resources/mappings/modules/order/CmReceiptOrderRelationMapper.xml

@@ -210,9 +210,29 @@
 		SELECT payType
 		FROM cm_discern_receipt cdr
 		LEFT JOIN cm_receipt_order_relation cror ON cdr.id = cror.receiptID
-		WHERE cror.orderID = #{orderId}
+		WHERE cror.shopOrderId = #{orderId}
 	</select>
 	<select id="findUserId" resultType="java.lang.String">
 		select userId from cm_order where orderId=#{orderId}
 	</select>
+	<select id="findByShopOrderIds" resultType="com.caimei.modules.order.entity.CmReceiptOrderRelation">
+		select
+			a.*,
+			b.payType as "payType",
+			b.receiptDate as "receiptDate",
+			b.confirmType as "confirmType",
+			b.balanceAccountsRemark as "balanceAccountsRemark",
+			b.payWay as "payWay"
+		from  cm_receipt_order_relation a
+		left join cm_discern_receipt b on a.receiptID = b.id
+		where a.shopOrderId in
+		<foreach collection="shopOrderIds" open="(" close=")" item="shopOrderId" separator=",">
+			#{shopOrderId}
+		</foreach>
+		  AND b.receiptType = '1'
+		  AND b.receiptStatus = '3'
+		  AND a.delFlag = '0'
+		  AND b.delFlag = '0'
+		order by b.receiptDate desc
+	</select>
 </mapper>

+ 8 - 1
src/main/resources/mappings/modules/order/CmReturnedPurchaseMapper.xml

@@ -398,5 +398,12 @@
 		SELECT SUM(IFNULL(returnedPurchaseFee,0)) FROM cm_returned_purchase
 		WHERE orderID=#{orderID} AND delFlag='0' AND status='2'
 	</select>
-
+	<select id="findReturnedShopOrder" resultType="java.lang.Integer">
+		SELECT shopOrderId FROM cm_returned_purchase_product crpp
+		LEFT JOIN cm_returned_purchase crp ON crp.id=crpp.returnedID
+		WHERE crp.orderId=#{orderID}
+		  AND crp.status=2
+		  AND crp.returnedWay =1
+		  AND crp.delflag=0
+	</select>
 </mapper>

+ 2 - 2
src/main/resources/mappings/modules/order/OrderMapper.xml

@@ -1247,9 +1247,9 @@
     <insert id="insertSplitAccount">
         INSERT INTO cm_split_account (orderId, productId, orderProductId, shopId, couponRecordId, vipRecordId,
                                       authVipRecordId, type, subUserNo, splitAccount,
-                                      mbOrderId, orderRequestNo, payStatus, productType, splitTime)
+                                      mbOrderId, orderRequestNo, payStatus, productType, shopOrderId ,splitTime)
         VALUES (#{orderId}, #{productId}, #{orderProductId}, #{shopId}, #{couponRecordId}, #{vipRecordId},
                 #{authVipRecordId}, #{type}, #{subUserNo}, #{splitAccount},
-                #{mbOrderId}, #{orderRequestNo}, #{payStatus}, #{productType}, NOW());
+                #{mbOrderId}, #{orderRequestNo}, #{payStatus}, #{productType},#{shopOrderId}, NOW());
     </insert>
 </mapper>