Bladeren bron

改动过的

huanglizhi 1 jaar geleden
bovenliggende
commit
41baa43a26

+ 1 - 1
module-erp/src/main/java/com/hys/app/controller/erp/use/KdnController.java

@@ -112,7 +112,7 @@ public class KdnController {
         return response;
     }
 
-    @GetMapping("/returnBack/abc")
+    @PostMapping("/cancelKdn/abc")
     public String abc() {
         return "请求成功了";
     }

+ 23 - 7
module-erp/src/main/java/com/hys/app/controller/erp/use/PayController.java

@@ -7,6 +7,7 @@ import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
 import com.github.binarywang.wxpay.exception.WxPayException;
 import com.github.binarywang.wxpay.service.impl.WxPayServiceImpl;
 import com.hys.app.framework.exception.ServiceException;
+import com.hys.app.framework.util.ScriptUtil;
 import com.hys.app.model.erp.dos.OrderCustomerFee;
 import com.hys.app.model.erp.dos.OrderDO;
 import com.hys.app.model.erp.dto.PayTypeUrl;
@@ -18,10 +19,14 @@ import com.hys.app.service.erp.OrderManager;
 import io.swagger.annotations.Api;
 import io.swagger.annotations.ApiOperation;
 import lombok.AllArgsConstructor;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 import org.springframework.validation.annotation.Validated;
 import org.springframework.web.bind.annotation.*;
 
 import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpSession;
+import java.io.UnsupportedEncodingException;
 import java.math.BigDecimal;
 import java.net.UnknownHostException;
 import java.time.LocalDateTime;
