修复微信审核回调支持JSON格式

This commit is contained in:
2026-11-03 10:11:13 +08:00
parent 083ec972e3
commit de014483a8
4 changed files with 166 additions and 4 deletions
@@ -46,7 +46,12 @@ public class WechatContentModerationCallbackController {
return echoString;
}
@PostMapping(value = "/callback", consumes = {MediaType.APPLICATION_XML_VALUE, MediaType.TEXT_XML_VALUE})
@PostMapping(value = "/callback", consumes = {
MediaType.APPLICATION_JSON_VALUE,
"application/*+json",
MediaType.APPLICATION_XML_VALUE,
MediaType.TEXT_XML_VALUE
})
public String callback(@RequestParam("timestamp") String timestamp,
@RequestParam("nonce") String nonce,
@RequestParam(value = "msg_signature", required = false) String messageSignature,
@@ -54,7 +59,7 @@ public class WechatContentModerationCallbackController {
@RequestParam(value = "encrypt_type", required = false) String encryptType,
@org.springframework.web.bind.annotation.RequestBody String body) throws Exception {
ModerationRuntimeConfig config = requireWechatConfig();
String encrypted = crypto.encryptedValue(body);
String encrypted = extractEncryptedPayload(body);
String expectedSignature = "aes".equalsIgnoreCase(encryptType) ? messageSignature : signature;
if (!crypto.verify(config.getCallbackToken(), timestamp, nonce,
"aes".equalsIgnoreCase(encryptType) ? encrypted : "", expectedSignature)) {
@@ -84,6 +89,22 @@ public class WechatContentModerationCallbackController {
return "success";
}
private String extractEncryptedPayload(String body) throws Exception {
if (!StringUtils.hasText(body)) {
throw new IllegalArgumentException("微信审核回调消息体为空");
}
String trimmed = body.trim();
if (trimmed.startsWith("{")) {
JsonNode root = objectMapper.readTree(trimmed);
String encrypted = firstText(root, "Encrypt", "encrypt");
if (!StringUtils.hasText(encrypted)) {
throw new IllegalArgumentException("微信审核回调 JSON 缺少 Encrypt 字段");
}
return encrypted;
}
return crypto.encryptedValue(body);
}
private String firstText(JsonNode node, String... keys) {
for (String key : keys) if (node != null && node.hasNonNull(key)) return node.path(key).asText();
return null;