puzhibing
昨天 63b68c39653208a1756640034c028789946d0e12
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
package com.ruoyi.order.service.impl;
 
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.account.api.feignClient.AppUserClient;
import com.ruoyi.account.api.model.TAppUser;
import com.ruoyi.chargingPile.api.model.Site;
import com.ruoyi.chargingPile.api.model.TChargingGun;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.order.api.model.TChargingOrder;
import com.ruoyi.order.api.model.TOrderEvaluate;
import com.ruoyi.order.service.WxSubscribeMessageService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;
 
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.LinkedHashMap;
import java.util.Map;
 
@Service
public class WxSubscribeMessageServiceImpl implements WxSubscribeMessageService {
 
    private static final Logger log = LoggerFactory.getLogger(WxSubscribeMessageServiceImpl.class);
    private static final String SEND_URL = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token={accessToken}";
 
    @Resource
    private AppUserClient appUserClient;
    @Resource
    private RestTemplate restTemplate;
 
    @Override
    public void sendChargeStart(TChargingOrder order, Site site, TChargingGun chargingGun) {
        if (order == null) {
            return;
        }
        Map<String, String> data = new LinkedHashMap<>();
        data.put("thing16", limit(siteName(site), 20));
        data.put("thing17", limit(gunCode(chargingGun), 20));
        data.put("amount10", amount(order.getRechargeAmount()));
        data.put("thing21", limit(defaultText(order.getPlateNum(), "未填写"), 20));
        send(WxSubscribeTemplate.CHARGE_START, order.getAppUserId(), page(WxSubscribeTemplate.CHARGE_START, order), data);
    }
 
    @Override
    public void sendChargeEnd(TChargingOrder order, Site site, TChargingGun chargingGun) {
        if (order == null) {
            return;
        }
        Map<String, String> data = new LinkedHashMap<>();
        data.put("thing6", limit(siteName(site), 20));
        data.put("character_string15", limit(gunCode(chargingGun), 32));
        data.put("amount33", amount(order.getPaymentAmount() == null ? order.getOrderAmount() : order.getPaymentAmount()));
        data.put("amount18", amount(order.getRefundAmount()));
        data.put("thing3", limit(endReason(order.getEndMode()), 20));
        send(WxSubscribeTemplate.CHARGE_END, order.getAppUserId(), page(WxSubscribeTemplate.CHARGE_END, order), data);
    }
 
    @Override
    public void sendEvaluationReply(TOrderEvaluate orderEvaluate, TChargingOrder order, Site site) {
        if (orderEvaluate == null) {
            return;
        }
        Map<String, String> data = new LinkedHashMap<>();
        data.put("thing1", limit(siteName(site), 20));
        data.put("thing3", limit(defaultText(orderEvaluate.getEvaluationResponse(), "平台已回复您的评价"), 20));
        send(WxSubscribeTemplate.SERVICE_EVALUATION, orderEvaluate.getAppUserId(), WxSubscribeTemplate.SERVICE_EVALUATION.getDefaultPage(), data);
    }
 
    @Override
    public void sendPriceDrop(Long appUserId, Site site, BigDecimal price) {
        Map<String, String> data = new LinkedHashMap<>();
        data.put("thing1", limit(siteName(site), 20));
        data.put("amount4", amount(price));
        send(WxSubscribeTemplate.PRICE_DROP, appUserId, priceDropPage(site), data);
    }
 
    private void send(WxSubscribeTemplate template, Long appUserId, String page, Map<String, String> data) {
        try {
            if (appUserId == null) {
                return;
            }
            R<TAppUser> userResult = appUserClient.getUserById(appUserId);
            TAppUser appUser = userResult == null ? null : userResult.getData();
            if (appUser == null || !StringUtils.hasText(appUser.getWxOpenid())) {
                log.info("微信订阅消息未发送,用户openid为空,template={}, appUserId={}", template.name(), appUserId);
                return;
            }
            R<String> tokenResult = appUserClient.getWXToken();
            String accessToken = tokenResult == null ? null : tokenResult.getData();
            if (!StringUtils.hasText(accessToken)) {
                log.warn("微信订阅消息未发送,access_token为空,template={}, appUserId={}", template.name(), appUserId);
                return;
            }
            JSONObject payload = buildPayload(appUser.getWxOpenid(), template, page, data);
            JSONObject response = restTemplate.postForObject(SEND_URL, payload, JSONObject.class, accessToken);
            if (response != null && response.getIntValue("errcode") != 0) {
                log.warn("微信订阅消息发送失败,template={}, appUserId={}, response={}", template.name(), appUserId, response);
            }
        } catch (Exception e) {
            log.warn("微信订阅消息发送异常,template={}, appUserId={}", template.name(), appUserId, e);
        }
    }
 
    static JSONObject buildPayload(String openid, WxSubscribeTemplate template, String page, Map<String, String> data) {
        JSONObject payload = new JSONObject();
        payload.put("touser", openid);
        payload.put("template_id", template.getTemplateId());
        if (StringUtils.hasText(page)) {
            payload.put("page", page);
        }
        JSONObject dataJson = new JSONObject();
        for (Map.Entry<String, String> entry : data.entrySet()) {
            JSONObject value = new JSONObject();
            value.put("value", entry.getValue());
            dataJson.put(entry.getKey(), value);
        }
        payload.put("data", dataJson);
        return payload;
    }
 
    private static String page(WxSubscribeTemplate template, TChargingOrder order) {
        if (order == null || order.getChargingGunId() == null) {
            return template.getDefaultPage();
        }
        return template.getDefaultPage() + "?gunId=" + order.getChargingGunId();
    }
 
    private static String priceDropPage(Site site) {
        if (site == null || site.getId() == null) {
            return WxSubscribeTemplate.PRICE_DROP.getDefaultPage();
        }
        return WxSubscribeTemplate.PRICE_DROP.getDefaultPage() + "?id=" + site.getId();
    }
 
    private static String siteName(Site site) {
        return site == null ? "充电站" : defaultText(site.getName(), "充电站");
    }
 
    private static String gunCode(TChargingGun chargingGun) {
        if (chargingGun == null) {
            return "充电桩";
        }
        if (StringUtils.hasText(chargingGun.getFullNumber())) {
            return chargingGun.getFullNumber();
        }
        if (StringUtils.hasText(chargingGun.getCode())) {
            return chargingGun.getCode();
        }
        return defaultText(chargingGun.getName(), "充电桩");
    }
 
    private static String amount(BigDecimal value) {
        return (value == null ? BigDecimal.ZERO : value).setScale(2, RoundingMode.HALF_UP).toPlainString() + "元";
    }
 
    private static String endReason(Integer endMode) {
        if (endMode == null) {
            return "充电结束";
        }
        switch (endMode) {
            case 0:
                return "异常终止";
            case 1:
                return "主动终止";
            case 2:
                return "满电终止";
            case 3:
                return "费用不足终止";
            default:
                return "充电结束";
        }
    }
 
    private static String defaultText(String value, String defaultValue) {
        return StringUtils.hasText(value) ? value : defaultValue;
    }
 
    private static String limit(String value, int maxLength) {
        if (value == null || value.length() <= maxLength) {
            return value;
        }
        return value.substring(0, maxLength);
    }
}