feat(服务号通知):新增通知模块功能

This commit is contained in:
2025-04-22 10:40:46 +08:00
parent bdfeb71287
commit 8b0a2cc636
24 changed files with 677 additions and 211 deletions
+3
View File
@@ -0,0 +1,3 @@
{
"java.compile.nullAnalysis.mode": "automatic"
}
+23
View File
@@ -20,3 +20,26 @@ CREATE INDEX idx_orders_device_time ON orders(device_sn, create_time);
-- 软删除标记 + 创建时间的联合索引(用于过滤已删除订单)
CREATE INDEX idx_orders_del_time ON orders(is_del, create_time);
服务号推送消息功能
1. 登录微信公众平台(mp.weixin.qq.com)
2. 配置服务器:
- 进入"设置与开发 -> 基本配置"
- 填写服务器配置
- URL: https://你的域名/wx/message
- Token: 与配置文件中的token一致
- EncodingAESKey: 点击随机生成,复制到配置文件
- 消息加解密方式: 选择安全模式
3. 配置消息模板:
- 进入"功能 -> 模板消息"
- 添加所需的消息模板
- 复制模板ID到配置文件
4. 配置云托管(如果使用):
- 进入"云托管"
- 创建环境
- 部署服务
- 配置域名
+10
View File
@@ -130,6 +130,16 @@
<version>5.0.3</version>
</dependency>
<!-- Spring Retry -->
<dependency>
<groupId>org.springframework.retry</groupId>
<artifactId>spring-retry</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
</dependencies>
<build>
@@ -1,25 +0,0 @@
package com.central.order.config;
import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
@Configuration
@Setter
@Getter
public class WechatMpConfig {
@Value("${tencent.notification.app-id}")
private String appId;
@Value("${tencent.notification.app-secret}")
private String appSecret;
@Value("${tencent.notification.token}")
private String token;
@Value("${tencent.notification.encoding-aes-key}")
private String encodingAesKey;
}
@@ -0,0 +1,49 @@
package com.central.order.config;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.config.impl.WxMpDefaultConfigImpl;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;
import java.nio.charset.StandardCharsets;
@Configuration
@RequiredArgsConstructor
public class WxMpConfiguration {
@Bean
@ConfigurationProperties(prefix = "wx.mp")
public WxMpProperties wxMpProperties() {
return new WxMpProperties();
}
@Bean
public WxMpService wxMpService(WxMpProperties wxMpProperties) {
WxMpService service = new WxMpServiceImpl();
WxMpDefaultConfigImpl config = new WxMpDefaultConfigImpl();
config.setAppId(wxMpProperties.getAppId());
config.setSecret(wxMpProperties.getSecret());
service.setWxMpConfigStorage(config);
return service;
}
@Bean
public RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
return restTemplate;
}
@Bean
public ObjectMapper objectMapper() {
return new ObjectMapper();
}
}
@@ -0,0 +1,54 @@
package com.central.order.config;
import lombok.Data;
@Data
public class WxMpProperties {
/**
* 设置微信公众号的appid
*/
private String appId;
/**
* 设置微信公众号的app secret
*/
private String secret;
/**
* 设置云托管环境ID
*/
private String cloudEnv;
/**
* 设置服务基础URL
*/
private String baseUrl;
/**
* 模板ID配置
*/
private TemplateConfig templateId = new TemplateConfig();
@Data
public static class TemplateConfig {
/**
* 支付成功通知模板ID
* 模板内容:
* 服务名称:{{thing2.DATA}}
* 出行时间:{{time3.DATA}}
* 订单号:{{character_string1.DATA}}
* 支付金额:{{amount4.DATA}}
*/
private String paymentSuccess;
/**
* 视频处理完成通知模板ID
*/
private String videoComplete;
/**
* 视频处理失败通知模板ID
*/
private String videoFail;
}
}
@@ -0,0 +1,35 @@
package com.central.order.constants;
public class WxConstants {
/**
* Redis key前缀
*/
public static final String REDIS_KEY_PREFIX = "wx:";
/**
* access_token相关
*/
public static class AccessToken {
public static final String CACHE_KEY = REDIS_KEY_PREFIX + "access_token";
public static final String LOCK_KEY = REDIS_KEY_PREFIX + "access_token:lock";
public static final long EXPIRE_TIME = 7000; // 7000秒
public static final long REFRESH_TIME = 5400000; // 1.5小时
}
/**
* 模板消息相关
*/
public static class Template {
public static final String API_SEND = "https://api.weixin.qq.com/cgi-bin/message/template/send";
public static final String API_GET_LIST = "https://api.weixin.qq.com/cgi-bin/template/get_all_private_template";
public static final String API_DELETE = "https://api.weixin.qq.com/cgi-bin/template/del_private_template";
}
/**
* 微信接口相关
*/
public static class Api {
public static final String ACCESS_TOKEN = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";
}
}
@@ -1,23 +0,0 @@
package com.central.order.controller;
import com.central.order.service.WechatNotificationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/wechat")
public class WechatNotificationController {
@Autowired
private WechatNotificationService notificationService;
@GetMapping("/send/notification")
public void sendNotification() {
String openId = "user_open_id";
String templateId = "template_id";
String data = "{\"first\":{\"value\":\"Hello\"},\"keyword1\":{\"value\":\"World\"}}";
notificationService.sendTemplateMessage(openId, templateId, data);
}
}
@@ -1,33 +0,0 @@
package com.central.order.controller;
import com.central.order.util.WechatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/wechat")
public class WechatVerificationController {
@Autowired
private WechatUtils weChatUtil;
@GetMapping
public String validate(@RequestParam("signature") String signature,
@RequestParam("timestamp") String timestamp,
@RequestParam("nonce") String nonce,
@RequestParam("echostr") String echostr) {
// 验证签名
if (weChatUtil.validateSignature(signature, timestamp, nonce)) {
return echostr;
}
return "invalid";
}
@PostMapping
public String handleMessage(@RequestBody String requestBody) {
// 处理微信服务器发送的消息
System.out.println("Received message: " + requestBody);
// 返回响应消息
return "success";
}
}
@@ -0,0 +1,39 @@
package com.central.order.controller;
import com.central.common.model.Result;
import com.central.order.service.IWxTemplateMessageService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@Slf4j
@RestController
@RequestMapping("/wx/test")
@RequiredArgsConstructor
public class WxTestController {
private final IWxTemplateMessageService templateMessageService;
@GetMapping("/template/send")
public Result<String> testSendTemplate(
@RequestParam String openId,
@RequestParam String orderNo,
@RequestParam String serviceName,
@RequestParam Integer rank) {
try {
// 发送消息
templateMessageService.sendPaymentSuccessNotice(
openId, orderNo, serviceName, rank);
return Result.succeed("发送成功");
} catch (Exception e) {
log.error("发送模板消息失败", e);
return Result.failed("发送失败:" + e.getMessage());
}
}
}
@@ -0,0 +1,135 @@
package com.central.order.handler;
import com.central.order.model.WxMessageRecord;
import com.central.order.model.WxUserSubscribe;
import com.central.order.service.IWxTemplateMessageService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
@Slf4j
@Component
@RequiredArgsConstructor
public class WxMessageHandler {
private final WxMpService wxMpService;
private final IWxTemplateMessageService templateMessageService;
public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage) {
try {
String msgType = wxMessage.getMsgType();
if (WxConsts.XmlMsgType.EVENT.equals(msgType)) {
return handleEventMessage(wxMessage);
}
return null;
} catch (Exception e) {
log.error("处理微信消息失败", e);
return null;
}
}
private WxMpXmlOutMessage handleEventMessage(WxMpXmlMessage wxMessage) {
String event = wxMessage.getEvent();
switch (event) {
case WxConsts.EventType.TEMPLATE_SEND_JOB_FINISH:
return handleTemplateSendJobFinish(wxMessage);
case WxConsts.EventType.SUBSCRIBE:
return handleSubscribeEvent(wxMessage);
case WxConsts.EventType.UNSUBSCRIBE:
return handleUnsubscribeEvent(wxMessage);
default:
log.info("未处理的事件类型:{}", event);
return null;
}
}
/**
* 处理模板消息发送完成事件
*/
private WxMpXmlOutMessage handleTemplateSendJobFinish(WxMpXmlMessage wxMessage) {
try {
String openId = wxMessage.getFromUser();
String msgId = wxMessage.getMsgId().toString();
String status = wxMessage.getStatus();
log.info("模板消息发送结果:openId={}, msgId={}, status={}",
openId, msgId, status);
// 更新消息发送状态
updateMessageStatus(openId, msgId, status);
} catch (Exception e) {
log.error("处理模板消息发送结果事件失败", e);
}
return null;
}
private WxMpXmlOutMessage handleSubscribeEvent(WxMpXmlMessage wxMessage) {
String openId = wxMessage.getFromUser();
log.info("用户关注:openId={}", openId);
// 保存用户关注状态
saveUserSubscribeStatus(openId, true);
return WxMpXmlOutMessage.TEXT()
.content("感谢关注!")
.fromUser(wxMessage.getToUser())
.toUser(openId)
.build();
}
private WxMpXmlOutMessage handleUnsubscribeEvent(WxMpXmlMessage wxMessage) {
String openId = wxMessage.getFromUser();
log.info("用户取消关注:openId={}", openId);
// 更新用户关注状态
saveUserSubscribeStatus(openId, false);
return null;
}
/**
* 更新消息发送状态
*/
private void updateMessageStatus(String openId, String msgId, String status) {
try {
WxMessageRecord record = WxMessageRecord.builder()
.openId(openId)
.msgId(msgId)
.status(status)
.updateTime(LocalDateTime.now())
.build();
// TODO: 调用消息记录服务更新状态
// messageRecordService.updateStatus(record);
} catch (Exception e) {
log.error("更新消息状态失败:openId={}, msgId={}", openId, msgId, e);
}
}
/**
* 保存用户关注状态
*/
private void saveUserSubscribeStatus(String openId, boolean isSubscribe) {
try {
WxUserSubscribe userSubscribe = WxUserSubscribe.builder()
.openId(openId)
.subscribed(isSubscribe)
.updateTime(LocalDateTime.now())
.build();
// TODO: 调用用户服务更新关注状态
// userSubscribeService.updateStatus(userSubscribe);
} catch (Exception e) {
log.error("更新用户关注状态失败:openId={}", openId, e);
}
}
}
@@ -151,10 +151,10 @@ public class OrderStatusChangeListener {
Integer queue = orderService.getOrderRankingByOrderId(order.getId(),tourism.getId());
if (sysUser.getOpenId() != null) {
wxTemplateMessageService.sendPaymentSuccessNotice(
order.getOrderNo(),
sysUser.getOpenId(),
queue,
tourism.getTourismName()
order.getOrderNo(),
tourism.getTourismName(),
queue
);
}
@@ -0,0 +1,29 @@
package com.central.order.model;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.IdType;
import java.time.LocalDateTime;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@TableName("wx_message_record")
public class WxMessageRecord {
@TableId(type = IdType.AUTO)
private Long id;
private String openId;
private String templateId;
private String msgId;
private String content;
private String status;
private String errorMsg;
private LocalDateTime createTime;
private LocalDateTime updateTime;
}
@@ -0,0 +1,44 @@
package com.central.order.model;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class WxTemplateInfo {
/**
* 模板ID
*/
private String priTmplId;
/**
* 模板标题
*/
private String title;
/**
* 模板内容
*/
private String content;
/**
* 模板示例
*/
private String example;
/**
* 类型
*/
private Integer type;
/**
* 创建时间
*/
private Date createTime;
}
@@ -0,0 +1,20 @@
package com.central.order.model;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.LocalDateTime;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class WxUserSubscribe {
private Long id;
private String openId;
private Boolean subscribed;
private LocalDateTime createTime;
private LocalDateTime updateTime;
}
@@ -0,0 +1,29 @@
package com.central.order.scheduler;
import com.central.order.service.IWxAccessTokenService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Slf4j
@Component
@RequiredArgsConstructor
public class WxAccessTokenRefreshTask {
@Autowired
private IWxAccessTokenService wxAccessTokenService;
/**
* 每100分钟刷新一次access_token
*/
// @Scheduled(initialDelay = 60000, fixedRate = 6000000)
public void refreshAccessToken() {
try {
log.info("开始执行定时刷新access_token任务");
wxAccessTokenService.refreshAccessToken();
} catch (Exception e) {
log.error("定时刷新access_token失败", e);
}
}
}
@@ -0,0 +1,14 @@
package com.central.order.service;
public interface IWxAccessTokenService {
/**
* 获取access_token
* @return access_token
*/
String getAccessToken();
/**
* 刷新access_token
*/
String refreshAccessToken();
}
@@ -2,12 +2,8 @@ package com.central.order.service;
public interface IWxTemplateMessageService {
/**
* 发送订单支付成功通知
* @param orderNo 订单号
* @param openId 用户openId
* @param rank 排队信息
* @param tourismName 景区名称
* 发送支付成功通知
*/
void sendPaymentSuccessNotice(String orderNo, String openId,
Integer rank, String tourismName);
void sendPaymentSuccessNotice(String openId, String orderNo, String tourismName,
Integer rank);
}
@@ -1,33 +0,0 @@
package com.central.order.service;
import com.central.order.config.WechatMpConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
@Service
public class WechatMpService {
@Autowired
private WechatMpConfig weChatConfig;
private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={appid}&secret={appsecret}";
public String getAccessToken() {
RestTemplate restTemplate = new RestTemplate();
String response = restTemplate.getForObject(ACCESS_TOKEN_URL, String.class, weChatConfig.getAppId(), weChatConfig.getAppSecret());
// 解析response获取access_token
// 这里假设返回的JSON格式为 {"access_token":"xxxxx","expires_in":7200}
return parseAccessToken(response);
}
private String parseAccessToken(String response) {
// 使用Jackson解析JSON
try {
com.fasterxml.jackson.databind.JsonNode node = new com.fasterxml.jackson.databind.ObjectMapper().readTree(response);
return node.get("access_token").asText();
} catch (Exception e) {
throw new RuntimeException("Failed to parse access token", e);
}
}
}
@@ -1,22 +0,0 @@
package com.central.order.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
@Service
public class WechatNotificationService {
@Autowired
private WechatMpService wechatService;
private static final String SEND_TEMPLATE_MESSAGE_URL = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={access_token}";
public void sendTemplateMessage(String openId, String templateId, String data) {
String accessToken = wechatService.getAccessToken();
RestTemplate restTemplate = new RestTemplate();
String requestBody = String.format("{\"touser\":\"%s\",\"template_id\":\"%s\",\"data\":%s}", openId, templateId, data);
restTemplate.postForObject(SEND_TEMPLATE_MESSAGE_URL, requestBody, String.class, accessToken);
}
}
@@ -0,0 +1,103 @@
package com.central.order.service.impl;
import com.central.common.exception.BusinessException;
import com.central.order.service.IWxAccessTokenService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Recover;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
@Slf4j
@Service
@RequiredArgsConstructor
public class WxAccessTokenServiceImpl implements IWxAccessTokenService {
private final WxMpService wxMpService;
private final StringRedisTemplate redisTemplate;
private static final String ACCESS_TOKEN_KEY = "wx:access_token";
private static final String ACCESS_TOKEN_LOCK_KEY = "wx:access_token:lock";
@Override
public String getAccessToken() {
// 先从Redis获取
String accessToken = redisTemplate.opsForValue().get(ACCESS_TOKEN_KEY);
if (StringUtils.isNotBlank(accessToken)) {
return accessToken;
}
// 获取分布式锁
String lockValue = UUID.randomUUID().toString();
boolean locked = redisTemplate.opsForValue()
.setIfAbsent(ACCESS_TOKEN_LOCK_KEY, lockValue, 30, TimeUnit.SECONDS);
if (!locked) {
// 如果没有获取到锁,等待100ms后重试
try {
Thread.sleep(100);
return getAccessToken();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new BusinessException("获取access_token被中断");
}
}
try {
// 双重检查
accessToken = redisTemplate.opsForValue().get(ACCESS_TOKEN_KEY);
if (StringUtils.isNotBlank(accessToken)) {
return accessToken;
}
// 刷新token
return refreshAccessToken();
} finally {
// 释放锁
if (lockValue.equals(redisTemplate.opsForValue().get(ACCESS_TOKEN_LOCK_KEY))) {
redisTemplate.delete(ACCESS_TOKEN_LOCK_KEY);
}
}
}
@Retryable(
value = {WxErrorException.class, RestClientException.class},
maxAttempts = 3,
backoff = @Backoff(delay = 2000, multiplier = 2)
)
public String refreshAccessToken() {
try {
log.info("开始刷新access_token");
String newToken = wxMpService.getAccessToken();
// 设置到Redis,有效期设置为110分钟(微信token有效期120分钟)
redisTemplate.opsForValue().set(ACCESS_TOKEN_KEY, newToken, 110, TimeUnit.MINUTES);
log.info("刷新access_token成功");
return newToken;
} catch (Exception e) {
log.error("刷新access_token失败", e);
throw new BusinessException("刷新access_token失败:" + e.getMessage());
}
}
@Recover
public String recover(Exception e) {
log.error("刷新access_token重试耗尽", e);
// 发送告警通知
sendAlertNotification("刷新access_token失败,请检查网络和配置");
throw new BusinessException("刷新access_token失败,请稍后重试");
}
private void sendAlertNotification(String message) {
// TODO: 实现告警通知逻辑
}
}
@@ -1,53 +1,103 @@
package com.central.order.service.impl;
import com.central.common.exception.BusinessException;
import com.central.order.config.WxMpProperties;
import com.central.order.service.IWxTemplateMessageService;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.apache.commons.lang3.StringUtils;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Recover;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
@Slf4j
@Service
@RequiredArgsConstructor
public class WxTemplateMessageServiceImpl implements IWxTemplateMessageService {
@Autowired
private WxMpService wxMpService;
@Value("${wx.mp.templateId.paymentSuccess}")
private String paymentSuccessTemplateId;
private final WxMpService wxMpService;
private final WxMpProperties wxMpProperties;
private final RestTemplate restTemplate;
private final ObjectMapper objectMapper;
@Override
public void sendPaymentSuccessNotice(String orderNo, String openId,
Integer rank, String tourismName) {
@Retryable(value = WxErrorException.class, maxAttempts = 3, backoff = @Backoff(delay = 1000, multiplier = 2))
public void sendPaymentSuccessNotice(String openId, String orderNo, String tourismName,
Integer rank) {
log.info("准备发送支付成功通知: openId={}, orderNo={}, serviceName={}, amount={}, tourTime={}",
openId, orderNo, tourismName, rank);
// 参数验证
if (StringUtils.isAnyBlank(openId, orderNo, tourismName)) {
throw new BusinessException("参数不能为空");
}
try {
// 构建模板消息
WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
.toUser(openId)
.templateId(paymentSuccessTemplateId)
.build();
.toUser(openId)
.templateId(wxMpProperties.getTemplateId().getPaymentSuccess())
.data(Arrays.asList(
new WxMpTemplateData("thing2", tourismName+"提示:您当前排在第"+rank+"位!"),
new WxMpTemplateData("time3", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))),
new WxMpTemplateData("character_string1", orderNo),
new WxMpTemplateData("amount4", "19.90")
))
.build();
// 设置模板数据
templateMessage.addData(new WxMpTemplateData("first", "您的订单支付成功!", "#173177"))
.addData(new WxMpTemplateData("订单编号:", orderNo))
.addData(new WxMpTemplateData("当前排在第", rank + "位"))
.addData(new WxMpTemplateData("您所在的景区:", tourismName))
.addData(new WxMpTemplateData("预计等待时间", Math.multiplyExact(rank,2)+""))
.addData(new WxMpTemplateData("remark",
"感谢您的支付!\n请前往景区出示订单完成体验。\n如有问题请联系客服。"));
// 发送消息并获取消息ID
String msgId = wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
// 发送模板消息
wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
// 记录发送结果
log.info("模板消息发送成功: openId={}, orderNo={}, msgId={}", openId, orderNo, msgId);
log.info("发送支付成功通知成功: orderNo={}, openId={}, amount={}",
orderNo, openId, rank);
// 保存发送记录
saveMessageRecord(openId, orderNo, msgId, templateMessage);
} catch (Exception e) {
log.error("发送支付成功通知失败: orderNo={}, openId={}", orderNo, openId, e);
} catch (WxErrorException e) {
log.error("发送模板消息失败: openId={}, orderNo={}, errorCode={}, errorMsg={}",
openId, orderNo, e.getError().getErrorCode(), e.getError().getErrorMsg());
throw new BusinessException("发送失败:" + e.getError().getErrorMsg());
}
}
private String formatDateTime(LocalDateTime dateTime) {
if (dateTime == null) {
return "";
}
return dateTime.format(DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm"));
}
private String formatAmount(BigDecimal amount) {
if (amount == null) {
return "0.00";
}
return amount.setScale(2, RoundingMode.HALF_UP).toString() + "元";
}
private void saveMessageRecord(String openId, String orderNo, String msgId,
WxMpTemplateMessage templateMessage) {
// TODO: 实现消息发送记录保存逻辑
}
@Recover
public void recover(WxErrorException e, String openId, String orderNo,
String serviceName, BigDecimal amount, LocalDateTime tourTime) {
log.error("发送模板消息重试耗尽: openId={}, orderNo={}, error={}",
openId, orderNo, e.getMessage());
// TODO: 实现失败处理逻辑
}
}
@@ -1,37 +0,0 @@
package com.central.order.util;
import com.central.order.config.WechatMpConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.security.MessageDigest;
import java.util.Arrays;
@Component
public class WechatUtils {
@Autowired
private WechatMpConfig wechatMpConfig;
public boolean validateSignature(String signature, String timestamp, String nonce) {
String[] arr = new String[]{wechatMpConfig.getToken(), timestamp, nonce};
Arrays.sort(arr);
String content = arr[0] + arr[1] + arr[2];
String calculatedSignature = sha1(content);
return calculatedSignature != null && calculatedSignature.equals(signature);
}
private String sha1(String str) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-1");
byte[] digest = md.digest(str.getBytes());
StringBuilder hexString = new StringBuilder();
for (byte b : digest) {
hexString.append(String.format("%02x", b));
}
return hexString.toString();
} catch (Exception e) {
throw new RuntimeException("Failed to calculate SHA-1", e);
}
}
}
@@ -85,6 +85,12 @@ aliyun:
wx:
mp:
templateId:
paymentSuccess: 你的支付成功通知模板ID
app-id: ${WX_APP_ID:wx0ea85b13966d88e1}
secret: ${WX_APP_SECRET:a90637566b2b73f41f8b1dabd64dc32b}
cloud-env: ${WX_CLOUD_ENV:prod-1gyj8ywz55460ab1}
base-url: https://springboot-ztti-156622-7-1355625269.sh.run.tcloudbase.com
template-id:
payment-success: uscmjgLdw0cKBRq8vFyCOPbYj7p-fHuEOIhFwwIAe4A # 支付成功通知模板ID
video-complete: TEMPLATE_ID_2 # 视频完成通知模板ID
video-failure: TEMPLATE_ID_3 # 视频失败通知模板ID