姜永辉 2 лет назад
Родитель
Сommit
6018d5c1bd

+ 10 - 0
pom.xml

@@ -132,6 +132,16 @@
             <artifactId>shiro-ehcache</artifactId>
             <version>${spring.shiro.version}</version>
         </dependency>
+        <dependency>
+            <groupId>com.github.binarywang</groupId>
+            <artifactId>weixin-java-pay</artifactId>
+            <version>4.4.0</version>
+        </dependency>
+        <dependency>
+            <groupId>com.github.binarywang</groupId>
+            <artifactId>weixin-java-miniapp</artifactId>
+            <version>4.4.0</version>
+        </dependency>
     </dependencies>
 
     <build>

+ 53 - 0
src/main/java/com/dk/oauth/config/WechatPayConfigInfo.java

@@ -0,0 +1,53 @@
+package com.dk.oauth.config;
+
+import lombok.Getter;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.context.annotation.Configuration;
+
+/**
+ * @author : 姜永辉
+ * @desc : 微信支付配置信息
+ * @date : 2022-7-7 19:49
+ */
+@Getter
+@Configuration
+public class WechatPayConfigInfo {
+
+    /**
+     * 小程序appid
+     */
+    @Value("${wx.pay.appId}")
+    private String appId;
+
+    /**
+     * 安全码
+     */
+    @Value("${wx.pay.appSecret}")
+    private String appSecret;
+
+    /**
+     * 支付商户号
+     */
+    @Value("${wx.pay.mchId}")
+    private String mchId;
+
+    /**
+     * 支付密钥
+     */
+    @Value("${wx.pay.mchKey}")
+    private String mchKey;
+
+    /**
+     * 证书路径
+     */
+    @Value("${wx.pay.keyPath}")
+    private String keyPath;
+
+    /**
+     * 小程序支付的回调接口地址
+     */
+    @Value("${wx.pay.wechatNotifyUrl}")
+    private String wechatNotifyUrl;
+
+
+}

+ 91 - 0
src/main/java/com/dk/oauth/controller/wxapi/basic/WechatPayController.java

@@ -0,0 +1,91 @@
+package com.dk.oauth.controller.wxapi.basic;
+
+import com.alibaba.fastjson.JSONObject;
+import com.dk.common.response.ResponseResultVO;
+import com.dk.oauth.service.wxapi.basic.WechatPayService;
+import com.github.binarywang.wxpay.bean.notify.WxPayNotifyResponse;
+import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
+import com.github.binarywang.wxpay.exception.WxPayException;
+import com.github.binarywang.wxpay.service.WxPayService;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiImplicitParam;
+import io.swagger.annotations.ApiImplicitParams;
+import io.swagger.annotations.ApiOperation;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.web.bind.annotation.*;
+
+import javax.annotation.Resource;
+import java.util.Map;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+
+
+/**
+ * @author : admin
+ * @desc : 微信支付的接口
+ * @date : 2024/2/22 17:21
+ */
+@Api(tags = "微信支付的接口")
+@RestController
+@RequestMapping("/wxapi/basic/wechat/pay")
+@Slf4j
+public class WechatPayController {
+    private ExecutorService executorService = Executors.newFixedThreadPool(20);
+
+    @Resource
+    private WechatPayService wechatPayService;
+
+    /**
+     * 商户 下单选取旗舰版或专业版的订单-预支付订单
+     *
+     * @param param
+     * @return
+     * @throws WxPayException
+     */
+    @ApiOperation(value = "下单选取旗舰版或专业版的订单预支付订单")
+    @ApiImplicitParams({
+            @ApiImplicitParam(name = "openId", value = "openId"),
+            @ApiImplicitParam(name = "paymentSn", value = "支付单号")
+    })
+    @PostMapping("/unified_order")
+    public ResponseResultVO unifiedOrder(@RequestBody Map<String, Object> param)
+            throws WxPayException {
+        return wechatPayService.unifiedOrder(param);
+    }
+
+    /**
+     * @desc : 微信支付的回调
+     * @author : 姜永辉
+     * @date : 2024/03/06 11:20
+     */
+    @PostMapping("/notify/order/{appId}")
+    public String parseOrderNotifyResult(@PathVariable(value = "appId") String appId, @RequestBody String xmlData)
+            throws WxPayException {
+        log.info("parseOrderNotifyResult--0" + appId + "---" + xmlData);
+        WxPayService wxPayService = wechatPayService.getWxPayService();
+        final WxPayOrderNotifyResult notifyResult = wxPayService.parseOrderNotifyResult(xmlData);
+        // 另起线程处理业务
+        executorService.execute(new Runnable() {
+            @Override
+            public void run() {
+                String resultCode = notifyResult.getResultCode();
+                log.info("parseOrderNotifyResult--1" + resultCode );
+                // 支付成功
+                if (resultCode.equals("SUCCESS")) {
+                    // 处理支付成功逻辑
+                    try {
+                        wechatPayService.notifyWechatPay(notifyResult);
+                    } catch (Exception e) {
+                        log.error("微信回调业务处理报错,params:" + notifyResult, e);
+                    }
+                } else {
+                    log.error("没有处理微信回调业务,交易状态:{},params:{}", resultCode, JSONObject.toJSON(notifyResult));
+                }
+            }
+        });
+        log.info("parseOrderNotifyResult--10000-成功"  );
+        return WxPayNotifyResponse.success("成功");
+    }
+
+
+}

