puzhibing
2024-08-17 1b43670626f48266efb898ec7cd7deedcab9ba10
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
package com.ruoyi.payment.wx.utils;
 
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.payment.wx.model.WeixinProperties;
import com.ruoyi.payment.wx.model.WxPaymentInfoModel;
import com.ruoyi.payment.wx.model.WxPaymentRefundModel;
import com.ruoyi.payment.wx.resp.NotifyV3PayDecodeRespBody;
import com.wechat.pay.contrib.apache.httpclient.WechatPayHttpClientBuilder;
import com.wechat.pay.contrib.apache.httpclient.auth.PrivateKeySigner;
import com.wechat.pay.contrib.apache.httpclient.auth.Verifier;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Credentials;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Validator;
import com.wechat.pay.contrib.apache.httpclient.cert.CertificatesManager;
import com.wechat.pay.contrib.apache.httpclient.util.PemUtil;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.impl.client.CloseableHttpClient;
 
import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.security.PrivateKey;
import java.util.Map;
 
/**
 * @author xiaochen
 * @ClassName WxWifiV3Pay
 * @Description
 * @date 2021-11-13 21:10
 */
@Slf4j
public class WxV3Pay extends WxAbstractPay {
    @Getter
    private WeixinProperties config;
    @Getter
    private Verifier verifier;
    private WechatPayHttpClientBuilder builder;
    @Getter
    private CloseableHttpClient httpClient;
    private PrivateKeySigner privateKeySigner;
    private WechatPay2Validator validator;
    @Getter
    private PrivateKey privateKey;
 
    /**
     * 初始化
     *
     * @param config
     */
    public WxV3Pay(WeixinProperties config) {
        // 检查v3支付配置信息
        if (WxUtils.getLogger().isDebugEnabled()) {
            WxUtils.debug("开始检查v3支付配置信息....");
        }
        try {
            this.config = config;
            checkWxConfig();
            this.privateKey = PemUtil.loadPrivateKey(config.getV3().getPrivateKeyStream());
            this.privateKeySigner = new PrivateKeySigner(config.getV3().getMchSerialNo(), privateKey);
            // 获取证书管理器实例
            CertificatesManager certificatesManager = CertificatesManager.getInstance();
            // 向证书管理器增加需要自动更新平台证书的商户信息
            certificatesManager.putMerchant(config.getMchId(), new WechatPay2Credentials(config.getMchId(),
                    this.privateKeySigner), config.getV3().getApiKey().getBytes(StandardCharsets.UTF_8));
            // 从证书管理器中获取verifier
            this.verifier = certificatesManager.getVerifier(config.getMchId());
            this.validator = new WechatPay2Validator(verifier);
            this.builder = WechatPayHttpClientBuilder.create()
                    .withMerchant(config.getMchId(), config.getV3().getMchSerialNo(), this.privateKey)
                    .withValidator(this.validator);
            this.httpClient = this.builder.build();
        } catch (Exception e) {
            // 打印异常信息
            e.printStackTrace();
            WxUtils.warn("检查v3支付配置信息出现错误,直连商户商户号:{},{}", config.getMchId(), e.getMessage());
            return;
        }
        if (WxUtils.getLogger().isDebugEnabled()) {
            WxUtils.debug("检查v3支付配置信息完成,未出现异常....");
        }
    }
 
    /**
     * 检查支付配置信息
     *
     * @throws Exception
     */
    private void checkWxConfig() throws Exception {
        if (this.config == null) {
            throw new Exception("config is null");
        }
        if (config.getMchId() == null || config.getMchId().trim().length() == 0) {
            throw new Exception("MchID in config is empty");
        }
        if (config.getV3().getMchSerialNo() == null) {
            throw new Exception("mchSerialNo in config is empty");
        }
        if (config.getV3().getPrivateKeyStream() == null) {
            throw new Exception("cert stream in config is empty");
        }
        if (this.config.getHttpConnectTimeoutMs() < 10) {
            throw new Exception("http connect timeout is too small");
        }
        if (this.config.getHttpReadTimeoutMs() < 10) {
            throw new Exception("http read timeout is too small");
        }
    }
 
    /**
     * jsApi下单
     *
     * @param tradeNo     订单号
     * @param amount      金额 分
     * @param openid      openid
     * @param description 订单描述
     * @return java.util.Map<java.lang.String, java.lang.Object>
     * @author xiaochen
     * @date 2022-03-22 12:47
     */
    public Map<String, Object> jsApi(String tradeNo, Integer amount, String openid, String description) {
        WxPaymentInfoModel requestBody = WxPaymentInfoModel.builder()
                .mchid(this.config.getMchId())
                .appid(this.config.getAppId())
                .description(description)
                .out_trade_no(tradeNo)
//                .attach("")
                .amount(WxPaymentInfoModel.Amount.builder().total(amount).build())
                .payer(WxPaymentInfoModel.Payer.builder().openid(openid).build())
                // 分不分账
                //.settle_info(WxPaymentInfoModel.SettleInfo.builder().profit_sharing(true).build())
                .build();
        // 封装基础数据
        String reqBody = buildBaseParam(requestBody
                , this.config.getV3().getNotifyPayUrl());
        //请求URL
        HttpEntityEnclosingRequestBase httpPost = requestPost(
                "/v3/pay/transactions/jsapi"
                , this.config.getHttpReadTimeoutMs()
                , this.config.getHttpConnectTimeoutMs()
                , reqBody);
        String repBody = result(httpClient, httpPost);
        ObjectMapper om = new ObjectMapper();
        try {
            JsonNode rootNode = om.readTree(repBody);
            String prepayId = rootNode.path("prepay_id").asText();
            return wxTuneUp(this.privateKeySigner, requestBody.getAppid(), prepayId);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("获取支付数据错误!");
        }
    }
 
 
    /**
     * 接收回调
     *
     * @param request
     * @return
     * @throws Exception
     */
    @Override
    public <T> T verifyNotify(HttpServletRequest request, TypeReference<T> valueTypeRef) throws Exception {
        return verifyNotify(request, this.verifier, this.config.getV3().getApiKey(), valueTypeRef);
    }
 
    /**
     * 订单查询
     *
     * @param out_trade_no
     * @param mchid
     * @return com.abl.biz.center.payment.wx.v3.NotifyV3PayDecodeRespBody
     * @author xiaochen
     * @date 2021-12-20 16:47
     */
    @Override
    public NotifyV3PayDecodeRespBody query(String out_trade_no, String mchid) {
        String url =
                String.format("/v3/pay/transactions/out-trade-no/%s", out_trade_no) + String.format("?mchid=%s", mchid);
        return query(this.httpClient, this.config.getHttpReadTimeoutMs(), this.config.getHttpConnectTimeoutMs(), url);
    }
 
    /**
     * 退款
     *
     * @param refundModel
     * @return java.util.Map<java.lang.String, java.lang.Object>
     * @author xiaochen
     */
    @Override
    public Map<String, Object> refund(WxPaymentRefundModel refundModel) {
//        refundModel.setNotify_url(this.config.getV3().getNotifyRefundUrl());
        return refund(this.httpClient, "/v3/refund/domestic/refunds", this.config.getHttpReadTimeoutMs(), this.config.getHttpConnectTimeoutMs(), refundModel);
    }
 
}