jiangping
2023-12-29 f9691d544e62d6c04dbfe45d05a6c7bc5e004291
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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
package com.doumee.core.wx;
 
import com.alibaba.fastjson.JSONObject;
import com.doumee.biz.system.SystemDictDataBiz;
import com.doumee.core.constants.Constants;
import com.doumee.core.constants.ResponseStatus;
import com.doumee.core.exception.BusinessException;
import com.doumee.core.utils.DateUtil;
import com.doumee.core.utils.HttpsUtil;
import com.doumee.core.utils.ID;
import com.doumee.core.utils.ImageDesignerUtil;
import com.doumee.dao.business.RefundMapper;
import com.doumee.dao.business.TransactionsMapper;
import com.doumee.dao.business.model.Locks;
import com.doumee.dao.business.model.Refund;
import com.doumee.dao.business.model.Transactions;
import com.doumee.dao.business.web.request.RefundDTO;
import com.doumee.dao.system.model.SystemDictData;
import com.wechat.pay.java.service.refund.model.AmountReq;
import com.wechat.pay.java.service.refund.model.CreateRequest;
import com.wechat.pay.java.service.refund.model.QueryByOutRefundNoRequest;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import java.io.*;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
 
/**
 * 微信小程序-公共方法
 */
@Service
@Slf4j
public class WxMiniUtilService {
 
    @Autowired
    private RefundMapper refundMapper;
 
    @Autowired
    private TransactionsMapper transactionsMapper;
 
    @Autowired
    private SystemDictDataBiz systemDictDataBiz;
    @Autowired
    private WxPayProperties wxPayProperties;
 