+ 145 - 0
src/main/java/com/dk/oauth/service/wxapi/basic/WechatPayService.java

@@ -0,0 +1,145 @@
+package com.dk.oauth.service.wxapi.basic;
+
+import com.dk.common.response.ResponseResultUtil;
+import com.dk.common.response.ResponseResultVO;
+import com.dk.common.util.*;
+import com.dk.oauth.config.WechatPayConfigInfo;
+import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
+import com.github.binarywang.wxpay.bean.request.BaseWxPayRequest;
+import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
+import com.github.binarywang.wxpay.bean.result.WxPayUnifiedOrderResult;
+import com.github.binarywang.wxpay.config.WxPayConfig;
+import com.github.binarywang.wxpay.exception.WxPayException;
+import com.github.binarywang.wxpay.service.WxPayService;
+import com.github.binarywang.wxpay.service.impl.WxPayServiceImpl;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * 微信支付服务
+ * 后台管理设置的金额 从dkic_ms里取数据 金额
+ * 所以放到了 权限的oauth-server 的服务里240327
+ * @author 姜永辉
+ * @since 20223-07-01 09:41:05
+ */
+@Service("wechatPayService")
+@Slf4j
+public class WechatPayService {
+    @Autowired
+    private WechatPayConfigInfo wechatPayConfigInfo;
+
+    /**
+     * 商户 下单选取旗舰版或专业版的订单
+     *
+     * @param param
+     * @return
+     * @throws WxPayException
+     */
+    public ResponseResultVO unifiedOrder(Map<String, Object> param) throws WxPayException {
+        String paymentSn = param.get("paymentSn").toString();
+        String openId = param.get("openId").toString();
+        log.info("下单选取旗舰版或专业版的订单1----------" + param.toString());
+        try {
+            // 获取单据的金额 --后台管理设置的金额 从dkic_ms里取数据 金额
+            // 所以放到了 权限的oauth-server 的服务里
+            // todo。。。。。。。。。。。。
+
+            String payFee = "0.01";
+            WxPayService wxPayService = this.getWxPayService();
+            WxPayUnifiedOrderRequest orderRequest = new WxPayUnifiedOrderRequest();
+            orderRequest.setBody("商品测试");
+            orderRequest.setOutTradeNo(paymentSn);
+            orderRequest.setTotalFee(BaseWxPayRequest.yuanToFen(payFee.toString()));//元转成分
+            orderRequest.setOpenid(openId);
+            orderRequest.setSpbillCreateIp(IpUtils.getIpAddr(ServletUtils.getRequest()));
+            orderRequest.setNotifyUrl(wechatPayConfigInfo.getWechatNotifyUrl() + "/" + wechatPayConfigInfo.getAppId());
+            orderRequest.setTradeType("JSAPI");
+            // 生成预支付订单
+            WxPayUnifiedOrderResult wxPayUnifiedOrderResult = wxPayService.unifiedOrder(orderRequest);
+            String prepay_id = wxPayUnifiedOrderResult.getPrepayId();
+            String timeStamp = new Date().getTime() + "";
+            String nonceStr = UUID.fastUUID().toString(true);
+            String pack = "prepay_id=" + prepay_id;
+            String signType = "MD5";
+            String paySign = "";
+            String sigmTemp = "appId=" + wxPayUnifiedOrderResult.getAppid() + "&nonceStr=" + nonceStr + "&package="
+                    + pack + "&signType=" + signType + "&timeStamp=" + timeStamp;
+            sigmTemp = sigmTemp + "&key=" + wechatPayConfigInfo.getMchKey();
+            paySign = Md5Utils.hash(sigmTemp);
+            log.info("下单选取旗舰版或专业版的订单2----------" + prepay_id + "--" + sigmTemp + "--");
+            Map<String, Object> params = new HashMap<String, Object>();
+            params.put("appId", wxPayUnifiedOrderResult.getAppid());
+            params.put("timeStamp", timeStamp);
+            params.put("nonceStr", nonceStr);
+            params.put("pack", pack);
+            params.put("signType", signType);
+            params.put("paySign", paySign);
+            log.info("下单选取旗舰版或专业版的订单3----------" + params.toString());
+            return ResponseResultUtil.success(params);
+        } catch (Exception e) {
+            log.error("unifiedOrder--微信支付失败!支付单号:{},原因:{}", paymentSn, e.getMessage());
+            return ResponseResultUtil.error("支付失败,请稍后重试!");
+        }
+    }
+
+    /**
+     * @desc : 处理支付成功逻辑
+     * @author : 姜永辉
+     * @date : 2024/03/06 11:29
+     */
+    public ResponseResultVO notifyWechatPay(WxPayOrderNotifyResult info) {
+        log.info("处理支付成功逻辑----------" + info.getOutTradeNo() + "---------" + info.toString());
+
+//  判断支付金额是否一致
+//        ShopOrderPaymentDto sop = new ShopOrderPaymentDto();
+//        sop.setPaymentsn(info.getOutTradeNo());
+//        sop.setPaystatus(0L);
+//        ShopOrderPayment shopOrderPaymentReturn = shopOrderPaymentMapper.selectEntity(sop);
+//        log.info("从订单流水表没有查到数据----------" + info.getOutTradeNo());
+//        if (shopOrderPaymentReturn == null) {
+//            log.error("从订单流水表没有查到数据----------" + info.getOutTradeNo());
+//            return ResponseResultUtil.error("从订单流水表没有查到数据----------" + info.getOutTradeNo());
+//        }
+//        // //  230918  在生成 微信码时候插入 待支付的 数据
+//        BigDecimal payFee = new BigDecimal(info.getTotalFee()).divide(new BigDecimal(100), 2, RoundingMode.HALF_EVEN);
+//        log.info("微信扫码和插入待支付订单的钱不符-------" + shopOrderPaymentReturn.getAmount()
+//                + "--" + payFee);
+//        if (shopOrderPaymentReturn.getAmount().compareTo(payFee) != 0) {
+//            log.error("微信扫码和插入待支付订单的钱不符-------" + shopOrderPaymentReturn.getAmount()
+//                    + "--" + payFee);
+//            return CommonResult.fail("微信扫码和插入待支付订单的钱不符-------" + shopOrderPaymentReturn.getAmount()
+//                    + "--" + payFee);
+//
+//        }
+        //判断是否已经做支付处理
+//        log.info("判断是否已经做支付处理----------" + shopOrderPaymentReturn.getPaystatus().toString());
+
+        return ResponseResultUtil.success();
+    }
+
+    /**
+     * @desc : 获取商户配置信息
+     * @author : 姜永辉
+     * @date : 2023-08-02 17:30
+     */
+    public WxPayService getWxPayService() {
+        log.info("getWxPayService----------" + wechatPayConfigInfo.toString());
+        WxPayConfig payConfig = new WxPayConfig();
+        payConfig.setAppId(StringUtils.trimToNull(wechatPayConfigInfo.getAppId()));
+        payConfig.setMchId(StringUtils.trimToNull(wechatPayConfigInfo.getMchId()));
+        payConfig.setMchKey(StringUtils.trimToNull(wechatPayConfigInfo.getMchKey()));
+//        payConfig.setSubAppId(null);
+//        payConfig.setSubMchId(null);
+//        payConfig.setKeyPath(StringUtils.trimToNull(wechatPayConfigInfo.getKeyPath()));
+        // 可以指定是否使用沙箱环境
+        payConfig.setUseSandboxEnv(false);
+        WxPayService wxPayService = new WxPayServiceImpl();
+        wxPayService.setConfig(payConfig);
+        return wxPayService;
+    }
+}