xiaoyong931011
2022-08-31 1e518fe3d26857ab604345351a576575fc82a145
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
package cc.mrbird.febs.pay.service.impl;
 
import cc.mrbird.febs.common.entity.FebsResponse;
import cc.mrbird.febs.common.enumerates.DataDictionaryEnum;
import cc.mrbird.febs.common.enumerates.FlowTypeEnum;
import cc.mrbird.febs.common.enumerates.MoneyFlowTypeEnum;
import cc.mrbird.febs.common.properties.XcxProperties;
import cc.mrbird.febs.common.utils.MallUtils;
import cc.mrbird.febs.common.utils.OssUtils;
import cc.mrbird.febs.common.utils.RedisUtils;
import cc.mrbird.febs.common.utils.SpringContextHolder;
import cc.mrbird.febs.mall.dto.ApiRechargeWalletDto;
import cc.mrbird.febs.mall.entity.DataDictionaryCustom;
import cc.mrbird.febs.mall.entity.MallMember;
import cc.mrbird.febs.mall.entity.MallOrderInfo;
import cc.mrbird.febs.mall.entity.MallOrderItem;
import cc.mrbird.febs.mall.mapper.DataDictionaryCustomMapper;
import cc.mrbird.febs.mall.mapper.MallMemberMapper;
import cc.mrbird.febs.mall.mapper.MallOrderInfoMapper;
import cc.mrbird.febs.mall.service.IMallMoneyFlowService;
import cc.mrbird.febs.pay.model.*;
import cc.mrbird.febs.pay.service.IXcxPayService;
import cc.mrbird.febs.pay.util.WechatConfigure;
import cc.mrbird.febs.pay.util.WeixinServiceUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.dynamic.datasource.toolkit.Base64;
import com.baomidou.mybatisplus.extension.exceptions.ApiException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
 
import java.io.*;
import java.math.BigDecimal;
import java.net.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
@Slf4j
@Service
@RequiredArgsConstructor
public class XcxPayServiceImpl implements IXcxPayService {
 
    @Autowired
    private MallOrderInfoMapper mallOrderInfoMapper;
    @Autowired
    private MallMemberMapper mallMemberMapper;
    @Autowired
    WeixinServiceUtil weixinServiceUtil;
    @Autowired
    private DataDictionaryCustomMapper dataDictionaryCustomMapper;
    private final IMallMoneyFlowService mallMoneyFlowService;
    @Autowired
    RedisUtils redisUtils;
 
    private final SpringContextHolder springContextHolder;
 
    private final XcxProperties xcxProperties = SpringContextHolder.getBean(XcxProperties.class);
 
    @Override
    public BrandWCPayRequestData startRechargeWallet(ApiRechargeWalletDto apiRechargeWalletDto) throws Exception {
        BigDecimal unit = new BigDecimal("100");
        BigDecimal money = new BigDecimal(apiRechargeWalletDto.getAmount().toString());
        BrandWCPayRequestData payData;
        String productNames = "小程序充值";
        MallMember mallMember = mallMemberMapper.selectById(apiRechargeWalletDto.getMemberId());
        String rechargeNo = "CZ_"+MallUtils.getOrderNum();
        Boolean debug = xcxProperties.getDebug();
        String attrStr = "{'rechargeNo':"+rechargeNo+",'memberId':"+mallMember.getId()+"}";
        if (debug) {
            payData = weixinServiceUtil.createRechargeWallet("[测试]" + productNames, rechargeNo,
                    1, mallMember.getOpenId(), attrStr);
        } else {
            payData = weixinServiceUtil.createRechargeWallet(productNames, rechargeNo,
                    unit.multiply(money).intValue(),mallMember.getOpenId(), attrStr);
        }
        mallMoneyFlowService.addMoneyFlow(
                mallMember.getId(),
                money,
                MoneyFlowTypeEnum.RECHARGE.getValue(),
                rechargeNo,
                FlowTypeEnum.BALANCE.getValue());
        return payData;
    }
 
