fix(微信通知):新增微信公众号通知逻辑

This commit is contained in:
2025-03-11 11:20:53 +08:00
parent c56b1c1f04
commit 66abda77d5
7 changed files with 180 additions and 0 deletions
+7
View File
@@ -96,6 +96,13 @@
<version>0.2.15</version>
</dependency>
<!-- 微信公众号 SDK -->
<dependency>
<groupId>com.github.binarywang</groupId>
<artifactId>weixin-java-mp</artifactId>
<version>4.5.0</version>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
@@ -0,0 +1,25 @@
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("${wechat.app-id}")
private String appId;
@Value("${wechat.app-secret}")
private String appSecret;
@Value("${wechat.token}")
private String token;
@Value("${wechat.encoding-aes-key}")
private String encodingAesKey;
}
@@ -0,0 +1,23 @@
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("/sendNotification")
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);
}
}
@@ -0,0 +1,33 @@
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,33 @@
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);
}
}
}
@@ -0,0 +1,22 @@
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,37 @@
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);
}
}
}