@@ -40,6 +45,8 @@ public class PayController {
     private WxPayServiceMy wxPayServiceMy;
     private OrderCustomerFeeManager orderCustomerFeeManager;
 
+    private static final Logger log = LoggerFactory.getLogger(ScriptUtil.class);
+
 
     @ApiOperation(value = "扫描完获取拉起支付的url")
     @PostMapping("/getPayUrl")
@@ -50,6 +57,7 @@ public class PayController {
         }
         PayOrder payOrder = new PayOrder();
         payOrder.setTraceNo(aDo.getId().toString());
+        payOrder.setOpenId(aDo.getOpenId());
 
         payOrder.setSubject("订单支付金额");
         payOrder.setTimeExpire(LocalDateTime.now().plusMinutes(30));
@@ -109,13 +117,21 @@ public class PayController {
         return "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[解析失败]]></return_msg></xml>";
     }
 
-    @GetMapping("getopenId")
-    public String getopenId() {
-        String appId = "wx51e98f2dee35237d";
-        String secret = "13803c1b0d911e023c7da0b300cbce89";
+    @GetMapping("getOpenIdCode/{orderId}")
+    public String getOpenIdCode(@PathVariable Long orderId) throws UnsupportedEncodingException {
+        return wxPayServiceMy.getOpenIdCode(orderId);
+    }
 
-        String accessToken = WxPayServiceMy.getAccessToken(appId, secret);
-        String openId = WxPayServiceMy.getOpenId(accessToken);
-        return openId;
+    @GetMapping("/weixin/callback/openidCode")
+    public void handleWeixinCallback(@RequestParam("code") String code, @RequestParam("state") String state, HttpSession session) {
+        if (!state.equals((String) session.getAttribute("WEIXIN_OAUTH_STATE"))) {
+            log.error("用户授权,state错误");
+        }
+        OrderDO aDo = orderManager.getById(state);
+        if (ObjectUtil.isNull(aDo)) {
+            log.error("用户授权完成后未找到订单信息:" + state);
+        }
+        aDo.setOpenId(wxPayServiceMy.getOpenId(code));
+        orderManager.updateById(aDo);
     }
 }

+ 51 - 0
module-erp/src/main/java/com/hys/app/controller/erp/use/WeixinController.java

@@ -0,0 +1,51 @@
+package com.hys.app.controller.erp.use;
+
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.bind.annotation.RestController;
+import java.security.MessageDigest;
+import java.util.Arrays;
+
+@RestController
+public class WeixinController {
+
+    private static final String TOKEN = "ryks2023weixin";  // 替换为您在微信公众平台设置的Token
+
+    @GetMapping("/weixin")
+    public String validateWeixinToken(
+            @RequestParam("signature") String signature,
+            @RequestParam("timestamp") String timestamp,
+            @RequestParam("nonce") String nonce,
+            @RequestParam("echostr") String echostr) {
+
+        String[] arr = {TOKEN, timestamp, nonce};
+        Arrays.sort(arr);
+        StringBuilder content = new StringBuilder();
+        for (String str : arr) {
+            content.append(str);
+        }
+
+        String generatedSignature = sha1(content.toString());
+
+        if (generatedSignature.equals(signature)) {
+            return echostr;
+        } else {
+            return "Failed to verify";
+        }
+    }
+
+    private String sha1(String data) {
+        try {
+            MessageDigest md = MessageDigest.getInstance("SHA-1");
+            md.update(data.getBytes());
+            byte[] bytes = md.digest();
+            StringBuilder sb = new StringBuilder();
+            for (byte b : bytes) {
+                sb.append(String.format("%02x", b));
+            }
+            return sb.toString();
+        } catch (Exception e) {
+            return "";
+        }
+    }
+}

+ 1 - 0
module-erp/src/main/java/com/hys/app/framework/security/AdminAccessDecisionManager.java

@@ -46,6 +46,7 @@ public class AdminAccessDecisionManager implements org.springframework.security.
         result = result || matcher.match("/admin/erp/kdn/returnBack/**", url);
         result = result || matcher.match("/admin/erp/scancode/**", url);
         result = result || matcher.match("/admin/erp/pay/**", url);
+        result = result || matcher.match("/weixin", url);
         if (result) {
             return;
         }

+ 2 - 0
module-erp/src/main/java/com/hys/app/model/erp/dos/OrderDO.java

@@ -198,4 +198,6 @@ public class OrderDO extends BaseDO {
      * 税率
      */
     private Integer  taxRate;
+
+    private String openId;
 }

+ 2 - 0
module-erp/src/main/java/com/hys/app/pay/ali/PayOrder.java

@@ -19,4 +19,6 @@ public class PayOrder {
 
     private LocalDateTime timeExpire;//绝对超时时间
 
+    private String openId;
+
 }

+ 4 - 1
module-erp/src/main/java/com/hys/app/pay/wx/WxConfig.java

@@ -26,5 +26,8 @@ public class WxConfig {
     private String notifyUrl;
     @Value("${wxpay.subMchId}")
     private String subMchId;
-
+    @Value("${wxpay.secret}")
+    private String secret;
+    @Value("${wxpay.oAuth2Url}")
+    private String oAuth2Url;
 }

+ 21 - 39
module-erp/src/main/java/com/hys/app/pay/wx/WxPayServiceMy.java

@@ -13,6 +13,7 @@ import com.github.binarywang.wxpay.service.WxPayService;
 import com.github.binarywang.wxpay.service.impl.WxPayServiceImpl;
 import com.github.binarywang.wxpay.util.SignUtils;
 import com.hys.app.framework.database.annotation.Id;
+import com.hys.app.framework.exception.ServiceException;
 import com.hys.app.framework.util.JsonUtil;
 import com.hys.app.pay.ali.PayOrder;
 import org.springframework.http.HttpStatus;
@@ -22,13 +23,13 @@ import org.springframework.web.bind.annotation.GetMapping;
 import org.springframework.web.bind.annotation.RequestParam;
 
 import javax.annotation.Resource;
+import javax.servlet.http.HttpSession;
 import java.io.BufferedReader;
 import java.io.IOException;
 import java.io.InputStreamReader;
-import java.net.HttpURLConnection;
-import java.net.InetAddress;
-import java.net.URL;
-import java.net.UnknownHostException;
+import java.io.UnsupportedEncodingException;
+import java.net.*;
+import java.nio.charset.StandardCharsets;
 import java.util.Base64;
 import java.util.HashMap;
 import java.util.LinkedHashMap;
@@ -57,6 +58,7 @@ public class WxPayServiceMy {
 
         WxPayUnifiedOrderRequest orderRequest = WxPayUnifiedOrderRequest.newBuilder()
                 .body(payOrder.getSubject())
+                .openid(payOrder.getOpenId())
                 .outTradeNo(payOrder.getTraceNo())
                 .totalFee((int) Math.round(payOrder.getTotalAmount() * 100)) // 单位是分
                 .spbillCreateIp(InetAddress.getLocalHost().getHostAddress())
@@ -83,55 +85,35 @@ public class WxPayServiceMy {
         }
     }
 
-    public static String getAccessToken(String appId, String secret) {
-        String accessToken = "";
-        try {
-            String authString = appId + ":" + secret;
-            byte[] authEncBytes = Base64.getEncoder().encode(authString.getBytes());
-            String authStringEnc = new String(authEncBytes);
-
-            URL url = new URL("https://api.weixin.qq.com/sns/oauth2/access_token");
-            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
-            connection.setRequestMethod("POST");
-            connection.setRequestProperty("Authorization", "Basic " + authStringEnc);
-
-            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
-            String inputLine;
-            StringBuffer response = new StringBuffer();
-
-            while ((inputLine = in.readLine()) != null) {
-                response.append(inputLine);
-            }
-            in.close();
-
-            accessToken = response.toString();
-        } catch (Exception e) {
-            e.printStackTrace();
-        }
+    public String getOpenIdCode(Long orderId) throws UnsupportedEncodingException {
+       return String.format("https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=%s&state=%s#wechat_redirect",
+                wxConfig.getAppId(), URLEncoder.encode(wxConfig.getOAuth2Url(), "UTF-8"), "snsapi_base", orderId);
 
-        return accessToken;
     }
 
-    public static String getOpenId(String accessToken) {
-        String openId = "";
+    public String getOpenId(String code) {
+
+        String urlString = String.format(
+                "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code",
+                wxConfig.getAppId(), wxConfig.getSecret(), code);
         try {
-            URL url = new URL("https://api.weixin.qq.com/sns/oauth2/access_token"+accessToken);
-                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
+            URL url = new URL(urlString);
+            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
             connection.setRequestMethod("GET");
 
-            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
+            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
+            StringBuilder response = new StringBuilder();
             String inputLine;
-            StringBuffer response = new StringBuffer();
 
             while ((inputLine = in.readLine()) != null) {
                 response.append(inputLine);
             }
             in.close();
-            LinkedHashMap<String, Object> map = JsonUtil.toMap(response.toString());
-            openId = map.get("openid").toString();
+            Map<String, Object> map = JsonUtil.toMap(response.toString());
+            return map.get("openid").toString();
         } catch (Exception e) {
             e.printStackTrace();
+            return null;  // 或者处理错误
         }
-        return openId;
     }
 }

+ 2 - 1
server/src/main/resources/application-local.yml

@@ -86,4 +86,5 @@ wxpay:
   apiV3Key: tt9teerjiwer930i4t54u5894irhjehf
   notifyUrl: http://529920wmvp80.vicp.fun:52722/admin/erp/pay/wxpay/notify
   subMchId: 1639506733
-
+  secret: 13803c1b0d911e023c7da0b300cbce89
+  oAuth2Url: http://app.raycos.com.cn

+ 3 - 1
server/src/main/resources/application-prod.yml

@@ -84,4 +84,6 @@ wxpay:
   keyPath: /apiclient_cert.p12
   apiV3Key: tt9teerjiwer930i4t54u5894irhjehf
   notifyUrl: https://apidoc.raycos.net/admin/erp/pay/wxpay/notify
-  subMchId: 1648546606
+  subMchId: 1648546606
+  secret: 13803c1b0d911e023c7da0b300cbce89
+  oAuth2Url:

+ 2 - 2
server/src/main/resources/application.yml

@@ -1,10 +1,10 @@
 server:
-  port: 9999
+  port: 8080
 spring:
   application:
     name: erp-server
   profiles:
-    active: prod
+    active: local
   jackson:
     property-naming-strategy: SNAKE_CASE
   servlet: