From b65cbfb8452a95575f0dc637b55ed49f058597fe Mon Sep 17 00:00:00 2001
From: liurunyu <lry9898@163.com>
Date: 星期二, 20 八月 2024 21:02:21 +0800
Subject: [PATCH] Merge branch 'master' of http://8.140.179.55:20000/r/pipIrr-SV

---
 pipIrr-platform/pipIrr-web/pipIrr-web-sell/src/main/java/com/dy/pipIrrSell/wechatpay/PaymentCtrl.java |  374 +++++++++++++++++++++++++---------------------------
 1 files changed, 179 insertions(+), 195 deletions(-)

diff --git a/pipIrr-platform/pipIrr-web/pipIrr-web-sell/src/main/java/com/dy/pipIrrSell/wechatpay/PaymentCtrl.java b/pipIrr-platform/pipIrr-web/pipIrr-web-sell/src/main/java/com/dy/pipIrrSell/wechatpay/PaymentCtrl.java
index 5258444..ce1fb29 100644
--- a/pipIrr-platform/pipIrr-web/pipIrr-web-sell/src/main/java/com/dy/pipIrrSell/wechatpay/PaymentCtrl.java
+++ b/pipIrr-platform/pipIrr-web/pipIrr-web-sell/src/main/java/com/dy/pipIrrSell/wechatpay/PaymentCtrl.java
@@ -6,8 +6,8 @@
 import com.dy.common.webUtil.BaseResponse;
 import com.dy.common.webUtil.BaseResponseUtils;
 import com.dy.common.webUtil.ResultCodeMsg;
-import com.dy.pipIrrGlobal.pojoSe.SeVirtualCard;
-import com.dy.pipIrrGlobal.pojoSe.SeWebchatLogonState;
+import com.dy.pipIrrGlobal.cert.WxCertUtil;
+import com.dy.pipIrrGlobal.pojoSe.*;
 import com.dy.pipIrrGlobal.voSe.VoClient;
 import com.dy.pipIrrSell.client.ClientSv;
 import com.dy.pipIrrSell.result.SellResultCode;
@@ -16,17 +16,25 @@
 import com.dy.pipIrrSell.util.RestTemplateUtil;
 import com.dy.pipIrrSell.virtualCard.VirtualCardSv;
 import com.dy.pipIrrSell.virtualCard.dto.DtoVirtualCard;
-import com.dy.pipIrrSell.wechatpay.dto.*;
+import com.dy.pipIrrSell.virtualCard.enums.LastOperateENUM;
+import com.dy.pipIrrSell.virtualCard.enums.RefundItemStateENUM;
+import com.dy.pipIrrSell.wallet.enums.RefundStatusENUM;
+import com.dy.pipIrrSell.wechatpay.dto.Code2Session;
+import com.dy.pipIrrSell.wechatpay.dto.DtoOrder;
+import com.dy.pipIrrSell.wechatpay.dto.NotifyResource;
+import com.dy.pipIrrSell.wechatpay.dto.OrderNotify;
 import io.swagger.v3.oas.annotations.Operation;
 import io.swagger.v3.oas.annotations.media.Content;
 import io.swagger.v3.oas.annotations.media.Schema;
 import io.swagger.v3.oas.annotations.responses.ApiResponse;
 import io.swagger.v3.oas.annotations.responses.ApiResponses;
 import io.swagger.v3.oas.annotations.tags.Tag;
+import jakarta.servlet.http.HttpServletRequest;
 import jakarta.servlet.http.HttpServletResponse;
 import jakarta.validation.Valid;
 import lombok.RequiredArgsConstructor;
 import lombok.extern.slf4j.Slf4j;
+import org.springframework.core.io.ResourceLoader;
 import org.springframework.http.HttpHeaders;
 import org.springframework.http.MediaType;
 import org.springframework.transaction.annotation.Transactional;
@@ -34,6 +42,7 @@
 import org.springframework.web.bind.annotation.*;
 
 import javax.crypto.NoSuchPaddingException;
+import java.io.BufferedReader;
 import java.io.IOException;
 import java.security.GeneralSecurityException;
 import java.security.InvalidKeyException;
