From f2e8f0ae62eea8a81f035b67bc6c965a959b8e73 Mon Sep 17 00:00:00 2001
From: wuzeyu <1223318623@qq.com>
Date: 星期五, 14 六月 2024 10:49:59 +0800
Subject: [PATCH] 修改 充值接口 返回充值ID作为订单号

---
 pipIrr-platform/pipIrr-web/pipIrr-web-sell/src/main/java/com/dy/pipIrrSell/wechatpay/PaymentCtrl.java |  190 ++++++++++++++++++-----------------------------
 1 files changed, 74 insertions(+), 116 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 48e0a35..2d237fa 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
@@ -1,5 +1,6 @@
 package com.dy.pipIrrSell.wechatpay;
 
+import com.alibaba.fastjson2.JSON;
 import com.alibaba.fastjson2.JSONObject;
 import com.dy.common.aop.SsoAop;
 import com.dy.common.webUtil.BaseResponse;
@@ -17,8 +18,8 @@
 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;
@@ -26,6 +27,7 @@
 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;
@@ -37,6 +39,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;
@@ -80,60 +83,6 @@
 
     // 骞冲彴璇佷功鍏挜
     private final Map CERTIFICATE_MAP = new HashMap();
-
-    /**
-     * 鐧诲綍鍑瘉鏍¢獙
-     * @param code2Session 鐧诲綍鍑瘉鏍¢獙浼犲叆瀵硅薄
-     * @param bindingResult
-     * @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))}
-            )
-    })
-    @PostMapping(path = "getSessionId")
-    @Transactional(rollbackFor = Exception.class)
-    @SsoAop()
-    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());
-        }
-
-        Map<String, Object> queryParams = new HashMap<>();
-        queryParams.put("appid", appid);
-        queryParams.put("secret", code2Session.getSecret());
-        queryParams.put("js_code", code2Session.getJs_code());
-        queryParams.put("grant_type", grantType);
-        Map<String, String> headerParams = new HashMap<>();
-        JSONObject job = restTemplateUtil.get(loginUrl, queryParams, headerParams);
-
-        if(job.getLong("errcode") != null && job.getLong("errcode") >= -1) {
-            return BaseResponseUtils.buildFail("鐧诲綍鍑瘉鏍¢獙澶辫触");
-        }
-
-        String openid = job.getString("openid");
-        String sessionKey = job.getString("session_key");
-
-        // 娣诲姞鐧诲綍鎬佽褰�
-        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) ;
-    }
 
     /**
      * 涓嬭浇寰俊鏀粯骞冲彴璇佷功 娴嬭瘯瀹屽簾闄�
@@ -203,14 +152,12 @@
         if(bindingResult != null && bindingResult.hasErrors()){
             return BaseResponseUtils.buildFail(Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage());
         }
-        // 鎺ユ敹鍙傛暟锛氱櫥褰曟�両D銆佸啘鎴稩D銆佽櫄鎷熷崱ID銆佸厖鍊奸噾棰�
+        // 鎺ユ敹鍙傛暟锛氱櫥褰曟�両D銆佽櫄鎷熷崱ID銆佸厖鍊奸噾棰濓紙鍒嗭級
         Long sessionId = order.getSessionId();
-        Long virtualId = order.getVirtualId();
+        Long virtualId = order.getVcId();
         Integer rechargeAmount = order.getRechargeAmount();
 
         String prepayId = "";
-        //SeWebchatLogonState po = paymentSv.selectOne(Long.parseLong(sessionId));
-        //String openid = po.getOpenId();
 
         SeOpenId po = paymentSv.selectOne(sessionId);
         String openid = po.getOpenId();
@@ -245,7 +192,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);
 
@@ -278,9 +225,47 @@
     }
 
     /**
+     * 鍐嶆绛惧悕
+     * @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) ;
+    }
+
+    /**
      * 鏀粯閫氱煡/閫�娆剧粨鏋滈�氱煡
      * @param headers
-     * @param orderNotify
+     * @param request
      * @param response
      * @return
      * @throws IOException
@@ -298,12 +283,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 {
         JSONObject result = new JSONObject();
 
         /**
          * 1.楠岀澶勭悊
-         *      浠巋eader涓彇鍑�4涓瓙鍙傛暟锛屽悓鏃跺彇鍑篵ody
+         *      浠巋eader涓彇鍑�4涓瓙鍙傛暟
          *      楠屾椂闂村樊锛岃秴杩�5鍒嗛挓鐨勪笉澶勭悊
          *      楠岃瘉绛惧悕
          *      楠岃瘉涔﹀簭鍒楀彿锛屽繀椤讳笌鏌愪竴涓瘉涔︾殑搴忓垪鍙蜂竴鑷�
@@ -312,7 +297,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;
@@ -348,10 +344,7 @@
             return result;
         }
 
-        /**
-         * 瑙e瘑澶勭悊
-         *      1
-         */
+        // 瑙e瘑澶勭悊
         String eventType = orderNotify.getEvent_type();
 
         if(eventType != null && eventType.equals("TRANSACTION.SUCCESS")) {
@@ -361,7 +354,7 @@
              * 鍙栧嚭閫氱煡鏁版嵁瀵硅薄锛岀户鑰屽彇鍑鸿В瀵嗘墍闇�鐨刟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();
@@ -369,19 +362,22 @@
             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瘑鍚庡彇鍑猴細鍟嗘埛璁㈠崟鍛樸�佸井淇℃敮浠樿鍗曞彿銆佷氦鏄撶姸鎬併�佹敮浠樺畬鎴愭椂闂�
+            // 瑙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");
 
-            // 鏇存柊铏氭嫙鍗¤〃鍙婂厖鍊艰〃鍝嶅簲瀛楁
-            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;
+            // 濡傛灉褰撳墠璁㈠崟鐘舵�佷负鏈敮浠樼姸鎬侊紝鍒欐洿鏂拌櫄鎷熷崱琛ㄥ強鍏呭�艰〃鍝嶅簲瀛楁
+            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")) {
             // 閫�娆炬垚鍔熷悗鍥炶皟
@@ -390,7 +386,7 @@
              * 鍙栧嚭閫氱煡鏁版嵁瀵硅薄锛岀户鑰屽彇鍑鸿В瀵嗘墍闇�鐨刟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();
@@ -454,43 +450,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