2021与蓝度共同重构项目,服务端
liuhaonan
2022-08-24 c78889bffa820ff599d3d524800c20b477074326
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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
package com.sandu.ximon.admin.pay.wx;
 
import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.bean.notify.WxPayRefundNotifyResult;
import com.github.binarywang.wxpay.bean.request.WxPayRefundRequest;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.bean.result.WxPayRefundResult;
import com.github.binarywang.wxpay.bean.result.WxPayUnifiedOrderResult;
import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.constant.WxPayConstants;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.sandu.common.execption.BusinessException;
import com.sandu.common.util.IpUtil;
import com.sandu.common.util.SpringContextHolder;
import com.sandu.ximon.admin.dto.wxquerydto.WxOrderDto;
import com.sandu.ximon.admin.pay.wxpay.UsrWxPayConfigService;
import com.sandu.ximon.admin.service.C3mOrderService;
import com.sandu.ximon.dao.domain.C3mOrder;
import com.sandu.ximon.dao.domain.WxConfigEntity;
import com.sandu.ximon.dao.enums.OrderStatus;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import javax.servlet.http.HttpServletRequest;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
 
/**
 * @author chenjiantian
 * @date 2021/8/12 11:26
 */
@Service
@Slf4j
@AllArgsConstructor
public class WxFastPayService {
 
    private final com.github.binarywang.wxpay.service.WxPayService wxPayService;
    public static final String WECHAT_ORDER_PAY_CALLBACK_URL = "http://112.74.63.130:20017/callback/pay/wechatCallback";
    //微信订单状态查询
    public static final String WECHAT_ORDER_QUETY_URL = "https://api.mch.weixin.qq.com/v3/pay/transactions/out-trade-no/";
    public static final String WECHAT_ORDER_QUETY = "?mchid=";
 
    private final UsrWxPayConfigService wxPayConfigService;
 
 
    /**
     * 微信订单状态查询
     *
     * @param poleId
     * @param outTradeNo
     * @return
     */
    public boolean WxOrderQuery(Long poleId, String outTradeNo) {
        WxConfigEntity wxConfig = wxPayConfigService.getConfigByPoleId(poleId);
        if (wxConfig == null) {
            throw new BusinessException("获取微信支付配置失败");
        }
        String s = HttpUtil.get(WECHAT_ORDER_QUETY_URL + outTradeNo + WECHAT_ORDER_QUETY + wxConfig.getMchId());//WxOrderDto
        WxOrderDto wxOrderDto = JSON.parseObject(s, WxOrderDto.class);
        if (("SUCCESS").equals(wxOrderDto.getTrade_state())) {
            return true;
        }
 
        return false;
    }
 
    /**
     * @param parameters
     * @return
     */
    @SuppressWarnings("rawtypes")
    private String createSign(String Key, SortedMap<Object, Object> parameters) {
 
        StringBuffer sb = new StringBuffer();
        Set es = parameters.entrySet();// 所有参与传参的参数按照accsii排序(升序)
        for (Object e : es) {
            Map.Entry entry = (Map.Entry) e;
            String k = (String) entry.getKey();
            Object v = entry.getValue();
            if (null != v && !"".equals(v) && !"sign".equals(k) && !"key".equals(k)) {
                sb.append(k + "=" + v + "&");
            }
        }
        sb.append("key=" + Key);
        System.out.println("字符串拼接后是:" + sb.toString());
        return SecureUtil.md5(sb.toString()).toUpperCase();
//        StringBuffer sb = new StringBuffer();
//        Set es = parameters.entrySet();// 所有参与传参的参数按照accsii排序(升序)
//        Iterator it = es.iterator();
//        while (it.hasNext()) {
//            Map.Entry entry = (Map.Entry) it.next();
//            String k = (String) entry.getKey();
//            Object v = entry.getValue();
//            if (null != v && !"".equals(v) && !"sign".equals(k) && !"key".equals(k)) {
//                sb.append(k + "=" + v + "&");
//            }
//        }
//        sb.append("key=" + Key);
//        System.out.println("字符串拼接后是:" + sb.toString());
//        String sign = EncriptionKit.encrypt(sb.toString()).toUpperCase();
//        return sign;
    }
 
    public WxPayOrderNotifyResult parseOrderNotifyResult(String xmlData) {
        try {
            return wxPayService.parseOrderNotifyResult(xmlData);
        } catch (WxPayException e) {
            e.printStackTrace();
            throw new BusinessException("解析回调结果失败," + e.getErrCodeDes());
        }
    }
 
 
    public WxPayOrderNotifyResult parseOrderNotifyResult(WxPayService wxPayService, String xmlData) {
        try {
            return wxPayService.parseOrderNotifyResult(xmlData);
        } catch (WxPayException e) {
            e.printStackTrace();
            throw new BusinessException("解析回调结果失败," + e.getErrCodeDes());
        }
    }
 
    public WxPayRefundNotifyResult parseRefundNotifyResult(String xmlData) {
        try {
            return wxPayService.parseRefundNotifyResult(xmlData);
        } catch (WxPayException e) {
            e.printStackTrace();
            throw new BusinessException("解析回调结果失败," + e.getErrCodeDes());
        }
    }
 
 
    /**
     * 退款
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean refund(C3mOrder c3mOrder) {
 
        WxConfigEntity wxConfig = wxPayConfigService.getConfigByPoleId(c3mOrder.getPoleId());
 
        if (wxConfig.getKeyPath() == null && wxConfig.getKeyPath().isEmpty()) {
            throw new BusinessException("微信证书不存在,无法进行退款");
        }
        //设置微信支付参数
        WxPayConfig payConfig = new WxPayConfig();
 
        payConfig.setAppId(StringUtils.trimToNull(wxConfig.getAppappid()));
        payConfig.setMchId(StringUtils.trimToNull(wxConfig.getMchId()));
        payConfig.setMchKey(StringUtils.trimToNull(wxConfig.getPrivateKey()));
        payConfig.setSubAppId(StringUtils.trimToNull(null));
        payConfig.setSubMchId(StringUtils.trimToNull(null));
        payConfig.setKeyPath(StringUtils.trimToNull(wxConfig.getKeyPath()));
        wxPayService.setConfig(payConfig);
 
 
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String refundNo = sdf.format(new Date());
        WxPayRefundRequest refundRequest = new WxPayRefundRequest();
        //退款金额不能大于订单总金额
        if (c3mOrder.getRefundAmount() > c3mOrder.getTotalAmount()) {
            throw new BusinessException("退款金额不能大于订单总金额");
        }
        System.out.println("" + c3mOrder.getRefundAmount());
        refundRequest.setOutTradeNo(c3mOrder.getOutTradeNo());
        refundRequest.setOutRefundNo(refundNo);
        refundRequest.setTotalFee(Integer.valueOf(parseWxAmount((c3mOrder.getTotalAmount() + ""))));
        refundRequest.setRefundFee(Integer.valueOf(parseWxAmount((c3mOrder.getRefundAmount() + ""))));
        try {
            WxPayRefundResult wxPayRefundResult = wxPayService.refund(refundRequest);
            if (WxPayConstants.ResultCode.SUCCESS.equals(wxPayRefundResult.getResultCode())) {
                c3mOrder.setOrderStatus(OrderStatus.REFUND.getStatus());
                c3mOrder.setChargingStates(1);
                SpringContextHolder.getBean(C3mOrderService.class).updateById(c3mOrder);
                return true;
            } else {
                log.error("微信退款失败,{}", wxPayRefundResult.getErrCodeDes());
                throw new BusinessException("微信退款失败," + wxPayRefundResult.getErrCodeDes());
            }
        } catch (WxPayException e) {
            log.error("微信退款失败,{}", e.getErrCodeDes());
            throw new BusinessException("微信退款失败," + e.getErrCodeDes());
        }
    }
 
    /**
     * 转换为微信金额(分)
     *
     * @param normalAmount 0.01元
     * @return
     */
    public static String parseWxAmount(String normalAmount) {
        //  保留2位小数
        double totalAmountDouble = Double.parseDouble(new DecimalFormat("#.00").format(
                Double.parseDouble(normalAmount)));
        String amount = (totalAmountDouble * 100) + "";
        amount = amount.substring(0, amount.indexOf("."));
        return amount;
    }
 