    @Override
    public BrandWCPayRequestData startPayment(MallOrderInfo mallOrderInfo) throws Exception {
        BigDecimal unit = new BigDecimal("100");
        BigDecimal money = new BigDecimal(mallOrderInfo.getAmount().toString());
        BrandWCPayRequestData payData;
        String productNames = getProductNames(mallOrderInfo.getMemberId(), mallOrderInfo.getId());
        MallMember mallMember = mallMemberMapper.selectById(mallOrderInfo.getMemberId());
        Boolean debug = xcxProperties.getDebug();
        if (debug) {
            payData = weixinServiceUtil.createOrder("[测试]" + productNames, mallOrderInfo.getOrderNo(),
                    1, mallMember.getOpenId(), String.valueOf(mallOrderInfo.getId()));
        } else {
            payData = weixinServiceUtil.createOrder(productNames, mallOrderInfo.getOrderNo(),
                    unit.multiply(money).intValue(),mallMember.getOpenId(), String.valueOf(mallOrderInfo.getId()));
        }
        mallOrderInfo.setWxOrderNo(payData.getPrepay_id());
        mallOrderInfoMapper.updateById(mallOrderInfo);
        return payData;
    }
 
    @Override
    public void pushOrderToAddress(OrderStateDto info) {
        RestTemplate restTemplate = new RestTemplate();
        String url =  WechatConfigure.SEND_INFO_URL  + redisUtils.get(WechatConfigure.WX_ACCESS_TOKEN_REDIS_KEY);
        //拼接推送的模版
        OrderStateMsgVo orderStateMsgVo = new OrderStateMsgVo();
        orderStateMsgVo.setTouser(info.getOpenId());//用户的openId
        orderStateMsgVo.setTemplate_id(info.getTemplateId());//订阅消息模板id
        orderStateMsgVo.setPage(info.getPage());
        Map<String, WxTemplateData> m = new HashMap<>(5);
        m.put("character_string1", new WxTemplateData(info.getOrderNo()));
        m.put("thing9", new WxTemplateData(info.getGoodsName()));
        m.put("phrase2", new WxTemplateData(info.getOrderState()));
        m.put("thing13", new WxTemplateData(info.getAddressArea()));
        m.put("thing16", new WxTemplateData(info.getTakeCode()));
        orderStateMsgVo.setData(m);
        String s = JSONUtil.toJsonStr(orderStateMsgVo);
        log.info(s);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, orderStateMsgVo, String.class);
        log.info(responseEntity.getBody());
    }
 
    private static final String WXAPPLETURl="https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=";
 
    @Override
    public void uniformMessageSend(OrderStateDto info) {
        RestTemplate restTemplate = new RestTemplate();
        String url =  WXAPPLETURl + redisUtils.get(WechatConfigure.WX_ACCESS_TOKEN_REDIS_KEY);
        //拼接推送的模版
        /**
         * {
         *   "touser": "oJkRK4_pWN2kjp75B_G6oGSWawj0",
         *   "template_id": "Yk3_M11Pw5rablln7kQBpasfG9ynRNwD9OKsyvUSoWg",
         *   "page": "index",
         *   "miniprogram_state":"developer",
         *   "lang":"zh_CN",
         *   "data": {
         *         "character_string1": {
         *             "value": "2022081214472943380"
         *         },
         *         "thing16": {
         *             "value": "22704967"
         *         },
         *         "thing9": {
         *             "value": "商品"
         *         },
         *         "thing13": {
         *             "value": "测试"
         *         },
         *         "phrase2": {
         *             "value": "已送达"
         *         }
         *   }
         * }
         */
        OrderStateMsgVo orderStateMsgVo = new OrderStateMsgVo();
        orderStateMsgVo.setTouser(info.getOpenId());//用户的openId
        orderStateMsgVo.setTemplate_id(info.getTemplateId());//订阅消息模板id
        orderStateMsgVo.setPage(info.getPage());
        Map<String, WxTemplateData> m = new HashMap<>(5);
        m.put("character_string2", new WxTemplateData(info.getOrderNo()));
        m.put("thing11", new WxTemplateData(info.getGoodsName()));
        m.put("amount1", new WxTemplateData(info.getAmount()));
        m.put("character_string9", new WxTemplateData(info.getTakeCode()));
        orderStateMsgVo.setData(m);
        String s = JSONUtil.toJsonStr(orderStateMsgVo);
        log.info(s);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, orderStateMsgVo, String.class);
        log.info(responseEntity.getBody());
    }
 
    @Override
    public List<String> getTemplateId() {
        List<String> wxTemplates = new ArrayList<>();
        List<DataDictionaryCustom> wxTemplateList = dataDictionaryCustomMapper.selectDicByType(DataDictionaryEnum.WX_TEMPLATE_ID_ONE.getType());
        if(CollUtil.isNotEmpty(wxTemplateList)){
            for(DataDictionaryCustom dic : wxTemplateList){
                wxTemplates.add(dic.getValue());
            }
        }
        return wxTemplates;
    }
 
    @Override
    public FebsResponse generateQrCode(WxGenerateQrCodeDto wxGenerateQrCodeDto) {
        String base64 = null;
        try {
            RestTemplate restTemplate = new RestTemplate();
            String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + redisUtils.get(WechatConfigure.WX_ACCESS_TOKEN_REDIS_KEY);
            Map<String, Object> params = new HashMap<>();
            params.put("scene", wxGenerateQrCodeDto.getScene());
            params.put("page", wxGenerateQrCodeDto.getPage());
            params.put("width", 430);
            ResponseEntity<byte[]> responseEntity = restTemplate.postForEntity(url, params, byte[].class);
            if (responseEntity.getStatusCode() == HttpStatus.OK) {
                byte[] body = responseEntity.getBody();
                InputStream inputStream = new ByteArrayInputStream(body);
                // 将获取流转为base64格式
                byte[] data = null;
                ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
                byte[] buff = new byte[100];
                int rc = 0;
                while ((rc = inputStream.read(buff, 0, 100)) > 0) {
                    swapStream.write(buff, 0, rc);
                }
                data = swapStream.toByteArray();
                base64 = Base64.byteArrayToBase64(data);
                inputStream.close();
                swapStream.close();
            }
        } catch (IOException e) {
            throw new ApiException("生成二维码失败");
        }
        return new FebsResponse().success().data(base64);
    }
 
    /**
     * 根据用户ID和订单ID获取所购买商品名称
     * @return 所含商品名称(多个以","隔开)
     */
    public String getProductNames(Long memberId, Long orderId) {
        MallOrderInfo mallOrderInfo = mallOrderInfoMapper.selectOrderByMemberIdAndId(memberId, orderId);
        List<MallOrderItem> details = mallOrderInfo.getItems();
        if (CollectionUtils.isEmpty(details)) {
            return "";
        }
        StringBuffer productNameBuffer = new StringBuffer();
        Integer maxLength = 30;
        for (int i = 0; i< details.size(); i++) {
            MallOrderItem mallOrderItem = details.get(i);
            String goodsName = mallOrderItem.getGoodsName();
            if (goodsName == null) {
                continue;
            }
            if (i == 0 && goodsName.length() > maxLength) {
                productNameBuffer.append(goodsName.substring(0, maxLength) + "...");
                break;
            }
            if ((productNameBuffer.length() + goodsName.length()) > maxLength) {
                productNameBuffer.append("等");
                break;
            }
            productNameBuffer.append(goodsName + ",");
        }
        String productNames = productNameBuffer.toString();
        if (productNames.endsWith(",")) {
            productNames = productNames.substring(0, productNames.length() - 1);
        }
        if (productNames.endsWith(",等")) {
            productNames = productNames.substring(0, productNames.length() - 2) + "等";
        }
        return productNames;
    }
}