@@ -59,31 +68,32 @@
 @RequestMapping(path="payment")
 @RequiredArgsConstructor
 public class PaymentCtrl {
+    private final ResourceLoader resourceLoader;
+
     private final PaymentSv paymentSv;
     private final RestTemplateUtil restTemplateUtil;
     private final PayHelper payHelper;
     private final VirtualCardSv virtualCardSv;
     private final ClientSv clientSv;
 
-    private String privateCertFileName = PayInfo.privateCertFileName;
-    private String appid = PayInfo.appid;
-    private String mchid = PayInfo.mchid;
-    private String schema = PayInfo.schema;
-    private String signType = PayInfo.signType;
-    private String description = PayInfo.description;
-    private String loginUrl = PayInfo.loginUrl;
-    private String notifyUrl = PayInfo.notifyUrl;
-    private String grantType = PayInfo.grantType;
-    private String refundUrl = PayInfo.refundUrl;
+    //private final String privateCertFileName = PayInfo.privateCertFileName;
+    private final String appid = PayInfo.appid;
+    private final String secret = PayInfo.secret;
+    private final String mchid = PayInfo.mchid;
+    private final String schema = PayInfo.schema;
+    private final String signType = PayInfo.signType;
+    private final String description = PayInfo.description;
+    private final String loginUrl = PayInfo.loginUrl;
+    private final String notifyUrl = PayInfo.notifyUrl;
+    private final String grantType = PayInfo.grantType;
 
     // 骞冲彴璇佷功鍏挜
-    private Map CERTIFICATE_MAP = new HashMap();
+    private final Map CERTIFICATE_MAP = new HashMap();
 
     /**
-     * 鐧诲綍鍑瘉鏍¢獙
-     * @param appid 灏忕▼搴� appId
-     * @param secret 灏忕▼搴� appSecret
-     * @param js_code 涓存椂鐧诲綍鍑瘉code
+     * 鐧诲綍鍑瘉鏍¢獙锛屽啘鎴风粦瀹氳处鍙烽�昏緫鍖呭惈鐧诲綍鍑瘉鏍¢獙锛屾鎺ュ彛浣滃簾
+     * @param code2Session 鐧诲綍鍑瘉鏍¢獙浼犲叆瀵硅薄
+     * @param bindingResult
      * @return
      * @throws Exception
      */
@@ -99,11 +109,18 @@
     @PostMapping(path = "getSessionId")
     @Transactional(rollbackFor = Exception.class)
     @SsoAop()
-    public BaseResponse<Boolean> getSessionId(@RequestParam("appid")  String appid, @RequestParam("secret") String secret, @RequestParam("js_code") String js_code) throws Exception {
+    public BaseResponse<Boolean> getSessionId(@RequestBody @Valid Code2Session code2Session, BindingResult bindingResult) throws Exception {
+        if(bindingResult != null && bindingResult.hasErrors()){
+            return BaseResponseUtils.buildFail(Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage());
+        }
+
+        String phoneNumber = code2Session.getPhoneNumber();
+        String jsCode = code2Session.getJs_code();
+
         Map<String, Object> queryParams = new HashMap<>();
         queryParams.put("appid", appid);
         queryParams.put("secret", secret);
-        queryParams.put("js_code", js_code);
+        queryParams.put("js_code", jsCode);
         queryParams.put("grant_type", grantType);
         Map<String, String> headerParams = new HashMap<>();
         JSONObject job = restTemplateUtil.get(loginUrl, queryParams, headerParams);
@@ -115,35 +132,24 @@
         String openid = job.getString("openid");
         String sessionKey = job.getString("session_key");
 
-        // 妫�楠岀櫥褰曟��
-        JSONObject checkSessionKey = payHelper.checkSessionKey(appid, secret, openid, sessionKey);
-        if(checkSessionKey != null) {
-            Integer errcode = checkSessionKey.getInteger("errcode");
-            String errmsg = checkSessionKey.getString("errmsg");
-        }
+        Long clientId = clientSv.getClientIdByPhone(phoneNumber);
+        String SessionId = "";
+        if(clientId != null) {
+            // 娣诲姞寰俊鐢ㄦ埛璐︽埛璁板綍
+            SeOpenId seOpenId = new SeOpenId();
+            seOpenId.setClientId(clientId);
+            seOpenId.setOpenId(openid);
+            seOpenId.setSessionKey(sessionKey);
+            seOpenId.setCreateTime(new Date());
+            Long rec = clientSv.addOpenId(seOpenId);
+            if(rec != null) {
+                SessionId = String.valueOf(rec);
+            }
+            return BaseResponseUtils.buildSuccess(SessionId);
 
-        // 閲嶇疆鐧诲綍鎬�
-        JSONObject resetUserSessionKey = payHelper.resetUserSessionKey(appid, secret, openid, sessionKey);
-        if(resetUserSessionKey != null) {
-            Integer errcode = checkSessionKey.getInteger("errcode");
-            String errmsg = checkSessionKey.getString("errmsg");
-            String openid_New = checkSessionKey.getString("openid");
-            String sessionKey_New = checkSessionKey.getString("session_key");
+        } else {
+            return BaseResponseUtils.buildError(SellResultCode.PHONE_NUMBER_IS_ERROR.getMessage());
         }
-
-        // 娣诲姞鐧诲綍鎬佽褰�
-        SeWebchatLogonState po = new SeWebchatLogonState();
-        po.setOpenId(openid);
-        po.setSessionKey(sessionKey);
-        Date createTime = new Date();
-        po.setCreateTime(createTime);
-        Long id = paymentSv.insert(po);
-        if(id == null || id <= 0) {
-            return BaseResponseUtils.buildFail("鐧诲綍鎬佽褰曟坊鍔犲け璐�");
-        }
-        String SessionId = String.valueOf(id);
-
-        return BaseResponseUtils.buildSuccess(SessionId) ;
     }
 
     /**
@@ -169,7 +175,8 @@
         String nonceStr = payHelper.generateRandomString();
         Long timestamp = System.currentTimeMillis() / 1000;
 
-        String header = schema + " " + payHelper.getToken(method, httpUrl, "", nonceStr, timestamp, privateCertFileName);
+        byte[] keyPemBs = WxCertUtil.getKey_pemBytes(resourceLoader) ;
+        String header = schema + " " + payHelper.getToken(method, httpUrl, "", nonceStr, timestamp, keyPemBs);
 
         Map<String, String> headers = new HashMap<>();
         headers.put("Authorization", header);
@@ -187,7 +194,7 @@
         // 鏋勯�犻獙绛惧悕涓�
         String signatureStr = payHelper.responseSign(wechatpayTimestamp, wechatpayNonce, job_body.toJSONString());
         // 楠岃瘉绛惧悕
-        Boolean valid = payHelper.responseSignVerify(wechatpaySerial, signatureStr, wechatpaySignature);
+        Boolean valid = payHelper.responseSignVerify(wechatpaySerial, signatureStr, wechatpaySignature, keyPemBs);
 
         return BaseResponseUtils.buildSuccess();
     }
@@ -196,7 +203,7 @@
      * JSAPI涓嬪崟
      * @param order 涓嬪崟璇锋眰瀵硅薄锛屽寘鍚渶瑕佷紶鍏ョ殑鍙傛暟
      * @param bindingResult
-     * @return
+     * @return 棰勬敮浠樹氦鏄撲細璇濇爣璇嗭紙鏈夋晥鏈�2灏忔椂锛�
      */
     @Operation(summary = "JSAPI涓嬪崟", description = "JSAPI涓嬪崟")
     @ApiResponses(value = {
@@ -210,17 +217,18 @@
     @PostMapping(path = "placeOrder")
     @Transactional(rollbackFor = Exception.class)
     @SsoAop()
-    public BaseResponse<Boolean> placeOrder(@RequestBody @Valid DtoOrder order, BindingResult bindingResult) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeySpecException, IOException, SignatureException, InvalidKeyException {
+    public BaseResponse<Boolean> placeOrder(@RequestBody @Valid DtoOrder order, BindingResult bindingResult) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeySpecException, IOException, SignatureException, InvalidKeyException, Exception {
         if(bindingResult != null && bindingResult.hasErrors()){
             return BaseResponseUtils.buildFail(Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage());
         }
-        // 鎺ユ敹鍙傛暟锛氱櫥褰曟�両D銆佸啘鎴稩D銆佽櫄鎷熷崱ID銆佸厖鍊奸噾棰�
-        String sessionId = order.getSessionId();
-        Long virtualId = order.getVirtualId();
+        // 鎺ユ敹鍙傛暟锛氱櫥褰曟�両D銆佽櫄鎷熷崱ID銆佸厖鍊奸噾棰濓紙鍒嗭級
+        Long sessionId = order.getSessionId();
+        Long virtualId = order.getVcId();
         Integer rechargeAmount = order.getRechargeAmount();
 
         String prepayId = "";
-        SeWebchatLogonState po = paymentSv.selectOne(Long.parseLong(sessionId));
+
+        SeOpenId po = paymentSv.selectOne(sessionId);
         String openid = po.getOpenId();
 
         SeVirtualCard seVirtualCard = virtualCardSv.selectVirtuCardById(virtualId);
@@ -253,7 +261,7 @@
 
         //璁㈠崟閲戦
         JSONObject job_amount = new JSONObject();
-        job_amount.put("total", 1);
+        job_amount.put("total", rechargeAmount);
         job_amount.put("currency", "CNY");
         job_body.put("amount", job_amount);
 
@@ -270,35 +278,29 @@
         String httpUrl = "/v3/pay/transactions/jsapi";
 
         String body = job_body.toJSONString();
-        String header = schema + " " + payHelper.getToken(method, httpUrl, body, nonceStr, timestamp, privateCertFileName);
+        String header = schema + " " + payHelper.getToken(method, httpUrl, body, nonceStr, timestamp, WxCertUtil.getKey_pemBytes(resourceLoader));
 
         Map<String, String> headers = new HashMap<>();
         headers.put("Authorization", header);
         headers.put("Accept", "application/json");
         headers.put("Content-Type", "application/json");
 
+        // 鏆傛椂娉ㄩ噴鎺夛紝璁よ瘉閫氳繃鍚庡啀鏀惧紑
         JSONObject job_result = restTemplateUtil.post(PayInfo.orderUrl, body, headers);
-        if(job_result != null) {
-            System.out.println(job_result.toString());
-            prepayId = job_result.getString("prepay_id");
+        if(job_result == null) {
+            return BaseResponseUtils.buildFail(SellResultCode.RECHARGE_ADD_FAIL.getMessage());
         }
 
-        return BaseResponseUtils.buildSuccess(prepayId) ;
+        return BaseResponseUtils.buildSuccess(job_result) ;
     }
 
     /**
-     * 鐢宠閫�娆�
-     * @param po 閫�娆捐姹傚璞�
-     * @param bindingResult
-     * @return
-     * @throws NoSuchPaddingException
-     * @throws NoSuchAlgorithmException
-     * @throws InvalidKeySpecException
-     * @throws IOException
-     * @throws SignatureException
-     * @throws InvalidKeyException
+     * 鍐嶆绛惧悕
+     * @param prepayId 棰勬敮浠樹氦鏄撲細璇濇爣璇�
+     * @return 灏忕▼搴忚皟璧锋敮浠樺弬鏁�
+     * @throws Exception
      */
-    @Operation(summary = "鐢宠閫�娆�", description = "鐢宠閫�娆�")
+    @Operation(summary = "鍐嶆绛惧悕", description = "鍐嶆绛惧悕")
     @ApiResponses(value = {
             @ApiResponse(
                     responseCode = ResultCodeMsg.RsCode.SUCCESS_CODE,
@@ -307,86 +309,33 @@
                             schema = @Schema(implementation = Boolean.class))}
             )
     })
-    @PostMapping(path = "refunds")
+    @GetMapping(path = "/signAgain")
     @Transactional(rollbackFor = Exception.class)
     @SsoAop()
-    public BaseResponse<Boolean> refunds(@RequestBody @Valid Refund po, BindingResult bindingResult) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeySpecException, IOException, SignatureException, InvalidKeyException {
-        if(bindingResult != null && bindingResult.hasErrors()){
-            return BaseResponseUtils.buildFail(Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage());
-        }
+    public BaseResponse<JSONObject> signAgain(@RequestParam("prepayId") String prepayId) throws Exception {
 
-        /**
-         * 1. 鍒ゆ柇浜ゆ槗鏃堕棿鏄惁瓒呰繃涓�骞�
-         * 2. 鍒ゆ柇閫�娆炬�婚噾棰濇槸鍚﹁秴杩囪鍗曢噾棰�
-         * 3. 鍒ゆ柇褰撳墠璁㈠崟閫�娆炬鏁版槸鍚﹁秴杩�50娆�
-         * 4. 鍒ゆ柇涓庤璁㈠崟涓婃閫�娆炬槸鍚︾浉闅�1鍒嗛挓
-         */
-
-        String tradeNo = po.getTradeNo();
-        String refundNo = po.getRefundNo();
-        Integer refund = po.getRefund();
-        if(refundNo == null || refundNo.length() <= 0) {
-            // 鏂版彁閫�娆剧敵璇凤紝鐢熸垚閫�娆惧崟鍙�
-            //refundNo = generateRefundNo(tradeNo);
-        }
-
-        // 鏍规嵁璁㈠崟鍙疯幏鍙栨�绘敮浠橀噾棰濆拰鎬婚��娆鹃噾棰�
-        Integer totalTradeAmount = 0;
-        Integer totalRefundAmount = 0;
-        //Integer totalTradeAmount = getTotalTradeAmount(tradeNo);
-        //Integer totalRefundAmount = getTotalRefundAmount(tradeNo);
-        if(totalRefundAmount > totalTradeAmount) {
-            return BaseResponseUtils.buildFail(SellResultCode.TOTAL_REFUND_EXCEED_TRADE.getMessage());
-        }
-
-        // 鐢熸垚body
-        RefundRequest.Amount amount = new RefundRequest.Amount();
-        amount.setRefund(refund);
-        amount.setTotal(totalTradeAmount);
-        amount.setCurrency("CNY");
-
-        RefundRequest refundRequest = new RefundRequest();
-        refundRequest.setOut_trade_no(tradeNo);
-        refundRequest.setOut_refund_no(refundNo);
-        refundRequest.setNotify_url(notifyUrl);
-        refundRequest.setAmount(amount);
-
-        // 鐢熸垚header
+        // 鑾峰彇闅忔満涓插拰鏃堕棿鎴筹紝鏀惧湪姝ゅ浠ヤ繚璇�
+        String appid = PayInfo.appid;
+        String timeStamp = String.valueOf(System.currentTimeMillis() / 1000);
         String nonceStr = payHelper.generateRandomString();
-        Long timestamp = System.currentTimeMillis() / 1000;
+        String pkg = "prepay_id=" + prepayId;
+        String message = payHelper.buildMessage_signAgain(appid, timeStamp, nonceStr, pkg);
+        String paySign = payHelper.sign(message.getBytes("utf-8"), WxCertUtil.getKey_pemBytes(resourceLoader));
 
-        String method = "POST";
-        String httpUrl = "/v3/refund/domestic/refunds";
+        JSONObject job_result = new JSONObject();
+        job_result.put("timeStamp", timeStamp);
+        job_result.put("nonceStr", nonceStr);
+        job_result.put("package", pkg);
+        job_result.put("signType", signType);
+        job_result.put("paySign", paySign);
 
-        String body = JSONObject.toJSONString(refundRequest);
-        String header = schema + " " + payHelper.getToken(method, httpUrl, body, nonceStr, timestamp, privateCertFileName);
-
-        Map<String, String> headers = new HashMap<>();
-        headers.put("Authorization", header);
-        headers.put("Accept", "application/json");
-        headers.put("Content-Type", "application/json");
-
-        JSONObject job_refundResponse = restTemplateUtil.post(PayInfo.orderUrl, body, headers);
-        RefundResponse refundResponse = JSON.parseObject(job_refundResponse.toJSONString(), RefundResponse.class);
-
-        String status = refundResponse.getStatus();
-        if(status != null && status.equals("SUCCESS")) {
-            // 閫�娆剧敵璇峰凡鍙楃悊
-            return BaseResponseUtils.buildSuccess(true) ;
-        } else if(status != null && status.equals("PROCESSING")) {
-            // 閫�娆惧鐞嗕腑
-            return BaseResponseUtils.buildFail(SellResultCode.PROCESSING.getMessage());
-        } else {
-            // 閫�娆惧紓甯�
-            return BaseResponseUtils.buildError(SellResultCode.ABNORMAL.getMessage());
-        }
-
+        return BaseResponseUtils.buildSuccess(job_result) ;
     }
 
     /**
      * 鏀粯閫氱煡/閫�娆剧粨鏋滈�氱煡
      * @param headers
-     * @param orderNotify
+     * @param request
      * @param response
      * @return
      * @throws IOException
@@ -404,12 +353,12 @@
     @PostMapping(path = "orderNotify", consumes = MediaType.APPLICATION_JSON_VALUE)
     @Transactional(rollbackFor = Exception.class)
     @SsoAop()
-    public JSONObject orderNotify(@RequestHeader HttpHeaders headers, @RequestBody OrderNotify orderNotify, HttpServletResponse response) throws IOException, GeneralSecurityException {
+    public JSONObject orderNotify(@RequestHeader HttpHeaders headers, HttpServletRequest request, HttpServletResponse response) throws IOException, GeneralSecurityException, Exception {
         JSONObject result = new JSONObject();
 
         /**
          * 1.楠岀澶勭悊
-         *      浠巋eader涓彇鍑�4涓瓙鍙傛暟锛屽悓鏃跺彇鍑篵ody
+         *      浠巋eader涓彇鍑�4涓瓙鍙傛暟
          *      楠屾椂闂村樊锛岃秴杩�5鍒嗛挓鐨勪笉澶勭悊
          *      楠岃瘉绛惧悕
          *      楠岃瘉涔﹀簭鍒楀彿锛屽繀椤讳笌鏌愪竴涓瘉涔︾殑搴忓垪鍙蜂竴鑷�
@@ -418,7 +367,18 @@
         String wechatpaySerial = String.valueOf(headers.get("Wechatpay-Serial").get(0));
         String wechatpaySignature = String.valueOf(headers.get("Wechatpay-Signature").get(0));
         String wechatpayTimestamp = String.valueOf(headers.get("Wechatpay-Timestamp").get(0));
-        String bodyStr = JSONObject.toJSONString(orderNotify);
+
+        // 鑾峰彇body鍐呭
+        BufferedReader reader = request.getReader();
+        StringBuilder stringBuilder = new StringBuilder();
+        String line;
+        while ((line = reader.readLine()) != null) {
+            stringBuilder.append(line);
+        }
+        String bodyStr = stringBuilder.toString();
+
+        // body杞璞�
+        OrderNotify orderNotify = JSON.parseObject(bodyStr, OrderNotify.class);
 
         // 楠屾椂闂存埑锛屾椂闂村樊澶т簬5鍒嗛挓鐨勬嫆缁�
         Long timeDiff = (System.currentTimeMillis() / 1000 - Long.parseLong(wechatpayTimestamp))/60;
@@ -431,8 +391,9 @@
 
         // 鏋勯�犻獙绛惧悕涓�
         String signatureStr = payHelper.responseSign(wechatpayTimestamp, wechatpayNonce, bodyStr);
+        byte[] keyPemBs = WxCertUtil.getKey_pemBytes(resourceLoader) ;
         // 楠岃瘉绛惧悕
-        Boolean valid = payHelper.responseSignVerify(wechatpaySerial, signatureStr, wechatpaySignature);
+        Boolean valid = payHelper.responseSignVerify(wechatpaySerial, signatureStr, wechatpaySignature, keyPemBs);
         if(!valid) {
             response.setStatus(500);
             result.put("code", "FAIL");
@@ -454,10 +415,7 @@
             return result;
         }
 
-        /**
-         * 瑙e瘑澶勭悊
-         *      1
-         */
+        // 瑙e瘑澶勭悊
         String eventType = orderNotify.getEvent_type();
 
         if(eventType != null && eventType.equals("TRANSACTION.SUCCESS")) {
@@ -467,7 +425,39 @@
              * 鍙栧嚭閫氱煡鏁版嵁瀵硅薄锛岀户鑰屽彇鍑鸿В瀵嗘墍闇�鐨刟ssociatedData鍜宯once锛屼互鍙婂瘑鏂嘽iphertext
              * 瑙e瘑ciphertext寰楀埌
              */
-            OrderNotify.NotifyResource notifyResource = orderNotify.getResource();
+            NotifyResource notifyResource = orderNotify.getResource();
+            String associatedData = notifyResource.getAssociated_data();
+            String nonce = notifyResource.getNonce();
+            String ciphertext = notifyResource.getCiphertext();
+
+            String resource = AesUtil.decryptToString(PayInfo.key.getBytes("utf-8"), associatedData.getBytes("utf-8"), nonce.getBytes("utf-8"), ciphertext);
+            JSONObject job_resource = JSONObject.parseObject(resource);
+
+            // 瑙e瘑鍚庡彇鍑猴細鍟嗘埛璁㈠崟鍙枫�佸井淇℃敮浠樿鍗曞彿銆佷氦鏄撶姸鎬併�佹敮浠樺畬鎴愭椂闂�
+            String out_trade_no = job_resource.getString("out_trade_no");
+            String transaction_id = job_resource.getString("transaction_id");
+            String trade_state = job_resource.getString("trade_state");
+            Date success_time = job_resource.getDate("success_time");
+
+            // 濡傛灉褰撳墠璁㈠崟鐘舵�佷负鏈敮浠樼姸鎬侊紝鍒欐洿鏂拌櫄鎷熷崱琛ㄥ強鍏呭�艰〃鍝嶅簲瀛楁
+            SeVcRecharge seVcRecharge = virtualCardSv.getVCRechargeByorderNumber(out_trade_no);
+            if(seVcRecharge != null && seVcRecharge.getOrderState() == 1) {
+                BaseResponse result_ = virtualCardSv.updateVCRecharge(out_trade_no, success_time);
+                if(!result_.getCode().equals("0001")) {
+                    response.setStatus(500);
+                    result.put("code", "FAIL");
+                    result.put("message", "澶辫触");
+                    return result;
+                }
+            }
+        } else if(eventType != null && eventType.equals("REFUND.SUCCESS")) {
+            // 閫�娆炬垚鍔熷悗鍥炶皟
+            /**
+             * 閫�娆炬垚鍔熺殑鍥炶皟
+             * 鍙栧嚭閫氱煡鏁版嵁瀵硅薄锛岀户鑰屽彇鍑鸿В瀵嗘墍闇�鐨刟ssociatedData鍜宯once锛屼互鍙婂瘑鏂嘽iphertext
+             * 瑙e瘑ciphertext寰楀埌
+             */
+            NotifyResource notifyResource = orderNotify.getResource();
             String associatedData = notifyResource.getAssociated_data();
             String nonce = notifyResource.getNonce();
             String ciphertext = notifyResource.getCiphertext();
@@ -478,20 +468,52 @@
             // 瑙e瘑鍚庡彇鍑猴細鍟嗘埛璁㈠崟鍛樸�佸井淇℃敮浠樿鍗曞彿銆佷氦鏄撶姸鎬併�佹敮浠樺畬鎴愭椂闂�
             String out_trade_no = job_resource.getString("out_trade_no");
             String transaction_id = job_resource.getString("transaction_id");
-            String trade_state = job_resource.getString("trade_state");
+            String out_refund_no = job_resource.getString("out_refund_no");
+            String refund_status = job_resource.getString("refund_status");
             Date success_time = job_resource.getDate("success_time");
-
-            // 鏇存柊铏氭嫙鍗¤〃鍙婂厖鍊艰〃鍝嶅簲瀛楁
-            BaseResponse result_ = virtualCardSv.updateVCRecharge(out_trade_no, success_time);
-            if(!result_.getCode().equals("0001")) {
+            if(!refund_status.equals("SUCCESS")) {
                 response.setStatus(500);
                 result.put("code", "FAIL");
                 result.put("message", "澶辫触");
                 return result;
             }
-        } else if(eventType != null && eventType.equals("REFUND.SUCCESS")) {
-            // 閫�娆炬垚鍔熷悗鍥炶皟
 
+            // 鏇存柊铏氭嫙鍗¤〃鍙婂厖鍊艰〃鍝嶅簲瀛楁
+            SeVcRefundItem seVcRefundItem = new SeVcRefundItem();
+            seVcRefundItem.setRefundTime(success_time);
+            seVcRefundItem.setRefundStatus(RefundItemStateENUM.REFUNDED.getCode());
+            Integer rec = virtualCardSv.updateRefundItem(seVcRefundItem);
+            if(rec == null && rec <= 0) {
+                response.setStatus(500);
+                result.put("code", "FAIL");
+                result.put("message", "澶辫触");
+                return result;
+            }
+
+            // 鏍规嵁閫�娆惧崟鍙峰弽鏌ラ��娆綢D锛屾牴鎹��娆綢D鑾峰彇閫�娆剧姸鎬佹槸鏈��娆剧殑璁板綍鏁伴噺锛屽鏋滄槸0鍒欒鏄庡叏閮ㄩ��娆惧畬鎴愶紝鏇存柊閫�娆捐〃鐘舵�佷负宸查��娆撅紝灏嗛��娆惧悗閲戦鏇存柊鍒拌櫄鎷熷崱琛�
+            /**
+             * 鏍规嵁閫�娆鹃�氱煡鎺ュ彛杩斿洖鐨勯��娆惧崟鍙峰弽鏌ラ��娆綢D锛屾煡璇㈣閫�娆綢D涓嬫湭閫�娆捐褰曟暟閲�
+             *      濡傛灉缁撴灉涓�0锛屽垯璇ラ��娆惧凡缁忓畬鎴�
+             *      1. 鏇存柊閫�娆捐〃鐘舵�佷负宸查��娆�
+             *      2. 灏嗛��娆惧悗浣欓鏇存柊鍒拌櫄鎷熷崱琛ㄤ腑
+             */
+            Integer noRefundedCount = virtualCardSv.getNoRefundedCount(out_refund_no);
+            if(noRefundedCount != null && noRefundedCount == 0) {
+                // 鑾峰彇閫�娆惧璞″苟淇敼閫�娆剧姸鎬�
+                Long refundId = virtualCardSv.getRefundIdByRefundNumber(out_refund_no);
+                SeVcRefund seVcRefund = virtualCardSv.selectRefundByRefundId(refundId);
+                seVcRefund.setRefundStatus(RefundStatusENUM.REFUNDED.getCode());
+                virtualCardSv.updateRefund(seVcRefund);
+
+                // 鑾峰彇铏氭嫙鍗″璞″苟淇敼浣欓銆佹渶鍚庢搷浣溿�佹渶鍚庢搷浣滄椂闂�
+                Long vcId = seVcRefund.getVcId();
+                Double afterRefund = seVcRefund.getAfterRefund();
+                SeVirtualCard seVirtualCard = virtualCardSv.selectVirtuCardById(vcId);
+                seVirtualCard.setMoney(afterRefund);
+                seVirtualCard.setLastOperate(LastOperateENUM.REFUND.getCode());
+                seVirtualCard.setLastOperateTime(new Date());
+                virtualCardSv.updateVirtualCard(seVirtualCard);
+            }
         }
 
         // 閫氱煡搴旂瓟
@@ -499,43 +521,5 @@
         result.put("code", "SUCCESS");
         result.put("message", "鎴愬姛");
         return  result;
-    }
-
-    /**
-     * 鍐嶆绛惧悕
-     * @param prepayId 棰勬敮浠樹氦鏄撲細璇濇爣璇�
-     * @return 灏忕▼搴忚皟璧锋敮浠樺弬鏁�
-     * @throws Exception
-     */
-    @Operation(summary = "鍐嶆绛惧悕", description = "鍐嶆绛惧悕")
-    @ApiResponses(value = {
-            @ApiResponse(
-                    responseCode = ResultCodeMsg.RsCode.SUCCESS_CODE,
-                    description = "鎿嶄綔缁撴灉锛歵rue锛氭垚鍔燂紝false锛氬け璐ワ紙BaseResponse.content锛�",
-                    content = {@Content(mediaType = MediaType.APPLICATION_JSON_VALUE,
-                            schema = @Schema(implementation = Boolean.class))}
-            )
-    })
-    @GetMapping(path = "/signAgain")
-    @Transactional(rollbackFor = Exception.class)
-    @SsoAop()
-    public BaseResponse<JSONObject> signAgain(@RequestParam("prepayId")  String prepayId) throws Exception {
-
-        // 鑾峰彇闅忔満涓插拰鏃堕棿鎴筹紝鏀惧湪姝ゅ浠ヤ繚璇�
-        String appid = PayInfo.appid;
-        String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
-        String nonceStr = payHelper.generateRandomString();
-        String pkg = "prepay_id=" + prepayId;
-        String message = payHelper.buildMessage_signAgain(appid, timestamp, nonceStr, pkg);
-        String paySign = payHelper.sign(message.getBytes("utf-8"), privateCertFileName);
-
-        JSONObject job_result = new JSONObject();
-        job_result.put("timestamp", timestamp);
-        job_result.put("nonceStr", nonceStr);
-        job_result.put("package", pkg);
-        job_result.put("signType", signType);
-        job_result.put("paySign", paySign);
-
-        return BaseResponseUtils.buildSuccess(job_result) ;
     }
 }

--
Gitblit v1.8.0