    @Transactional(rollbackFor = {BusinessException.class,Exception.class})
    public boolean wxRefund(RefundDTO refundDTO) {
        // 发送退款请求
        Refund refund = new Refund();
        refund.setId(Constants.getUUID());
        refund.setCreateDate(new Date());
        refund.setMemberId(refundDTO.getMemberId());
        refund.setMoney(refundDTO.getRefundAmount());
//        refund.setOnlineOrderid(refNum);
        refund.setPayWay(Constants.ZERO);
        refund.setStatus(Constants.ZERO);
        refund.setDoneDate(new Date());
        refund.setCreator(refundDTO.getCreator());
        refund.setType(refundDTO.getType());
        refund.setObjId(refundDTO.getOrderId());
        refund.setReason(refundDTO.getReason());
        refund.setCanBalance(refundDTO.getCanBalance());
        refundMapper.insert(refund);
 
        CreateRequest request = new CreateRequest();
        request.setOutTradeNo(refundDTO.getOrderId());
        request.setOutRefundNo(refund.getId());
        request.setSubMchid(WxMiniConfig.wxProperties.getSubMchId());
        request.setNotifyUrl(WxMiniConfig.wxProperties.getRefundNotifyUrl());
        AmountReq amountReq = new AmountReq();
        amountReq.setTotal(refundDTO.getTotalAmount().longValue());
        amountReq.setRefund(refundDTO.getRefundAmount().longValue());
        amountReq.setCurrency("CNY");
        request.setAmount(amountReq);
        try {
            log.error("=============="+JSONObject.toJSONString(request));
            com.wechat.pay.java.service.refund.model.Refund response = WxMiniConfig.refundService.create(request);
            log.error("=============="+JSONObject.toJSONString(response));
            if ("SUCCESS".equals(response.getStatus().name())
                    || "PROCESSING".equals(response.getStatus().name()) ) {
                return  true;
            }else{
                throw  new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"对不起,退款申请失败哦!");
            }
        }catch (Exception e){
            e.printStackTrace();
            throw  new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"对不起,退款申请失败!");
        }
 
    }
    @Transactional(rollbackFor = {BusinessException.class,Exception.class})
    public com.wechat.pay.java.service.refund.model.Refund isSuucessRefund(String outTradeNo) {
        // 发送退款请求
 
        QueryByOutRefundNoRequest request = new QueryByOutRefundNoRequest();
        request.setOutRefundNo(outTradeNo);
        request.setSubMchid(WxMiniConfig.wxProperties.getSubMchId());
        try {
            log.error("=============="+JSONObject.toJSONString(request));
            com.wechat.pay.java.service.refund.model.Refund response = WxMiniConfig.refundService.queryByOutRefundNo(request);
            log.error("=============="+JSONObject.toJSONString(response));
            if ("SUCCESS".equals(response.getStatus().name())
                    || "PROCESSING".equals(response.getStatus().name()) ) {
                return  response;
            }
        }catch (Exception e){
            e.printStackTrace();
 
        }
        return  null;
    }
    public Refund wxRefundOld(RefundDTO refundDTO) {
        // 发送退款请求
        String refNum = ID.nextGUID();
        CreateRequest request = new CreateRequest();
        request.setOutTradeNo(refundDTO.getOrderId());
        request.setOutRefundNo(refNum);
        request.setSubMchid(WxMiniConfig.wxProperties.getSubMchId());
        request.setNotifyUrl(WxMiniConfig.wxProperties.getRefundNotifyUrl());
//
        AmountReq amountReq = new AmountReq();
        amountReq.setTotal(refundDTO.getTotalAmount().longValue());
        amountReq.setRefund(refundDTO.getRefundAmount().longValue());
        amountReq.setCurrency("CNY");
        request.setAmount(amountReq);
        System.out.println("实际总金额" + refundDTO.getTotalAmount());
        System.out.println("实际退款金额" + refundDTO.getRefundAmount());
//            request.setTotalFee(1);
//            request.setRefundFee(1);
        try {
            com.wechat.pay.java.service.refund.model.Refund response = WxMiniConfig.refundService.create(request);
            if ("SUCCESS".equals(response.getStatus().name()) ) {
                //存储退款记录 与 流水记录
                Refund refund = new Refund();
                refund.setId(Constants.getUUID());
                refund.setCreateDate(new Date());
                refund.setMemberId(refundDTO.getMemberId());
                refund.setMoney(refundDTO.getRefundAmount());
                refund.setOnlineOrderid(refNum);
                refund.setPayWay(Constants.ZERO);
                refund.setStatus(Constants.TWO);
                refund.setDoneDate(new Date());
                refund.setCreator(refundDTO.getCreator());
                refund.setType(refundDTO.getType());
                refund.setObjId(refundDTO.getOrderId());
                refund.setReason(refundDTO.getReason());
                refund.setCanBalance(refundDTO.getCanBalance());
                refundMapper.insert(refund);
                //存储交易流水表
                Transactions transactions = new Transactions();
                transactions.setId(Constants.getUUID());
                transactions.setMemberId(refundDTO.getMemberId());
                transactions.setCreateDate(new Date());
                transactions.setIsdeleted(Constants.ZERO);
                transactions.setOrderId(refundDTO.getOrderId());
                transactions.setMoney(refundDTO.getRefundAmount());
                transactions.setPreOrderid(refundDTO.getOrderId());
                transactions.setOnlineOrderid(refNum);
                transactions.setDoneDate(new Date());
                if(refund.getType().equals(Constants.REFUND_TYPE.PLAT_AUTO.getKey())||refund.getType().equals(Constants.REFUND_TYPE.PLAT_FORCE.getKey())){
                    //平台自动退款 或 强制退款
                    transactions.setType(Constants.TRANSACTIONS_TYPE.REFUND.getKey());
                    transactions.setTitle(Constants.REFUND_TYPE.PLAT_AUTO.getInfo());
                    transactions.setContent(Constants.REFUND_TYPE.PLAT_AUTO.getInfo());
                }else if(refund.getType().equals(Constants.REFUND_TYPE.NORMAL.getKey())){
                    //用户主动退款
                    transactions.setType(Constants.TRANSACTIONS_TYPE.REFUND.getKey());
                    transactions.setTitle(Constants.REFUND_TYPE.NORMAL.getInfo());
                    transactions.setContent(Constants.REFUND_TYPE.NORMAL.getInfo());
                }else if(refund.getType().equals(Constants.REFUND_TYPE.BACK.getKey())){
                    //结算后退款
                    transactions.setType(Constants.TRANSACTIONS_TYPE.REFUND.getKey());
                    transactions.setTitle(Constants.REFUND_TYPE.BACK.getInfo());
                    transactions.setContent(Constants.REFUND_TYPE.BACK.getInfo());
                }
                transactions.setBalance(BigDecimal.ZERO);
                transactions.setObjId(refund.getId());
                transactions.setObjType(Constants.ONE);
                transactionsMapper.insert(transactions);
                return refund;
            } else{
                throw  new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"对不起,退款失败!");
            }
        }catch (BusinessException e){
            throw e;
        }catch (Exception e){
            e.printStackTrace();
            throw  new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"对不起,退款失败!");
        }
 
 
    }
 
    public static void main(String[] args) throws IOException {
      /* InputStream inputStream = HttpsUtil.postJson("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=75_W8lx5-bp9WEo69pQ6hvN70fJJJCNSRby6Wi6z_R9G7Sd5GMdY7ZT8Zq3PrKWrFBq92utfgqu3P8iw1NOvJNfyZssEYCy6k94Wch-GQNXcarSV65gowLk-SA9bncWTJbAGAHEU", "{\"check_path\":false,\"is_hyaline\":false,\"page\":\"pages/index/index\",\"scene\":\"1993/90\",\"env_version\":\"trial\"}");
        File file = new File("D://test.png");
 
        //定义一个用于读取InputStream数据的byte数组
        byte[] buffer = new byte[1024];
 
//输出流,用于写入文件
        FileOutputStream outputStream = new FileOutputStream(file);
 
//循环读取数据并将其写入文件中
        int length;
        while ((length = inputStream.read(buffer)) > 0) {
            outputStream.write(buffer, 0, length);
        }
 
//关闭InputStream和OutputStream
        inputStream.close();
        outputStream.close();*/
        Map<String,Object> body = new HashMap<>();
        // 场景码,与前端约定,最终是需要前端解析
        body.put("scene",   "1992/41" );
        // 正式版为 "release",体验版为 "trial",开发版为 "develop"。默认是正式版。
//        body.put("env_version", "release");
        body.put("env_version", "trial");
        // 透明,根据你的场景自行设置body参数
        body.put("is_hyaline",false);
        body.put("check_path", false);
        body.put("page","pages/index/index");
        OkHttpClient client = new OkHttpClient().newBuilder().build();
        okhttp3.MediaType mediaType = okhttp3.MediaType.parse("application/json");
        log.info("=========================================="+JSONObject.toJSONString(body));
        okhttp3.RequestBody requestBody = okhttp3.RequestBody.create(mediaType, JSONObject.toJSONString(body));
        Request request = new Request.Builder().url("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=75_MppLyM-Fy1rWPbJE8ccXfy90Afg_3wdENqKBEshglyyARP3egjvsti3agoaZJ0UVKHh_wwuIDcbu41ptPKleUcaD1vDRi4BrH8oN8TEHPTUCb1Kcp6ZoMJNNWScZKChAIAHSK").method("POST", requestBody).build();
        try {
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                InputStream inputStream = new ByteArrayInputStream(response.body().bytes());
                String nowDate = DateUtil.getNowShortDate();
                File file = new File("D://test1.png");
                FileUtils.copyInputStreamToFile(inputStream,file);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    /**
     * 生成小程序码
     * https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/qrcode-link/qr-code/getUnlimitedQRCode.html
     * @return
     */
    public void generateWXMiniCode(Locks locks,SystemDictData systemDictData,String prePath,String path){
 
        if(Objects.isNull(systemDictData)){
            return;
        }
         String url =  "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+ systemDictData.getCode();
        String release =   systemDictDataBiz.queryByCode(Constants.MINI_PROGRAMME,Constants.MINI_PROGRAMME_REALEASE).getCode();
        //生成图片上传OSS
        Map<String,Object> body = new HashMap<>();
        // 场景码,与前端约定,最终是需要前端解析
        body.put("scene", locks.getSiteId() + "/" +locks.getCode() );
        // 正式版为 "release",体验版为 "trial",开发版为 "develop"。默认是正式版。
//        body.put("env_version", "release");
        body.put("env_version", StringUtils.defaultString(release, "release"));
        // 透明,根据你的场景自行设置body参数
        body.put("is_hyaline", false);
        body.put("check_path", false);
        body.put("width", 290);
        body.put("page","pages/index/index");
        log.info("=========================================="+url+"\n"+JSONObject.toJSONString(body));
        try {
            InputStream inputStream  =HttpsUtil.postJson(url,JSONObject.toJSONString(body));;
            if (inputStream !=null) {
                String nowDate = DateUtil.getNowShortDate();
                String name =locks.getSiteId()+"-"+locks.getCode()+"-"+nowDate+".png";
                String fileName =prePath+path+"/"+name;
//                File file = new File(prePath+path,locks.getSiteId()+"-"+locks.getCode()+"-"+nowDate+".png");
//                FileUtils.copyInputStreamToFile(inputStream,file);
                if(ImageDesignerUtil.graphicsGenerationIs(locks.getSiteId()+"/"+locks.getCode(),inputStream,fileName)){
                    locks.setInfo(name);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 生成小程序码
     * https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/qrcode-link/qr-code/getUnlimitedQRCode.html
     * @return
     */
    public void generateWXMiniCodeOld(Locks locks,SystemDictData systemDictData,String prePath,String path){
 
        if(Objects.isNull(systemDictData)){
            return;
        }
      String release =   systemDictDataBiz.queryByCode(Constants.MINI_PROGRAMME,Constants.MINI_PROGRAMME_REALEASE).getCode();
        //生成图片上传OSS
        Map<String,Object> body = new HashMap<>();
        // 场景码,与前端约定,最终是需要前端解析
        body.put("scene", locks.getSiteId() + "/" +locks.getCode() );
        // 正式版为 "release",体验版为 "trial",开发版为 "develop"。默认是正式版。
//        body.put("env_version", "release");
        body.put("env_version", StringUtils.defaultString(release, "release"));
        // 透明,根据你的场景自行设置body参数
        body.put("is_hyaline", Boolean.FALSE.toString());
        body.put("check_path", Boolean.FALSE.toString());
        body.put("page","pages/index/index");
        OkHttpClient client = new OkHttpClient().newBuilder().build();
        okhttp3.MediaType mediaType = okhttp3.MediaType.parse("application/json");
        okhttp3.RequestBody requestBody = okhttp3.RequestBody.create(mediaType, JSONObject.toJSONString(body));
        log.info("=========================================="+JSONObject.toJSONString(body));
        Request request = new Request.Builder().url("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+systemDictData.getCode()).method("POST", requestBody).build();
        try {
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                InputStream inputStream = new ByteArrayInputStream(response.body().bytes());
                String nowDate = DateUtil.getNowShortDate();
                File file = new File(prePath+path,locks.getSiteId()+"-"+locks.getCode()+"-"+nowDate+".png");
                FileUtils.copyInputStreamToFile(inputStream,file);
                locks.setInfo(locks.getSiteId()+"-"+locks.getCode()+"-"+nowDate+".png");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
}