    /**
     * 小程序支付  微信
     *
     * @param body
     * @param orderId
     * @param totalFee
     * @param poleId
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public SortedMap<Object, Object> miniAppPay(HttpServletRequest request, String body, String orderId, int totalFee, Long poleId, String wxCode) throws WxErrorException {
        WxConfigEntity wxConfig = wxPayConfigService.getConfigByPoleId(poleId);
 
        //设置微信支付参数
        WxPayConfig payConfig = new WxPayConfig();
 
        payConfig.setAppId(StringUtils.trimToNull(wxConfig.getAppappid()));
        payConfig.setMchId(StringUtils.trimToNull(wxConfig.getMchId()));
        payConfig.setMchKey(StringUtils.trimToNull(wxConfig.getPrivateKey()));
        payConfig.setSubAppId(StringUtils.trimToNull(null));
        payConfig.setSubMchId(StringUtils.trimToNull(null));
        payConfig.setKeyPath(StringUtils.trimToNull(null));
        wxPayService.setConfig(payConfig);
 
 
        //设置微信同一订单请求
        WxPayUnifiedOrderRequest wxPayUnifiedOrderRequest = new WxPayUnifiedOrderRequest();
        wxPayUnifiedOrderRequest.setBody(body);
        wxPayUnifiedOrderRequest.setOutTradeNo(orderId);
        wxPayUnifiedOrderRequest.setTotalFee(totalFee);
        wxPayUnifiedOrderRequest.setOpenid(wxCode);
 
 
        wxPayUnifiedOrderRequest.setSignType(WxPayConstants.SignType.MD5);
        wxPayUnifiedOrderRequest.setSpbillCreateIp(IpUtil.getIpAddr(request));
        wxPayUnifiedOrderRequest.setNotifyUrl(WECHAT_ORDER_PAY_CALLBACK_URL);
        wxPayUnifiedOrderRequest.setTradeType(WxPayConstants.TradeType.JSAPI);
        System.out.println("-----------" + wxPayUnifiedOrderRequest);
 
        try {
            WxPayUnifiedOrderResult wxPayUnifiedOrderResult = wxPayService.unifiedOrder(wxPayUnifiedOrderRequest);
            String time = String.valueOf(System.currentTimeMillis() / 1000);
            if (WxPayConstants.ResultCode.SUCCESS.equals(wxPayUnifiedOrderResult.getResultCode())) {
                SortedMap<Object, Object> parameters = new TreeMap<>();
                parameters.put("appId", wxPayUnifiedOrderResult.getAppid());
 
                parameters.put("nonceStr", wxPayUnifiedOrderResult.getNonceStr()); // 随机字符串
//                parameters.put("partnerid", wxConfig.getMchId()); // 商户id
 
                parameters.put("signType", WxPayConstants.SignType.MD5);
                //  parameters.put("out_trade_no", orderId);//商户订单号
//                parameters.put("prepayid", wxPayUnifiedOrderResult.getPrepayId());
                parameters.put("package", "prepay_id=" + wxPayUnifiedOrderResult.getPrepayId());
                parameters.put("timeStamp", time);
 
                String sign = createSign(wxConfig.getPrivateKey(), parameters);
 
                //hashMap.put("paySign", wechatSign);
                parameters.put("paySign", sign);
                return parameters;
            } else {
                log.error("微信支付失败,{}", wxPayUnifiedOrderResult.getErrCodeDes());
                throw new BusinessException("微信支付失败," + wxPayUnifiedOrderResult);
            }
        } catch (WxPayException e) {
            log.error("微信支付失败,{}", e.getErrCodeDes());
            throw new BusinessException("微信支付失败," + e.getErrCodeDes());
        }
    }
 
 
    public WxMaService getWxMaService(WxConfigEntity wxConfig) {
        if (wxConfig == null) {
            throw new BusinessException("找不到微信配置");
        }
        WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl();
        config.setAppid(wxConfig.getAppappid());
        config.setSecret(wxConfig.getAppSecret());
        WxMaService service = new WxMaServiceImpl();
        service.setWxMaConfig(config);
        return service;
    }
 
    public String getOpenId(Long poleId, String wxCode) throws WxErrorException {
        WxConfigEntity userConfig = wxPayConfigService.getConfigByPoleId(poleId);
        if (userConfig == null) {
            throw new BusinessException("找不到微信配置");
        }
        WxMaJscode2SessionResult sessionInfo = this.getWxMaService(userConfig).getUserService().getSessionInfo(wxCode);
        return sessionInfo.getOpenid();
    }
 
}