From 029b7cc578637c13fe5a9db987d566bfd5591b59 Mon Sep 17 00:00:00 2001 From: xiaowang <2161656029@qq.com> Date: Wed, 4 Nov 2026 11:16:04 +0800 Subject: [PATCH 1/2] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E7=B3=BB=E7=BB=9F?= =?UTF-8?q?=E6=8E=A5=E5=85=A5=E8=AF=8A=E6=96=AD=E5=9F=BA=E7=A1=80=E8=83=BD?= =?UTF-8?q?=E5=8A=9B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...atContentModerationCallbackController.java | 16 +- .../WechatContentModerationProvider.java | 17 +- ...dminSecureIntegrationConfigController.java | 30 ++ .../dto/IntegrationProbeRequestDTO.java | 18 + .../entity/IntegrationProbeResultDO.java | 54 +++ .../mapper/IntegrationProbeResultMapper.java | 9 + .../service/IntegrationProbeService.java | 15 + .../impl/IntegrationProbeServiceImpl.java | 447 ++++++++++++++++++ .../system/vo/IntegrationProbeCheckVO.java | 14 + .../system/vo/IntegrationProbeResultVO.java | 20 + .../V15__系统接入诊断结果_20261104.sql | 22 + JC-Salon-Frontend/src/api/admin.ts | 29 ++ .../src/views/admin/SystemSettingsView.vue | 92 +++- 13 files changed, 778 insertions(+), 5 deletions(-) create mode 100644 JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/dto/IntegrationProbeRequestDTO.java create mode 100644 JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/entity/IntegrationProbeResultDO.java create mode 100644 JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/mapper/IntegrationProbeResultMapper.java create mode 100644 JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/service/IntegrationProbeService.java create mode 100644 JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/service/impl/IntegrationProbeServiceImpl.java create mode 100644 JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/vo/IntegrationProbeCheckVO.java create mode 100644 JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/vo/IntegrationProbeResultVO.java create mode 100644 JC-Salon-Core/src/main/resources/db/migration/V15__系统接入诊断结果_20261104.sql diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/controller/front/WechatContentModerationCallbackController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/controller/front/WechatContentModerationCallbackController.java index 81d2e1fd..fa0e972b 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/controller/front/WechatContentModerationCallbackController.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/controller/front/WechatContentModerationCallbackController.java @@ -7,6 +7,7 @@ import com.xiaowang.jayucloud.salon.core.modules.privacy.service.ContentModerati import com.xiaowang.jayucloud.salon.core.modules.privacy.support.WechatCallbackCrypto; import com.xiaowang.jayucloud.salon.core.modules.system.secure.ModerationRuntimeConfig; import com.xiaowang.jayucloud.salon.core.modules.system.service.SecureIntegrationConfigService; +import com.xiaowang.jayucloud.salon.core.modules.system.service.IntegrationProbeService; import lombok.RequiredArgsConstructor; import org.springframework.http.MediaType; import org.springframework.util.StringUtils; @@ -24,6 +25,7 @@ public class WechatContentModerationCallbackController { private final WechatMiniProperties wechatProperties; private final WechatCallbackCrypto crypto; private final ContentModerationService contentModerationService; + private final IntegrationProbeService integrationProbeService; private final ObjectMapper objectMapper; @GetMapping("/callback") @@ -88,7 +90,9 @@ public class WechatContentModerationCallbackController { extra = firstText(root, "extra", "Extra"); } if (!StringUtils.hasText(taskId)) throw new IllegalArgumentException("微信审核回调缺少任务标识"); - contentModerationService.handleWechatImageResult(taskId, suggest, reason, decodeSourceEnvVersion(extra)); + if (!integrationProbeService.handleImageCallback(taskId, suggest, decodeProbeId(extra))) { + contentModerationService.handleWechatImageResult(taskId, suggest, reason, decodeSourceEnvVersion(extra)); + } return "success"; } @@ -102,6 +106,16 @@ public class WechatContentModerationCallbackController { } } + private String decodeProbeId(String extra) { + if (!StringUtils.hasText(extra)) return null; + try { + JsonNode payload = objectMapper.readTree(extra); + return firstText(payload, "probeId", "probe_id"); + } catch (Exception ignored) { + return null; + } + } + private String extractEncryptedPayload(String body) throws Exception { if (!StringUtils.hasText(body)) { throw new IllegalArgumentException("微信审核回调消息体为空"); diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/moderation/WechatContentModerationProvider.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/moderation/WechatContentModerationProvider.java index 20fb1caa..28509fb4 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/moderation/WechatContentModerationProvider.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/moderation/WechatContentModerationProvider.java @@ -62,6 +62,21 @@ public class WechatContentModerationProvider implements ContentModerationProvide @Override public ModerationOutcome submitImage(String contentType, String imageUrl, String openId, String sourceEnvVersion) { + return submitImageWithExtra(contentType, imageUrl, openId, encodeSourceEnvVersion(sourceEnvVersion)); + } + + public ModerationOutcome submitTestImage(String imageUrl, String openId, String probeId) { + Map extra = new LinkedHashMap<>(); + extra.put("envVersion", "trial"); + extra.put("probeId", probeId); + try { + return submitImageWithExtra("INTEGRATION_PROBE", imageUrl, openId, objectMapper.writeValueAsString(extra)); + } catch (java.io.IOException exception) { + throw new IllegalStateException("无法编码微信审核测试标识", exception); + } + } + + private ModerationOutcome submitImageWithExtra(String contentType, String imageUrl, String openId, String extra) { if (!StringUtils.hasText(openId)) return pending("OPENID_REQUIRED", "缺少微信作者身份,转人工复核"); if (!StringUtils.hasText(imageUrl) || !imageUrl.startsWith("https://")) { return retry("IMAGE_URL_INVALID", "审核图片需要短期有效的 HTTPS 地址"); @@ -72,7 +87,7 @@ public class WechatContentModerationProvider implements ContentModerationProvide payload.put("version", 2); payload.put("scene", properties.getScene()); payload.put("openid", openId); - payload.put("extra", encodeSourceEnvVersion(sourceEnvVersion)); + payload.put("extra", extra); return parseResult(post(IMAGE_CHECK_URL, payload), true); } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/controller/admin/AdminSecureIntegrationConfigController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/controller/admin/AdminSecureIntegrationConfigController.java index a03c6149..f02f5fd9 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/controller/admin/AdminSecureIntegrationConfigController.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/controller/admin/AdminSecureIntegrationConfigController.java @@ -7,7 +7,10 @@ import com.xiaowang.jayucloud.salon.core.modules.security.support.AdminScopeHelp import com.xiaowang.jayucloud.salon.core.modules.security.support.SecurityAuditActions; import com.xiaowang.jayucloud.salon.core.modules.security.support.SecurityAuditSupport; import com.xiaowang.jayucloud.salon.core.modules.system.dto.SecureIntegrationConfigDTO; +import com.xiaowang.jayucloud.salon.core.modules.system.dto.IntegrationProbeRequestDTO; +import com.xiaowang.jayucloud.salon.core.modules.system.service.IntegrationProbeService; import com.xiaowang.jayucloud.salon.core.modules.system.service.SecureIntegrationConfigService; +import com.xiaowang.jayucloud.salon.core.modules.system.vo.IntegrationProbeResultVO; import com.xiaowang.jayucloud.salon.core.modules.system.vo.SecureIntegrationConfigVO; import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; import lombok.RequiredArgsConstructor; @@ -20,12 +23,14 @@ import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest; import javax.validation.Valid; import java.util.Map; +import java.util.List; @RestController @RequiredArgsConstructor @RequestMapping("/admin/system-settings/secure-integration") public class AdminSecureIntegrationConfigController { private final SecureIntegrationConfigService secureIntegrationConfigService; + private final IntegrationProbeService integrationProbeService; private final AdminScopeHelper adminScopeHelper; private final SecurityAuditSupport securityAuditSupport; @@ -74,4 +79,29 @@ public class AdminSecureIntegrationConfigController { throw exception; } } + + @GetMapping("/probe-results") + @RequirePermission("messagehub:config:manage") + public Result> listProbeResults(HttpServletRequest request) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(integrationProbeService.listLatest(currentUser)); + } + + @PostMapping("/probe") + @RequirePermission("messagehub:config:manage") + @OperationGuard(action = "secure-integration-probe", ttlSeconds = 8, message = "接入测试处理中,请勿重复提交") + public Result probe(HttpServletRequest request, + @Valid @RequestBody IntegrationProbeRequestDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + try { + IntegrationProbeResultVO result = integrationProbeService.probe(currentUser, dto); + securityAuditSupport.success(request, SecurityAuditActions.SECURE_CONFIG_UPDATE, + "probe=" + dto.getService() + "/" + dto.getOperation() + ",status=" + result.getStatus()); + return Result.success(result); + } catch (RuntimeException exception) { + securityAuditSupport.fail(request, SecurityAuditActions.SECURE_CONFIG_UPDATE, + "probe=" + dto.getService() + "/" + dto.getOperation()); + throw exception; + } + } } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/dto/IntegrationProbeRequestDTO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/dto/IntegrationProbeRequestDTO.java new file mode 100644 index 00000000..d93fab43 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/dto/IntegrationProbeRequestDTO.java @@ -0,0 +1,18 @@ +package com.xiaowang.jayucloud.salon.core.modules.system.dto; + +import lombok.Data; + +import javax.validation.constraints.NotBlank; + +@Data +public class IntegrationProbeRequestDTO { + @NotBlank(message = "测试服务不能为空") + private String service; + + @NotBlank(message = "测试操作不能为空") + private String operation; + + private String mode = "DIAGNOSTIC"; + private String targetPhone; + private Boolean confirmed; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/entity/IntegrationProbeResultDO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/entity/IntegrationProbeResultDO.java new file mode 100644 index 00000000..8c4510d3 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/entity/IntegrationProbeResultDO.java @@ -0,0 +1,54 @@ +package com.xiaowang.jayucloud.salon.core.modules.system.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import com.xiaowang.jayucloud.salon.core.common.entity.BaseEntity; +import lombok.Data; +import lombok.EqualsAndHashCode; + +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_integration_probe_result") +public class IntegrationProbeResultDO extends BaseEntity { + @TableField("service_code") + private String serviceCode; + + @TableField("operation_code") + private String operationCode; + + @TableField("mode") + private String mode; + + @TableField("provider") + private String provider; + + @TableField("status") + private String status; + + @TableField("summary") + private String summary; + + @TableField("error_code") + private String errorCode; + + @TableField("checks_json") + private String checksJson; + + @TableField("remote_task_id") + private String remoteTaskId; + + @TableField("correlation_key") + private String correlationKey; + + @TableField("temporary_object_provider") + private String temporaryObjectProvider; + + @TableField("temporary_object_name") + private String temporaryObjectName; + + @TableField("expires_at") + private java.time.LocalDateTime expiresAt; + + @TableField("checked_at") + private java.time.LocalDateTime checkedAt; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/mapper/IntegrationProbeResultMapper.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/mapper/IntegrationProbeResultMapper.java new file mode 100644 index 00000000..46b6bcab --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/mapper/IntegrationProbeResultMapper.java @@ -0,0 +1,9 @@ +package com.xiaowang.jayucloud.salon.core.modules.system.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.jayucloud.salon.core.modules.system.entity.IntegrationProbeResultDO; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface IntegrationProbeResultMapper extends BaseMapper { +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/service/IntegrationProbeService.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/service/IntegrationProbeService.java new file mode 100644 index 00000000..9507bd9a --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/service/IntegrationProbeService.java @@ -0,0 +1,15 @@ +package com.xiaowang.jayucloud.salon.core.modules.system.service; + +import com.xiaowang.jayucloud.salon.core.modules.system.dto.IntegrationProbeRequestDTO; +import com.xiaowang.jayucloud.salon.core.modules.system.vo.IntegrationProbeResultVO; +import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; + +import java.util.List; + +public interface IntegrationProbeService { + IntegrationProbeResultVO probe(UserDO currentUser, IntegrationProbeRequestDTO request); + + List listLatest(UserDO currentUser); + + boolean handleImageCallback(String taskId, String suggest, String probeId); +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/service/impl/IntegrationProbeServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/service/impl/IntegrationProbeServiceImpl.java new file mode 100644 index 00000000..f1cb0d62 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/service/impl/IntegrationProbeServiceImpl.java @@ -0,0 +1,447 @@ +package com.xiaowang.jayucloud.salon.core.modules.system.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.JsonNode; +import com.xiaowang.jayucloud.salon.core.config.WechatMiniProperties; +import com.xiaowang.jayucloud.salon.core.modules.file.service.ObjectStorageProvider; +import com.xiaowang.jayucloud.salon.core.modules.integration.entity.WechatMiniBindingDO; +import com.xiaowang.jayucloud.salon.core.modules.integration.mapper.WechatMiniBindingMapper; +import com.xiaowang.jayucloud.salon.core.modules.integration.service.MessageHubClientService; +import com.xiaowang.jayucloud.salon.core.modules.integration.service.MessageHubPushConfigService; +import com.xiaowang.jayucloud.salon.core.modules.integration.service.WechatMiniClientService; +import com.xiaowang.jayucloud.salon.core.modules.integration.service.WechatSubscribeMessageService; +import com.xiaowang.jayucloud.salon.core.modules.privacy.moderation.ModerationOutcome; +import com.xiaowang.jayucloud.salon.core.modules.privacy.moderation.WechatContentModerationProvider; +import com.xiaowang.jayucloud.salon.core.modules.system.dto.IntegrationProbeRequestDTO; +import com.xiaowang.jayucloud.salon.core.modules.system.entity.IntegrationProbeResultDO; +import com.xiaowang.jayucloud.salon.core.modules.system.mapper.IntegrationProbeResultMapper; +import com.xiaowang.jayucloud.salon.core.modules.system.service.IntegrationProbeService; +import com.xiaowang.jayucloud.salon.core.modules.system.service.SecureIntegrationConfigService; +import com.xiaowang.jayucloud.salon.core.modules.system.vo.IntegrationProbeCheckVO; +import com.xiaowang.jayucloud.salon.core.modules.system.vo.IntegrationProbeResultVO; +import com.xiaowang.jayucloud.salon.core.modules.system.vo.SecureIntegrationConfigVO; +import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; +import org.springframework.web.client.RestTemplate; +import org.springframework.scheduling.annotation.Scheduled; + +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.UUID; + +@Slf4j +@Service +@RequiredArgsConstructor +public class IntegrationProbeServiceImpl implements IntegrationProbeService { + private static final String[] SERVICES = {"CONTENT_MODERATION", "MAP", "OBJECT_STORAGE", "SMS", "SUBSCRIBE_MESSAGE"}; + private static final String TEXT = "CONTENT_MODERATION"; + private static final String MAP = "MAP"; + private static final String STORAGE = "OBJECT_STORAGE"; + private static final String SMS = "SMS"; + private static final String SUBSCRIBE = "SUBSCRIBE_MESSAGE"; + + private final IntegrationProbeResultMapper resultMapper; + private final ObjectMapper objectMapper; + private final SecureIntegrationConfigService secureIntegrationConfigService; + private final WechatMiniProperties wechatMiniProperties; + private final WechatMiniClientService wechatMiniClientService; + private final WechatMiniBindingMapper bindingMapper; + private final WechatContentModerationProvider wechatContentModerationProvider; + private final List storageProviders; + private final MessageHubPushConfigService messageHubPushConfigService; + private final MessageHubClientService messageHubClientService; + private final RestTemplate restTemplate; + + @Override + public IntegrationProbeResultVO probe(UserDO currentUser, IntegrationProbeRequestDTO request) { + requirePlatformAdmin(currentUser); + String service = normalize(request.getService()); + String operation = normalize(request.getOperation()); + String mode = normalize(request.getMode()); + if (!Arrays.asList(SERVICES).contains(service)) throw new IllegalArgumentException("不支持的测试服务"); + if (!"DIAGNOSTIC".equals(mode) && !"REAL".equals(mode)) throw new IllegalArgumentException("不支持的测试模式"); + validateOperation(service, operation, mode); + if ("REAL".equals(mode) && (SMS.equals(service) || SUBSCRIBE.equals(service)) && !Boolean.TRUE.equals(request.getConfirmed())) { + throw new IllegalArgumentException("真实发送测试必须先确认可能产生的外部副作用"); + } + IntegrationProbeResultVO result; + try { + result = switch (service) { + case TEXT -> probeModeration(currentUser, operation, mode); + case MAP -> probeMap(currentUser, operation); + case STORAGE -> probeStorage(operation); + case SMS -> probeSms(currentUser, operation, mode, request.getTargetPhone()); + case SUBSCRIBE -> probeSubscribe(operation, mode); + default -> failure(service, operation, mode, "不支持的测试服务", "UNSUPPORTED"); + }; + } catch (RuntimeException exception) { + log.warn("系统接入探测失败,service={}, operation={}, mode={}, type={}", service, operation, mode, exception.getClass().getSimpleName()); + result = failure(service, operation, mode, safeMessage(exception), "PROBE_FAILURE"); + } + save(result); + return result; + } + + @Override + public List listLatest(UserDO currentUser) { + requirePlatformAdmin(currentUser); + return resultMapper.selectList(new LambdaQueryWrapper() + .orderByAsc(IntegrationProbeResultDO::getServiceCode) + .orderByAsc(IntegrationProbeResultDO::getOperationCode)) + .stream().map(this::toVO).toList(); + } + + @Override + public boolean handleImageCallback(String taskId, String suggest, String probeId) { + IntegrationProbeResultDO row = null; + if (StringUtils.hasText(taskId)) { + row = resultMapper.selectOne(new LambdaQueryWrapper() + .eq(IntegrationProbeResultDO::getRemoteTaskId, taskId).last("LIMIT 1")); + } + if (row == null && StringUtils.hasText(probeId)) { + row = resultMapper.selectOne(new LambdaQueryWrapper() + .eq(IntegrationProbeResultDO::getCorrelationKey, probeId).last("LIMIT 1")); + } + if (row == null) return false; + row.setStatus("pass".equalsIgnoreCase(suggest) ? "PASS" : "review".equalsIgnoreCase(suggest) ? "WARN" : "FAIL"); + row.setSummary("微信图片审核回调:" + (StringUtils.hasText(suggest) ? suggest : "review")); + row.setCheckedAt(LocalDateTime.now()); + try { row.setChecksJson(objectMapper.writeValueAsString(List.of(new IntegrationProbeCheckVO("微信图片审核回调", row.getStatus(), row.getSummary())))); } + catch (Exception ignored) { } + deleteTemporaryObject(row); + resultMapper.updateById(row); + return true; + } + + @Scheduled(fixedDelay = 300000) + public void expirePendingImageProbes() { + List expired = resultMapper.selectList(new LambdaQueryWrapper() + .eq(IntegrationProbeResultDO::getServiceCode, TEXT) + .eq(IntegrationProbeResultDO::getOperationCode, "IMAGE_CALLBACK") + .eq(IntegrationProbeResultDO::getStatus, "PENDING") + .lt(IntegrationProbeResultDO::getExpiresAt, LocalDateTime.now())); + for (IntegrationProbeResultDO row : expired) { + row.setStatus("FAIL"); + row.setSummary("图片审核回调超时,请检查微信回调地址和公网可达性"); + row.setErrorCode("CALLBACK_TIMEOUT"); + row.setCheckedAt(LocalDateTime.now()); + deleteTemporaryObject(row); + resultMapper.updateById(row); + } + } + + private IntegrationProbeResultVO probeModeration(UserDO currentUser, String operation, String mode) { + SecureIntegrationConfigVO config = secureIntegrationConfigService.getAdminConfig(currentUser); + List checks = new ArrayList<>(); + checks.add(check("加密主密钥", Boolean.TRUE.equals(config.getEncryptionKeyConfigured()), "已配置", "未配置,安全接入密钥无法读取")); + checks.add(check("审核 Provider", "WECHAT".equals(config.getModerationProvider()) || "MOCK".equals(config.getModerationProvider()), config.getModerationProvider(), "未启用")); + checks.add(check("小程序凭据", Boolean.TRUE.equals(config.getWechatMiniAppConfigured()), "AppID 与 AppSecret 已配置", "AppID 或 AppSecret 未配置")); + if ("WECHAT".equals(config.getModerationProvider())) { + checks.add(check("回调配置", Boolean.TRUE.equals(config.getModerationCallbackReady()), "公网 HTTPS 回调资料完整", "回调 URL、Token、AESKey 或加密主密钥不完整")); + } + if (!"WECHAT".equals(config.getModerationProvider())) checks.add(new IntegrationProbeCheckVO("加密主密钥", "WARN", "当前 Provider 不是真实微信审核,无需校验加密回调密钥")); + if ("CONFIG".equals(operation)) return result(TEXT, operation, mode, config.getModerationProvider(), statusForChecks(checks), "内容审核配置诊断完成", null, checks); + if ("MOCK".equals(config.getModerationProvider())) { + checks.add(new IntegrationProbeCheckVO("真实接口", "WARN", "当前使用本地模拟审核,不会调用微信接口")); + return result(TEXT, operation, mode, "MOCK", "WARN", "当前为本地模拟流程", null, checks); + } + if (!"WECHAT".equals(config.getModerationProvider())) return result(TEXT, operation, mode, config.getModerationProvider(), "FAIL", "微信内容审核未启用", "PROVIDER_DISABLED", checks); + if (!Boolean.TRUE.equals(config.getModerationReady())) return result(TEXT, operation, mode, "WECHAT", "FAIL", "微信审核配置未就绪,未发起接口请求", "MODERATION_NOT_READY", checks); + String openId = findProbeOpenId(); + if (!StringUtils.hasText(openId)) { + checks.add(new IntegrationProbeCheckVO("测试账号", "WARN", "当前环境没有可用微信绑定,请先使用体验版登录")); + return result(TEXT, operation, mode, "WECHAT", "WARN", "缺少可用于探测的微信绑定账号", "OPENID_REQUIRED", checks); + } + if ("IMAGE_CALLBACK".equals(operation)) return probeImageCallback(mode, openId, checks); + ModerationOutcome outcome = wechatContentModerationProvider.reviewText("INTEGRATION_PROBE", "Salon 接入测试", openId); + String status = outcome.status() == ModerationOutcome.Status.APPROVED ? "PASS" : outcome.status() == ModerationOutcome.Status.PENDING ? "WARN" : "FAIL"; + checks.add(new IntegrationProbeCheckVO("微信文本接口", status, outcome.reason())); + return result(TEXT, "TEXT", mode, "WECHAT", status, status.equals("PASS") ? "微信文本审核接口调用成功" : outcome.reason(), outcome.code(), checks); + } + + private IntegrationProbeResultVO probeImageCallback(String mode, String openId, List checks) { + String objectName = "integration-probe/" + UUID.randomUUID() + ".png"; + String probeId = UUID.randomUUID().toString(); + ObjectStorageProvider uploaded = null; + boolean awaitingCallback = false; + try { + byte[] image = createProbePng(); + for (ObjectStorageProvider provider : storageProviders) { + if (provider.isEnabled()) { + provider.uploadStream(new java.io.ByteArrayInputStream(image), image.length, "image/png", objectName); + uploaded = provider; + break; + } + } + if (uploaded == null) return result(TEXT, "IMAGE_CALLBACK", mode, "WECHAT", "FAIL", "没有可用对象存储,无法生成图片审核地址", "STORAGE_UNAVAILABLE", checks); + String url = uploaded.getPresignedUrl(objectName, 5); + if (!StringUtils.hasText(url) || !url.startsWith("https://")) return result(TEXT, "IMAGE_CALLBACK", mode, "WECHAT", "FAIL", "对象存储未提供公网 HTTPS 签名地址", "IMAGE_URL_INVALID", checks); + savePendingImageProbe(mode, probeId, uploaded.providerCode(), objectName); + ModerationOutcome outcome = wechatContentModerationProvider.submitTestImage(url, openId, probeId); + String status = outcome.status() == ModerationOutcome.Status.PENDING ? "PENDING" : outcome.status() == ModerationOutcome.Status.APPROVED ? "PASS" : "FAIL"; + checks.add(new IntegrationProbeCheckVO("微信图片异步接口", status, outcome.reason())); + awaitingCallback = "PENDING".equals(status); + updatePendingImageTask(probeId, outcome.remoteTaskId()); + return result(TEXT, "IMAGE_CALLBACK", mode, "WECHAT", status, outcome.reason(), outcome.code(), checks); + } catch (Exception exception) { + checks.add(new IntegrationProbeCheckVO("微信图片异步接口", "FAIL", "临时图片上传或审核请求失败")); + return result(TEXT, "IMAGE_CALLBACK", mode, "WECHAT", "FAIL", "微信图片审核探测失败", "IMAGE_PROBE_FAILED", checks); + } finally { + if (uploaded != null && !awaitingCallback) try { uploaded.deleteFile(objectName); } catch (Exception ignored) { log.warn("清理接入测试临时图片失败"); } + } + } + + private byte[] createProbePng() throws java.io.IOException { + java.awt.image.BufferedImage image = new java.awt.image.BufferedImage(64, 64, java.awt.image.BufferedImage.TYPE_INT_RGB); + java.awt.Graphics2D graphics = image.createGraphics(); + try { graphics.setColor(java.awt.Color.WHITE); graphics.fillRect(0, 0, 64, 64); } + finally { graphics.dispose(); } + java.io.ByteArrayOutputStream output = new java.io.ByteArrayOutputStream(); + javax.imageio.ImageIO.write(image, "png", output); + return output.toByteArray(); + } + + private void savePendingImageProbe(String mode, String probeId, String provider, String objectName) throws Exception { + IntegrationProbeResultDO row = findResult(TEXT, "IMAGE_CALLBACK"); + if (row == null) { row = new IntegrationProbeResultDO(); row.setServiceCode(TEXT); row.setOperationCode("IMAGE_CALLBACK"); } + row.setMode(mode); row.setProvider("WECHAT"); row.setStatus("PENDING"); row.setSummary("已提交微信图片审核,等待回调"); row.setErrorCode(null); + row.setChecksJson(objectMapper.writeValueAsString(List.of(new IntegrationProbeCheckVO("微信图片异步接口", "PENDING", "等待微信回调")))); + row.setRemoteTaskId(null); row.setCorrelationKey(probeId); row.setTemporaryObjectProvider(provider); row.setTemporaryObjectName(objectName); + row.setExpiresAt(LocalDateTime.now().plusMinutes(5)); row.setCheckedAt(LocalDateTime.now()); + if (row.getId() == null) resultMapper.insert(row); else resultMapper.updateById(row); + } + + private void updatePendingImageTask(String probeId, String taskId) { + if (!StringUtils.hasText(taskId)) return; + IntegrationProbeResultDO row = resultMapper.selectOne(new LambdaQueryWrapper() + .eq(IntegrationProbeResultDO::getCorrelationKey, probeId).last("LIMIT 1")); + if (row != null) { row.setRemoteTaskId(clip(taskId, 128)); resultMapper.updateById(row); } + } + + private IntegrationProbeResultDO findResult(String service, String operation) { + return resultMapper.selectOne(new LambdaQueryWrapper() + .eq(IntegrationProbeResultDO::getServiceCode, service) + .eq(IntegrationProbeResultDO::getOperationCode, operation).last("LIMIT 1")); + } + + private void deleteTemporaryObject(IntegrationProbeResultDO row) { + if (!StringUtils.hasText(row.getTemporaryObjectProvider()) || !StringUtils.hasText(row.getTemporaryObjectName())) return; + storageProviders.stream().filter(provider -> provider.providerCode().equals(row.getTemporaryObjectProvider())).findFirst().ifPresent(provider -> { + try { provider.deleteFile(row.getTemporaryObjectName()); } + catch (Exception ignored) { log.warn("清理接入测试临时图片失败,provider={}", provider.providerCode()); } + }); + row.setTemporaryObjectProvider(null); + row.setTemporaryObjectName(null); + } + + private IntegrationProbeResultVO probeMap(UserDO currentUser, String operation) { + SecureIntegrationConfigVO config = secureIntegrationConfigService.getAdminConfig(currentUser); + List checks = new ArrayList<>(); + boolean selectedKey = "AMAP".equals(config.getMapProvider()) ? Boolean.TRUE.equals(config.getAmapWebKeyConfigured()) : Boolean.TRUE.equals(config.getTencentWebKeyConfigured()); + checks.add(check("当前 Web Key", selectedKey, "已配置", "未配置")); + checks.add(new IntegrationProbeCheckVO("高德小程序 Key", Boolean.TRUE.equals(config.getAmapMiniKeyConfigured()) ? "PASS" : "WARN", Boolean.TRUE.equals(config.getAmapMiniKeyConfigured()) ? "已配置" : "未配置,仅影响小程序选点")); + if (!selectedKey) return result(MAP, operation, "DIAGNOSTIC", config.getMapProvider(), "FAIL", "当前地图渠道缺少 Web Key", "MAP_KEY_MISSING", checks); + if (!Boolean.TRUE.equals(config.getMapEnabled())) return result(MAP, operation, "DIAGNOSTIC", config.getMapProvider(), "WARN", "地图服务当前已停用,保存并启用后才能测试真实请求", "MAP_DISABLED", checks); + if ("CONFIG".equals(operation)) return result(MAP, operation, "DIAGNOSTIC", config.getMapProvider(), "PASS", "地图 Key 配置诊断完成", null, checks); + Map runtime = secureIntegrationConfigService.getMapRuntimeConfig(currentUser); + String key = runtime.get("key"); + String url = "AMAP".equals(config.getMapProvider()) + ? "https://restapi.amap.com/v3/geocode/geo?address=" + java.net.URLEncoder.encode("天安门", StandardCharsets.UTF_8) + "&key=" + key + : "https://apis.map.qq.com/ws/geocoder/v1/?address=" + java.net.URLEncoder.encode("天安门", StandardCharsets.UTF_8) + "&key=" + key; + try { + JsonNode body = objectMapper.readTree(restTemplate.getForObject(url, String.class)); + boolean success = "AMAP".equals(config.getMapProvider()) ? body.path("status").asInt(0) == 1 : body.path("status").asInt(-1) == 0; + checks.add(new IntegrationProbeCheckVO("地图 API 请求", success ? "PASS" : "FAIL", success ? "固定地址解析成功" : "地图服务返回失败")); + return result(MAP, operation, "DIAGNOSTIC", config.getMapProvider(), success ? "PASS" : "FAIL", success ? "地图服务调用成功" : "地图服务调用失败", null, checks); + } catch (Exception exception) { + checks.add(new IntegrationProbeCheckVO("地图 API 请求", "FAIL", "地图接口不可达或返回格式异常")); + return result(MAP, operation, "DIAGNOSTIC", config.getMapProvider(), "FAIL", "地图服务调用失败", "MAP_REQUEST_FAILED", checks); + } + } + + private IntegrationProbeResultVO probeStorage(String operation) { + List checks = new ArrayList<>(); + if ("CONFIG".equals(operation)) { + for (ObjectStorageProvider provider : storageProviders) { + checks.add(new IntegrationProbeCheckVO(provider.providerCode(), provider.isEnabled() ? "PASS" : "WARN", provider.isEnabled() ? "已启用并具备基本配置" : "未启用或配置不完整")); + } + String status = checks.stream().anyMatch(item -> "WARN".equals(item.getStatus())) ? "WARN" : "PASS"; + return result(STORAGE, operation, "DIAGNOSTIC", "MULTI", status, status.equals("PASS") ? "对象存储配置完整" : "存在未启用的对象存储渠道", null, checks); + } + byte[] bytes = "salon-integration-probe".getBytes(StandardCharsets.UTF_8); + String objectName = "integration-probe/" + UUID.randomUUID() + ".txt"; + int enabled = 0; + try { + for (ObjectStorageProvider provider : storageProviders) { + if (!provider.isEnabled()) { + checks.add(new IntegrationProbeCheckVO(provider.providerCode(), "WARN", "未启用或配置不完整")); + continue; + } + enabled++; + try { + provider.uploadStream(new java.io.ByteArrayInputStream(bytes), bytes.length, "text/plain", objectName); + try (InputStream input = provider.downloadFile(objectName)) { + boolean same = java.util.Arrays.equals(bytes, input.readAllBytes()); + String signed = provider.getPresignedUrl(objectName, 5); + byte[] signedBytes = StringUtils.hasText(signed) ? restTemplate.getForObject(signed, byte[].class) : null; + boolean signedRead = java.util.Arrays.equals(bytes, signedBytes); + checks.add(new IntegrationProbeCheckVO(provider.providerCode(), same && signedRead ? "PASS" : "FAIL", same && signedRead ? "上传、读取和签名访问成功" : "对象内容或签名读取不一致")); + } + } catch (Exception exception) { + checks.add(new IntegrationProbeCheckVO(provider.providerCode(), "FAIL", "上传或读取失败")); + } finally { + try { provider.deleteFile(objectName); } catch (Exception ignored) { log.warn("清理对象存储测试文件失败,provider={}", provider.providerCode()); } + } + } + String status = enabled == 0 ? "FAIL" : checks.stream().anyMatch(item -> "FAIL".equals(item.getStatus())) ? "FAIL" : checks.stream().anyMatch(item -> "WARN".equals(item.getStatus())) ? "WARN" : "PASS"; + return result(STORAGE, operation, "DIAGNOSTIC", "MULTI", status, status.equals("PASS") ? "对象存储三副本往返测试成功" : "对象存储存在未就绪渠道", null, checks); + } catch (RuntimeException exception) { + return result(STORAGE, operation, "DIAGNOSTIC", "MULTI", "FAIL", "对象存储测试失败", "STORAGE_PROBE_FAILED", checks); + } + } + + private IntegrationProbeResultVO probeSms(UserDO currentUser, String operation, String mode, String phone) { + List checks = new ArrayList<>(); + List configs = messageHubPushConfigService.listConfigs(currentUser); + List expectedScenes = List.of("USER_REGISTER_SMS_CODE", "USER_LOGIN_SMS_CODE", "USER_RESET_PASSWORD_SMS_CODE", "USER_BIND_PHONE_SMS_CODE", "USER_CHANGE_PHONE_SMS_CODE", "USER_CHANGE_PASSWORD_SMS_CODE"); + long enabled = expectedScenes.stream().filter(scene -> configs.stream().anyMatch(item -> scene.equals(item.getSceneCode()) && Integer.valueOf(1).equals(item.getEnabled()))).count(); + checks.add(new IntegrationProbeCheckVO("短信业务场景", enabled == expectedScenes.size() ? "PASS" : "FAIL", enabled + "/" + expectedScenes.size() + " 个场景已启用")); + boolean complete = enabled == expectedScenes.size(); + if ("CONFIG".equals(operation) || !"REAL".equals(mode)) return result(SMS, operation, mode, "MESSAGEHUB", complete ? "PASS" : "FAIL", complete ? "短信场景配置完整;未发送真实短信" : "部分短信场景未启用", null, checks); + if (!complete) return result(SMS, operation, mode, "MESSAGEHUB", "FAIL", "短信场景配置不完整,未发送测试短信", "SMS_CONFIG_INCOMPLETE", checks); + if (!StringUtils.hasText(phone) || !phone.matches("^1[3-9]\\d{9}$")) throw new IllegalArgumentException("真实短信测试需要填写有效手机号"); + int testCode = java.util.concurrent.ThreadLocalRandom.current().nextInt(100000, 1000000); + messageHubClientService.sendSmsVerificationCode("USER_LOGIN_SMS_CODE", phone, String.valueOf(testCode)); + checks.add(new IntegrationProbeCheckVO("真实短信投递", "PASS", "测试短信已提交,手机号 " + maskPhone(phone))); + return result(SMS, "SEND", mode, "MESSAGEHUB", "PASS", "测试短信已提交", null, checks); + } + + private IntegrationProbeResultVO probeSubscribe(String operation, String mode) { + List checks = new ArrayList<>(); + String provider = StringUtils.hasText(wechatMiniProperties.getSubscribeMessageProvider()) ? wechatMiniProperties.getSubscribeMessageProvider().trim().toLowerCase(Locale.ROOT) : "mock"; + boolean enabled = Boolean.TRUE.equals(wechatMiniProperties.getSubscribeMessageEnabled()); + checks.add(new IntegrationProbeCheckVO("发送渠道", "wechat".equals(provider) && enabled ? "PASS" : "WARN", "wechat".equals(provider) && enabled ? "微信真实发送已启用" : "当前为 Mock 或已停用")); + boolean credentials = StringUtils.hasText(wechatMiniProperties.getAppId()) && StringUtils.hasText(wechatMiniProperties.getAppSecret()); + checks.add(check("小程序凭据", credentials, "已配置", "AppID 或 AppSecret 未配置")); + if (!credentials) return result(SUBSCRIBE, operation, mode, "WECHAT", "FAIL", "订阅消息凭据不完整", "WECHAT_CREDENTIALS_MISSING", checks); + if (!"wechat".equals(provider) || !enabled) return result(SUBSCRIBE, operation, mode, provider.toUpperCase(Locale.ROOT), "WARN", "当前订阅消息未启用微信真实发送", "PROVIDER_NOT_LIVE", checks); + try { + wechatMiniClientService.getAccessTokenForContentModeration(); + checks.add(new IntegrationProbeCheckVO("access_token", "PASS", "获取成功")); + if ("SEND".equals(operation) && "REAL".equals(mode)) { + String openId = findProbeOpenId(); + checks.add(check("测试账号", StringUtils.hasText(openId), "已找到当前环境绑定账号", "请先使用体验版登录")); + if (!StringUtils.hasText(openId)) return result(SUBSCRIBE, operation, mode, "WECHAT", "WARN", "缺少可用于探测的微信绑定账号", "OPENID_REQUIRED", checks); + WechatMiniClientService.SubscribeMessageResult send = wechatMiniClientService.sendSubscribeMessage(openId, WechatSubscribeMessageService.TEMPLATE_APPOINTMENT, + Map.of("thing1", "接入测试", "time2", "12:00", "thing3", "请忽略此测试消息", "name5", "测试技师", "name6", "测试客户"), wechatMiniProperties.getSubscribeMessagePage(), wechatMiniProperties.getSubscribeMessageMiniprogramState()); + String status = send.success() ? "PASS" : "FAIL"; + String sendDetail = send.success() ? "测试消息已提交" : subscribeSendError(send.errCode()); + checks.add(new IntegrationProbeCheckVO("订阅消息发送", status, sendDetail)); + return result(SUBSCRIBE, "SEND", mode, "WECHAT", status, sendDetail, send.success() ? null : String.valueOf(send.errCode()), checks); + } + return checkSubscribeTemplates(operation, mode, checks); + } catch (Exception exception) { + checks.add(new IntegrationProbeCheckVO("access_token", "FAIL", "微信接口不可用")); + return result(SUBSCRIBE, operation, mode, "WECHAT", "FAIL", "订阅消息接口探测失败", "WECHAT_REQUEST_FAILED", checks); + } + } + + private IntegrationProbeResultVO checkSubscribeTemplates(String operation, String mode, List checks) throws Exception { + String accessToken = wechatMiniClientService.getAccessTokenForContentModeration(); + String url = "https://api.weixin.qq.com/cgi-bin/wxopen/template/list?access_token=" + java.net.URLEncoder.encode(accessToken, StandardCharsets.UTF_8); + JsonNode response = objectMapper.readTree(restTemplate.getForObject(url, String.class)); + int errorCode = response.path("errcode").asInt(0); + if (errorCode != 0) { + checks.add(new IntegrationProbeCheckVO("微信模板列表", "WARN", "微信未允许读取模板清单,请使用真实发送确认模板状态")); + return result(SUBSCRIBE, operation, mode, "WECHAT", "WARN", "凭据可用,模板状态需真实发送验证", String.valueOf(errorCode), checks); + } + java.util.Set configured = new java.util.HashSet<>(); + for (JsonNode item : response.path("data")) { + String templateId = item.path("priTmplId").asText(); + if (StringUtils.hasText(templateId)) configured.add(templateId); + } + List required = List.of(WechatSubscribeMessageService.TEMPLATE_APPOINTMENT, WechatSubscribeMessageService.TEMPLATE_CANCELLED, WechatSubscribeMessageService.TEMPLATE_SERVICE_START); + long matched = required.stream().filter(configured::contains).count(); + checks.add(new IntegrationProbeCheckVO("固定订阅模板", matched == required.size() ? "PASS" : "FAIL", matched + "/" + required.size() + " 个模板已添加到当前小程序")); + return result(SUBSCRIBE, operation, mode, "WECHAT", matched == required.size() ? "PASS" : "FAIL", matched == required.size() ? "订阅消息凭据与固定模板可用" : "微信后台缺少订阅模板", matched == required.size() ? null : "TEMPLATE_MISSING", checks); + } + + private IntegrationProbeResultVO result(String service, String operation, String mode, String provider, String status, String summary, String errorCode, List checks) { + IntegrationProbeResultVO result = new IntegrationProbeResultVO(); + result.setService(service); result.setOperation(operation); result.setMode(mode); result.setProvider(provider); result.setStatus(status); result.setSummary(summary); result.setErrorCode(errorCode); result.setCheckedAt(LocalDateTime.now()); result.setChecks(checks); + return result; + } + + private IntegrationProbeResultVO failure(String service, String operation, String mode, String summary, String errorCode) { + return result(service, operation, mode, "UNKNOWN", "FAIL", summary, errorCode, new ArrayList<>()); + } + + private void validateOperation(String service, String operation, String mode) { + boolean valid = switch (service) { + case TEXT -> List.of("CONFIG", "TEXT", "IMAGE_CALLBACK").contains(operation); + case MAP -> List.of("CONFIG", "REQUEST").contains(operation); + case STORAGE -> List.of("CONFIG", "ROUND_TRIP").contains(operation); + case SMS -> ("CONFIG".equals(operation) && "DIAGNOSTIC".equals(mode)) || ("SEND".equals(operation) && "REAL".equals(mode)); + case SUBSCRIBE -> ("CONFIG".equals(operation) && "DIAGNOSTIC".equals(mode)) || ("SEND".equals(operation) && "REAL".equals(mode)); + default -> false; + }; + if (!valid) throw new IllegalArgumentException("服务测试操作与测试模式不匹配"); + } + + private IntegrationProbeCheckVO check(String name, boolean ok, String pass, String fail) { return new IntegrationProbeCheckVO(name, ok ? "PASS" : "FAIL", ok ? pass : fail); } + + private String statusForChecks(List checks) { return checks.stream().anyMatch(item -> "FAIL".equals(item.getStatus())) ? "FAIL" : checks.stream().anyMatch(item -> "WARN".equals(item.getStatus())) ? "WARN" : "PASS"; } + + private String findProbeOpenId() { + if (!StringUtils.hasText(wechatMiniProperties.getAppId())) return null; + WechatMiniBindingDO binding = bindingMapper.selectOne(new LambdaQueryWrapper() + .eq(WechatMiniBindingDO::getAppId, wechatMiniProperties.getAppId()) + .eq(WechatMiniBindingDO::getStatus, 1) + .isNotNull(WechatMiniBindingDO::getOpenId) + .last("LIMIT 1")); + return binding == null ? null : binding.getOpenId(); + } + + private void save(IntegrationProbeResultVO result) { + try { + IntegrationProbeResultDO row = findResult(result.getService(), result.getOperation()); + if (row == null) { row = new IntegrationProbeResultDO(); row.setServiceCode(result.getService()); row.setOperationCode(result.getOperation()); } + if ("PENDING".equals(result.getStatus()) && row.getId() != null && !"PENDING".equals(row.getStatus())) return; + row.setMode(result.getMode()); row.setProvider(result.getProvider()); row.setStatus(result.getStatus()); row.setSummary(clip(result.getSummary(), 500)); row.setErrorCode(clip(result.getErrorCode(), 64)); row.setCheckedAt(result.getCheckedAt()); + if (!"PENDING".equals(result.getStatus())) deleteTemporaryObject(row); + row.setChecksJson(objectMapper.writeValueAsString(result.getChecks())); + if (row.getId() == null) resultMapper.insert(row); else resultMapper.updateById(row); + } catch (Exception exception) { log.warn("保存接入探测结果失败,service={}, operation={}", result.getService(), result.getOperation()); } + } + + private IntegrationProbeResultVO toVO(IntegrationProbeResultDO row) { + IntegrationProbeResultVO result = result(row.getServiceCode(), row.getOperationCode(), row.getMode(), row.getProvider(), row.getStatus(), row.getSummary(), row.getErrorCode(), new ArrayList<>()); + result.setCheckedAt(row.getCheckedAt()); + try { result.setChecks(objectMapper.readValue(row.getChecksJson(), new TypeReference>() {})); } catch (Exception ignored) { } + return result; + } + + private String normalize(String value) { return StringUtils.hasText(value) ? value.trim().toUpperCase(Locale.ROOT) : ""; } + private String safeMessage(RuntimeException exception) { return "探测请求未完成,请查看脱敏检查项"; } + private String subscribeSendError(int code) { + if (code == 43101) return "当前绑定账号尚未授权此订阅模板"; + if (code == 40037 || code == 47003) return "订阅模板无效或模板字段不匹配"; + if (code == 40001 || code == 40014) return "微信 access_token 无效或已过期"; + return "微信未接受测试消息,请核对模板状态和订阅授权"; + } + private String clip(String value, int max) { if (!StringUtils.hasText(value)) return null; String text = value.trim(); return text.length() <= max ? text : text.substring(0, max); } + private String maskPhone(String phone) { return phone.substring(0, 3) + "****" + phone.substring(phone.length() - 4); } + private void requirePlatformAdmin(UserDO user) { if (user == null || !Integer.valueOf(4).equals(user.getType())) throw new RuntimeException("仅平台管理员可以测试系统接入"); } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/vo/IntegrationProbeCheckVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/vo/IntegrationProbeCheckVO.java new file mode 100644 index 00000000..ae2cb197 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/vo/IntegrationProbeCheckVO.java @@ -0,0 +1,14 @@ +package com.xiaowang.jayucloud.salon.core.modules.system.vo; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@NoArgsConstructor +@AllArgsConstructor +public class IntegrationProbeCheckVO { + private String name; + private String status; + private String detail; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/vo/IntegrationProbeResultVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/vo/IntegrationProbeResultVO.java new file mode 100644 index 00000000..b063ce4e --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/vo/IntegrationProbeResultVO.java @@ -0,0 +1,20 @@ +package com.xiaowang.jayucloud.salon.core.modules.system.vo; + +import lombok.Data; + +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.List; + +@Data +public class IntegrationProbeResultVO { + private String service; + private String operation; + private String mode; + private String provider; + private String status; + private String summary; + private String errorCode; + private LocalDateTime checkedAt; + private List checks = new ArrayList<>(); +} diff --git a/JC-Salon-Core/src/main/resources/db/migration/V15__系统接入诊断结果_20261104.sql b/JC-Salon-Core/src/main/resources/db/migration/V15__系统接入诊断结果_20261104.sql new file mode 100644 index 00000000..685f456c --- /dev/null +++ b/JC-Salon-Core/src/main/resources/db/migration/V15__系统接入诊断结果_20261104.sql @@ -0,0 +1,22 @@ +CREATE TABLE IF NOT EXISTS t_integration_probe_result ( + id BIGINT NOT NULL, + service_code VARCHAR(64) NOT NULL, + operation_code VARCHAR(64) NOT NULL, + mode VARCHAR(32) NOT NULL, + provider VARCHAR(64) NULL, + status VARCHAR(16) NOT NULL, + summary VARCHAR(500) NULL, + error_code VARCHAR(64) NULL, + checks_json TEXT NULL, + remote_task_id VARCHAR(128) NULL, + correlation_key VARCHAR(128) NULL, + temporary_object_provider VARCHAR(64) NULL, + temporary_object_name VARCHAR(512) NULL, + expires_at DATETIME NULL, + checked_at DATETIME NOT NULL, + create_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + update_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + PRIMARY KEY (id), + UNIQUE KEY uk_integration_probe_service_operation (service_code, operation_code), + KEY idx_integration_probe_checked_at (checked_at) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='系统接入最近一次诊断结果'; diff --git a/JC-Salon-Frontend/src/api/admin.ts b/JC-Salon-Frontend/src/api/admin.ts index 66a48442..76b23ebe 100644 --- a/JC-Salon-Frontend/src/api/admin.ts +++ b/JC-Salon-Frontend/src/api/admin.ts @@ -1596,6 +1596,33 @@ export interface SecureIntegrationConfigVO { mockProviderAllowed: boolean encryptionKeyConfigured: boolean updatedAt?: string + probeResults?: IntegrationProbeResultVO[] +} + +export interface IntegrationProbeCheckVO { + name: string + status: 'PASS' | 'WARN' | 'FAIL' | 'PENDING' + detail: string +} + +export interface IntegrationProbeResultVO { + service: 'CONTENT_MODERATION' | 'MAP' | 'OBJECT_STORAGE' | 'SMS' | 'SUBSCRIBE_MESSAGE' | string + operation: string + mode: 'DIAGNOSTIC' | 'REAL' | string + provider?: string + status: 'PASS' | 'WARN' | 'FAIL' | 'PENDING' | string + summary: string + errorCode?: string + checkedAt?: string + checks?: IntegrationProbeCheckVO[] +} + +export interface IntegrationProbeRequest { + service: string + operation: string + mode?: 'DIAGNOSTIC' | 'REAL' + targetPhone?: string + confirmed?: boolean } export interface SecureIntegrationConfigUpdate { @@ -1633,6 +1660,8 @@ export const adminSystemParameterConfigApi = { export const adminSecureIntegrationConfigApi = { getConfig: () => adminApi.get('/system-settings/secure-integration') as unknown as Promise, + listProbeResults: () => adminApi.get('/system-settings/secure-integration/probe-results') as unknown as Promise, + probe: (data: IntegrationProbeRequest) => adminApi.post('/system-settings/secure-integration/probe', data) as unknown as Promise, getMapRuntimeConfig: () => adminApi.get<{ provider: 'TENCENT' | 'AMAP'; enabled: string; key: string }>('/system-settings/secure-integration/map-runtime') as unknown as Promise<{ provider: 'TENCENT' | 'AMAP'; enabled: string; key: string }>, saveMapConfig: (data: SecureIntegrationConfigUpdate) => adminApi.post('/system-settings/secure-integration/map', data) as unknown as Promise, saveModerationConfig: (data: SecureIntegrationConfigUpdate) => adminApi.post('/system-settings/secure-integration/content-moderation', data) as unknown as Promise diff --git a/JC-Salon-Frontend/src/views/admin/SystemSettingsView.vue b/JC-Salon-Frontend/src/views/admin/SystemSettingsView.vue index cb4c52c5..3658c4df 100644 --- a/JC-Salon-Frontend/src/views/admin/SystemSettingsView.vue +++ b/JC-Salon-Frontend/src/views/admin/SystemSettingsView.vue @@ -36,6 +36,27 @@ +
+
接入诊断TEST
+
+
+
+ {{ card.label }} + {{ card.description }} + 最近:{{ probeFor(card.service)?.summary }} · {{ formatProbeTime(probeFor(card.service)?.checkedAt) }} +
+
+ {{ card.action }} + 图片回调 + 真实发送 +
+ {{ probeStatusLabel(probeFor(card.service)?.status) }} + 未测试 +
+
+

配置保存后再测试。短信和订阅消息默认只诊断,真实发送会产生外部副作用并要求二次确认;对象存储测试文件会自动清理。

+
+
账号默认值USER保存密码设置
@@ -257,6 +278,17 @@
+ + + + +
@@ -265,7 +297,7 @@ import { computed, onMounted, reactive, ref } from 'vue' import { useRoute } from 'vue-router' import { message, Modal } from 'ant-design-vue' import { ApiOutlined, ArrowDownOutlined, ArrowUpOutlined, CopyOutlined, ExportOutlined, SettingOutlined, UserOutlined } from '@ant-design/icons-vue' -import { adminSecureIntegrationConfigApi, adminSystemParameterConfigApi, type SecureIntegrationConfigVO, type SystemParameterConfigVO } from '@/api/admin' +import { adminSecureIntegrationConfigApi, adminSystemParameterConfigApi, type IntegrationProbeResultVO, type SecureIntegrationConfigVO, type SystemParameterConfigVO } from '@/api/admin' import { ADMIN_API_BASE_URL } from '@/config/api' import { loadCachedAdminUserInfo } from '@/utils/admin-session' @@ -275,6 +307,13 @@ type MapKey = 'tencentWeb' | 'amapWeb' | 'amapMini' const route = useRoute() const activeSection = ref(route.query.section === 'account' ? 'account' : 'runtime') const loading = ref(false) +const testingProbe = ref('') +const probeResults = ref([]) +const realProbeOpen = ref(false) +const realProbeLoading = ref(false) +const realProbeService = ref<'SMS' | 'SUBSCRIBE_MESSAGE'>('SMS') +const realProbePhone = ref('') +const realProbeConfirmed = ref(false) const savingDefaultPassword = ref(false) const savingReviewNotice = ref(false) const savingManagerReviewMode = ref(false) @@ -342,6 +381,13 @@ const sections = [ { key: 'services' as const, label: '服务接入', icon: ApiOutlined }, { key: 'account' as const, label: '当前账号', icon: UserOutlined } ] +const probeCards = [ + { service: 'CONTENT_MODERATION', label: '微信内容审核', description: '先诊断配置,再调用无害文本;图片测试会等待微信回调。', operation: 'TEXT', action: '文本探测' }, + { service: 'MAP', label: '地图服务', description: '调用当前渠道固定地址,验证 Web Key 是否真正可用。', operation: 'REQUEST', action: '测试请求' }, + { service: 'OBJECT_STORAGE', label: '对象存储三副本', description: '临时上传、读取、签名访问并自动清理。', operation: 'ROUND_TRIP', action: '往返测试' }, + { service: 'SMS', label: '短信服务', description: '默认只检查六个验证码场景和 MessageHub 配置。', operation: 'CONFIG', action: '配置诊断' }, + { service: 'SUBSCRIBE_MESSAGE', label: '微信订阅消息', description: '默认检查凭据和固定模板,不发送真实消息。', operation: 'CONFIG', action: '配置诊断' } +] const mapKeyRows: Array<{ key: MapKey; label: string; description: string; placeholder: string; url: string }> = [ { key: 'tencentWeb', label: '腾讯 Web Key', description: '用于后台腾讯地图选点。', placeholder: '填写腾讯 Web Key;留空保持原值', url: 'https://lbs.qq.com/dev/console/key/manage' }, { key: 'amapWeb', label: '高德 Web Key', description: '用于后台高德地图选点。', placeholder: '填写高德 Web Key;留空保持原值', url: 'https://console.amap.com/dev/key/app' }, @@ -406,13 +452,14 @@ const confirmSecureKeyChanges = (title: string, changes: string[]) => new Promis const load = async () => { loading.value = true try { - const [userConfigs, smsConfigs, workbenchConfigs, shopConfigs, fileConfigs, secureConfig] = await Promise.all([ + const [userConfigs, smsConfigs, workbenchConfigs, shopConfigs, fileConfigs, secureConfig, latestProbeResults] = await Promise.all([ adminSystemParameterConfigApi.listConfigs('USER'), adminSystemParameterConfigApi.listConfigs('SMS'), adminSystemParameterConfigApi.listConfigs('WORKBENCH'), adminSystemParameterConfigApi.listConfigs('SHOP'), adminSystemParameterConfigApi.listConfigs('FILE'), - adminSecureIntegrationConfigApi.getConfig() + adminSecureIntegrationConfigApi.getConfig(), + adminSecureIntegrationConfigApi.listProbeResults() ]) const defaultPassword = userConfigs.find(item => item.configKey === 'DEFAULT_PASSWORD') if (defaultPassword) { @@ -448,6 +495,7 @@ const load = async () => { } } secureStatus.value = secureConfig + probeResults.value = latestProbeResults || [] mapProvider.value = secureConfig.mapProvider === 'AMAP' ? 'AMAP' : 'TENCENT' mapEnabled.value = Boolean(secureConfig.mapEnabled) moderationProvider.value = secureConfig.moderationProvider || 'DISABLED' @@ -465,6 +513,44 @@ const load = async () => { } } +const probeFor = (service: string) => probeResults.value.filter(item => item.service === service).sort((a, b) => String(b.checkedAt || '').localeCompare(String(a.checkedAt || '')))[0] +const formatProbeTime = (time?: string) => time ? new Date(time).toLocaleString('zh-CN', { hour12: false }) : '暂无时间' +const probeStatusLabel = (status?: string) => ({ PASS: '通过', WARN: '需关注', FAIL: '失败', PENDING: '等待回调' } as Record)[status || ''] || '未知' +const runProbe = async (service: string, operation: string) => { + const key = `${service}:${operation}` + testingProbe.value = key + try { + const result = await adminSecureIntegrationConfigApi.probe({ service, operation, mode: 'DIAGNOSTIC' }) + probeResults.value = [...probeResults.value.filter(item => !(item.service === result.service && item.operation === result.operation)), result] + message[result.status === 'PASS' ? 'success' : result.status === 'WARN' ? 'warning' : 'error'](result.summary) + } catch (error) { message.error(error instanceof Error ? error.message : '接入测试失败') } + finally { testingProbe.value = '' } +} +const openRealProbe = (service: 'SMS' | 'SUBSCRIBE_MESSAGE') => { + realProbeService.value = service + realProbePhone.value = '' + realProbeConfirmed.value = false + realProbeOpen.value = true +} +const submitRealProbe = async () => { + if (realProbeService.value === 'SMS' && !/^1[3-9]\d{9}$/.test(realProbePhone.value.trim())) { message.warning('请输入有效的接收手机号'); return } + if (realProbeService.value === 'SUBSCRIBE_MESSAGE' && !realProbeConfirmed.value) { message.warning('请确认发送真实订阅消息'); return } + realProbeLoading.value = true + try { + const result = await adminSecureIntegrationConfigApi.probe({ + service: realProbeService.value, + operation: 'SEND', + mode: 'REAL', + targetPhone: realProbeService.value === 'SMS' ? realProbePhone.value.trim() : undefined, + confirmed: true + }) + probeResults.value = [...probeResults.value.filter(item => !(item.service === result.service && item.operation === result.operation)), result] + message[result.status === 'PASS' ? 'success' : result.status === 'WARN' ? 'warning' : 'error'](result.summary) + realProbeOpen.value = false + } catch (error) { message.error(error instanceof Error ? error.message : '真实接入测试失败') } + finally { realProbeLoading.value = false } +} + const validateDefaultPassword = () => { const password = defaultPasswordForm.configValue.trim() if (password.length < 8 || password.length > 32) { -- 2.54.0 From d4fc48bc2aefca52cb043412b36d31602b36553e Mon Sep 17 00:00:00 2001 From: xiaowang <2161656029@qq.com> Date: Wed, 4 Nov 2026 12:39:47 +0800 Subject: [PATCH 2/2] =?UTF-8?q?=E5=AE=8C=E5=96=84=E7=B3=BB=E7=BB=9F?= =?UTF-8?q?=E6=8E=A5=E5=85=A5=E8=AF=8A=E6=96=AD=E4=B8=8E=E5=AE=A1=E6=A0=B8?= =?UTF-8?q?=E7=8A=B6=E6=80=81=E5=B1=95=E7=A4=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../WechatContentModerationProvider.java | 11 +- ...dminSecureIntegrationConfigController.java | 12 +- .../impl/IntegrationProbeServiceImpl.java | 204 +++++++++++++++--- .../system/vo/SecureIntegrationConfigVO.java | 3 + ...ntentModerationCallbackControllerTest.java | 5 +- .../impl/IntegrationProbeServiceImplTest.java | 139 ++++++++++++ .../src/utils/moderation-status.test.ts | 35 +++ .../src/utils/moderation-status.ts | 64 ++++++ .../src/views/admin/PrivacyComplianceView.vue | 51 ++++- .../src/views/admin/SystemSettingsView.vue | 133 ++++++++---- .../Salon系统接入诊断与测试说明_20261104.md | 33 +++ docs/scripts/运行与发布配置总说明.md | 1 + 12 files changed, 607 insertions(+), 84 deletions(-) create mode 100644 JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/system/service/impl/IntegrationProbeServiceImplTest.java create mode 100644 JC-Salon-Frontend/src/utils/moderation-status.test.ts create mode 100644 JC-Salon-Frontend/src/utils/moderation-status.ts create mode 100644 docs/scripts/Salon系统接入诊断与测试说明_20261104.md diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/moderation/WechatContentModerationProvider.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/moderation/WechatContentModerationProvider.java index 28509fb4..18cb4466 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/moderation/WechatContentModerationProvider.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/moderation/WechatContentModerationProvider.java @@ -65,9 +65,9 @@ public class WechatContentModerationProvider implements ContentModerationProvide return submitImageWithExtra(contentType, imageUrl, openId, encodeSourceEnvVersion(sourceEnvVersion)); } - public ModerationOutcome submitTestImage(String imageUrl, String openId, String probeId) { + public ModerationOutcome submitTestImage(String imageUrl, String openId, String probeId, String sourceEnvVersion) { Map extra = new LinkedHashMap<>(); - extra.put("envVersion", "trial"); + extra.put("envVersion", normalizeEnvVersion(sourceEnvVersion)); extra.put("probeId", probeId); try { return submitImageWithExtra("INTEGRATION_PROBE", imageUrl, openId, objectMapper.writeValueAsString(extra)); @@ -76,6 +76,13 @@ public class WechatContentModerationProvider implements ContentModerationProvide } } + private String normalizeEnvVersion(String value) { + if ("developer".equalsIgnoreCase(value) || "develop".equalsIgnoreCase(value)) return "develop"; + if ("trial".equalsIgnoreCase(value)) return "trial"; + if ("formal".equalsIgnoreCase(value) || "release".equalsIgnoreCase(value)) return "release"; + return "UNKNOWN"; + } + private ModerationOutcome submitImageWithExtra(String contentType, String imageUrl, String openId, String extra) { if (!StringUtils.hasText(openId)) return pending("OPENID_REQUIRED", "缺少微信作者身份,转人工复核"); if (!StringUtils.hasText(imageUrl) || !imageUrl.startsWith("https://")) { diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/controller/admin/AdminSecureIntegrationConfigController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/controller/admin/AdminSecureIntegrationConfigController.java index f02f5fd9..f40efc2f 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/controller/admin/AdminSecureIntegrationConfigController.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/controller/admin/AdminSecureIntegrationConfigController.java @@ -38,7 +38,9 @@ public class AdminSecureIntegrationConfigController { @RequirePermission("messagehub:config:manage") public Result getConfig(HttpServletRequest request) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); - return Result.success(secureIntegrationConfigService.getAdminConfig(currentUser)); + SecureIntegrationConfigVO config = secureIntegrationConfigService.getAdminConfig(currentUser); + config.setProbeResults(integrationProbeService.listLatest(currentUser)); + return Result.success(config); } @GetMapping("/map-runtime") @@ -95,8 +97,12 @@ public class AdminSecureIntegrationConfigController { UserDO currentUser = adminScopeHelper.getCurrentUser(request); try { IntegrationProbeResultVO result = integrationProbeService.probe(currentUser, dto); - securityAuditSupport.success(request, SecurityAuditActions.SECURE_CONFIG_UPDATE, - "probe=" + dto.getService() + "/" + dto.getOperation() + ",status=" + result.getStatus()); + String auditDetail = "probe=" + dto.getService() + "/" + dto.getOperation() + ",status=" + result.getStatus(); + if ("FAIL".equals(result.getStatus())) { + securityAuditSupport.fail(request, SecurityAuditActions.SECURE_CONFIG_UPDATE, auditDetail); + } else { + securityAuditSupport.success(request, SecurityAuditActions.SECURE_CONFIG_UPDATE, auditDetail); + } return Result.success(result); } catch (RuntimeException exception) { securityAuditSupport.fail(request, SecurityAuditActions.SECURE_CONFIG_UPDATE, diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/service/impl/IntegrationProbeServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/service/impl/IntegrationProbeServiceImpl.java index f1cb0d62..b689e09a 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/service/impl/IntegrationProbeServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/service/impl/IntegrationProbeServiceImpl.java @@ -23,13 +23,14 @@ import com.xiaowang.jayucloud.salon.core.modules.system.vo.IntegrationProbeCheck import com.xiaowang.jayucloud.salon.core.modules.system.vo.IntegrationProbeResultVO; import com.xiaowang.jayucloud.salon.core.modules.system.vo.SecureIntegrationConfigVO; import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; -import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; import org.springframework.web.client.RestTemplate; import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.core.env.Environment; import java.io.InputStream; import java.nio.charset.StandardCharsets; @@ -43,7 +44,6 @@ import java.util.UUID; @Slf4j @Service -@RequiredArgsConstructor public class IntegrationProbeServiceImpl implements IntegrationProbeService { private static final String[] SERVICES = {"CONTENT_MODERATION", "MAP", "OBJECT_STORAGE", "SMS", "SUBSCRIBE_MESSAGE"}; private static final String TEXT = "CONTENT_MODERATION"; @@ -63,6 +63,33 @@ public class IntegrationProbeServiceImpl implements IntegrationProbeService { private final MessageHubPushConfigService messageHubPushConfigService; private final MessageHubClientService messageHubClientService; private final RestTemplate restTemplate; + private final Environment environment; + + public IntegrationProbeServiceImpl(IntegrationProbeResultMapper resultMapper, + ObjectMapper objectMapper, + SecureIntegrationConfigService secureIntegrationConfigService, + WechatMiniProperties wechatMiniProperties, + WechatMiniClientService wechatMiniClientService, + WechatMiniBindingMapper bindingMapper, + WechatContentModerationProvider wechatContentModerationProvider, + List storageProviders, + MessageHubPushConfigService messageHubPushConfigService, + MessageHubClientService messageHubClientService, + @Qualifier("restTemplate") RestTemplate restTemplate, + Environment environment) { + this.resultMapper = resultMapper; + this.objectMapper = objectMapper; + this.secureIntegrationConfigService = secureIntegrationConfigService; + this.wechatMiniProperties = wechatMiniProperties; + this.wechatMiniClientService = wechatMiniClientService; + this.bindingMapper = bindingMapper; + this.wechatContentModerationProvider = wechatContentModerationProvider; + this.storageProviders = storageProviders; + this.messageHubPushConfigService = messageHubPushConfigService; + this.messageHubClientService = messageHubClientService; + this.restTemplate = restTemplate; + this.environment = environment; + } @Override public IntegrationProbeResultVO probe(UserDO currentUser, IntegrationProbeRequestDTO request) { @@ -115,8 +142,21 @@ public class IntegrationProbeServiceImpl implements IntegrationProbeService { .eq(IntegrationProbeResultDO::getCorrelationKey, probeId).last("LIMIT 1")); } if (row == null) return false; - row.setStatus("pass".equalsIgnoreCase(suggest) ? "PASS" : "review".equalsIgnoreCase(suggest) ? "WARN" : "FAIL"); - row.setSummary("微信图片审核回调:" + (StringUtils.hasText(suggest) ? suggest : "review")); + if (!TEXT.equals(row.getServiceCode()) || !"IMAGE_CALLBACK".equals(row.getOperationCode())) return false; + if (!"PENDING".equals(row.getStatus())) return true; + if (row.getExpiresAt() != null && row.getExpiresAt().isBefore(LocalDateTime.now())) { + row.setStatus("FAIL"); + row.setSummary("图片审核回调已超过等待期限"); + row.setErrorCode("CALLBACK_TIMEOUT"); + row.setCheckedAt(LocalDateTime.now()); + deleteTemporaryObject(row); + resultMapper.updateById(row); + return true; + } + String candidateSuggest = StringUtils.hasText(suggest) ? suggest.trim().toLowerCase(Locale.ROOT) : "review"; + String normalizedSuggest = List.of("pass", "review", "risky").contains(candidateSuggest) ? candidateSuggest : "unknown"; + row.setStatus("pass".equals(normalizedSuggest) ? "PASS" : "review".equals(normalizedSuggest) ? "WARN" : "FAIL"); + row.setSummary("微信图片审核回调:" + normalizedSuggest); row.setCheckedAt(LocalDateTime.now()); try { row.setChecksJson(objectMapper.writeValueAsString(List.of(new IntegrationProbeCheckVO("微信图片审核回调", row.getStatus(), row.getSummary())))); } catch (Exception ignored) { } @@ -140,23 +180,50 @@ public class IntegrationProbeServiceImpl implements IntegrationProbeService { deleteTemporaryObject(row); resultMapper.updateById(row); } + List cleanup = resultMapper.selectList(new LambdaQueryWrapper() + .isNotNull(IntegrationProbeResultDO::getTemporaryObjectName) + .lt(IntegrationProbeResultDO::getExpiresAt, LocalDateTime.now())); + for (IntegrationProbeResultDO row : cleanup) { + deleteTemporaryObject(row); + resultMapper.updateById(row); + } } private IntegrationProbeResultVO probeModeration(UserDO currentUser, String operation, String mode) { SecureIntegrationConfigVO config = secureIntegrationConfigService.getAdminConfig(currentUser); List checks = new ArrayList<>(); - checks.add(check("加密主密钥", Boolean.TRUE.equals(config.getEncryptionKeyConfigured()), "已配置", "未配置,安全接入密钥无法读取")); - checks.add(check("审核 Provider", "WECHAT".equals(config.getModerationProvider()) || "MOCK".equals(config.getModerationProvider()), config.getModerationProvider(), "未启用")); - checks.add(check("小程序凭据", Boolean.TRUE.equals(config.getWechatMiniAppConfigured()), "AppID 与 AppSecret 已配置", "AppID 或 AppSecret 未配置")); - if ("WECHAT".equals(config.getModerationProvider())) { - checks.add(check("回调配置", Boolean.TRUE.equals(config.getModerationCallbackReady()), "公网 HTTPS 回调资料完整", "回调 URL、Token、AESKey 或加密主密钥不完整")); + String provider = config.getModerationProvider(); + if ("WECHAT".equals(provider)) { + checks.add(check("审核 Provider", true, "微信内容安全审核", "未启用")); + checks.add(check("加密主密钥", Boolean.TRUE.equals(config.getEncryptionKeyConfigured()), "已配置", "未配置,安全接入密钥无法读取")); + checks.add(check("小程序凭据", Boolean.TRUE.equals(config.getWechatMiniAppConfigured()), "AppID 与 AppSecret 已配置", "AppID 或 AppSecret 未配置")); + String callbackUrl = config.getModerationCallbackUrl(); + boolean callbackUrlValid = false; + try { + java.net.URI callback = java.net.URI.create(callbackUrl == null ? "" : callbackUrl); + callbackUrlValid = "https".equalsIgnoreCase(callback.getScheme()) + && StringUtils.hasText(callback.getHost()) + && (callback.getPort() == -1 || callback.getPort() == 443) + && callback.getUserInfo() == null && callback.getQuery() == null && callback.getFragment() == null + && "/api/integration/wechat/content-moderation/callback".equals(callback.getPath()); + } catch (IllegalArgumentException ignored) { } + checks.add(check("回调 HTTPS 地址", callbackUrlValid, "公网 HTTPS 回调地址有效", "回调地址缺失或格式不正确")); + checks.add(check("回调 Token", Boolean.TRUE.equals(config.getModerationCallbackTokenConfigured()), "已配置", "未配置")); + checks.add(check("EncodingAESKey", Boolean.TRUE.equals(config.getModerationEncodingAesKeyConfigured()), "已配置", "未配置")); + checks.add(check("回调配置汇总", Boolean.TRUE.equals(config.getModerationCallbackReady()), "回调资料完整", "回调 URL、Token、AESKey、加密主密钥或 App 凭据不完整")); + } else if ("MOCK".equals(provider)) { + boolean mockAllowed = Boolean.TRUE.equals(config.getMockProviderAllowed()); + checks.add(new IntegrationProbeCheckVO("审核 Provider", mockAllowed ? "PASS" : "FAIL", mockAllowed ? "本地模拟审核已启用" : "当前环境不允许模拟审核")); + checks.add(new IntegrationProbeCheckVO("真实接口", "WARN", "模拟渠道不会调用微信接口")); + } else { + checks.add(new IntegrationProbeCheckVO("审核 Provider", "WARN", "内容审核未启用,内容保持隔离")); } - if (!"WECHAT".equals(config.getModerationProvider())) checks.add(new IntegrationProbeCheckVO("加密主密钥", "WARN", "当前 Provider 不是真实微信审核,无需校验加密回调密钥")); if ("CONFIG".equals(operation)) return result(TEXT, operation, mode, config.getModerationProvider(), statusForChecks(checks), "内容审核配置诊断完成", null, checks); - if ("MOCK".equals(config.getModerationProvider())) { + if ("MOCK".equals(config.getModerationProvider()) && Boolean.TRUE.equals(config.getMockProviderAllowed())) { checks.add(new IntegrationProbeCheckVO("真实接口", "WARN", "当前使用本地模拟审核,不会调用微信接口")); return result(TEXT, operation, mode, "MOCK", "WARN", "当前为本地模拟流程", null, checks); } + if ("MOCK".equals(config.getModerationProvider())) return result(TEXT, operation, mode, "MOCK", "FAIL", "当前环境不允许使用模拟审核", "MOCK_NOT_ALLOWED", checks); if (!"WECHAT".equals(config.getModerationProvider())) return result(TEXT, operation, mode, config.getModerationProvider(), "FAIL", "微信内容审核未启用", "PROVIDER_DISABLED", checks); if (!Boolean.TRUE.equals(config.getModerationReady())) return result(TEXT, operation, mode, "WECHAT", "FAIL", "微信审核配置未就绪,未发起接口请求", "MODERATION_NOT_READY", checks); String openId = findProbeOpenId(); @@ -172,24 +239,43 @@ public class IntegrationProbeServiceImpl implements IntegrationProbeService { } private IntegrationProbeResultVO probeImageCallback(String mode, String openId, List checks) { + IntegrationProbeResultDO current = findResult(TEXT, "IMAGE_CALLBACK"); + if (current != null && "PENDING".equals(current.getStatus()) && current.getExpiresAt() != null && current.getExpiresAt().isAfter(LocalDateTime.now())) { + return result(TEXT, "IMAGE_CALLBACK", mode, "WECHAT", "PENDING", "已有图片测试正在等待微信回调", null, + List.of(new IntegrationProbeCheckVO("微信图片异步接口", "PENDING", "等待上一条测试的微信回调或超时清理"))); + } + if (current != null && StringUtils.hasText(current.getTemporaryObjectName())) { + deleteTemporaryObject(current); + resultMapper.updateById(current); + if (StringUtils.hasText(current.getTemporaryObjectName())) { + return result(TEXT, "IMAGE_CALLBACK", mode, "WECHAT", "FAIL", "上一张临时测试图片仍未清理,请稍后重试", "TEMP_CLEANUP_FAILED", + List.of(new IntegrationProbeCheckVO("临时图片清理", "FAIL", "无法确认旧测试文件已删除"))); + } + } String objectName = "integration-probe/" + UUID.randomUUID() + ".png"; String probeId = UUID.randomUUID().toString(); ObjectStorageProvider uploaded = null; boolean awaitingCallback = false; + boolean pendingSaved = false; try { byte[] image = createProbePng(); for (ObjectStorageProvider provider : storageProviders) { if (provider.isEnabled()) { - provider.uploadStream(new java.io.ByteArrayInputStream(image), image.length, "image/png", objectName); uploaded = provider; + provider.uploadStream(new java.io.ByteArrayInputStream(image), image.length, "image/png", objectName); break; } } if (uploaded == null) return result(TEXT, "IMAGE_CALLBACK", mode, "WECHAT", "FAIL", "没有可用对象存储,无法生成图片审核地址", "STORAGE_UNAVAILABLE", checks); String url = uploaded.getPresignedUrl(objectName, 5); - if (!StringUtils.hasText(url) || !url.startsWith("https://")) return result(TEXT, "IMAGE_CALLBACK", mode, "WECHAT", "FAIL", "对象存储未提供公网 HTTPS 签名地址", "IMAGE_URL_INVALID", checks); + if (!StringUtils.hasText(url) || !url.startsWith("https://")) { + checks.add(new IntegrationProbeCheckVO("临时图片地址", "FAIL", "对象存储未提供公网 HTTPS 签名地址")); + return result(TEXT, "IMAGE_CALLBACK", mode, "WECHAT", "FAIL", "对象存储未提供公网 HTTPS 签名地址", "IMAGE_URL_INVALID", checks); + } savePendingImageProbe(mode, probeId, uploaded.providerCode(), objectName); - ModerationOutcome outcome = wechatContentModerationProvider.submitTestImage(url, openId, probeId); + pendingSaved = true; + ModerationOutcome outcome = wechatContentModerationProvider.submitTestImage(url, openId, probeId, + wechatMiniProperties.getSubscribeMessageMiniprogramState()); String status = outcome.status() == ModerationOutcome.Status.PENDING ? "PENDING" : outcome.status() == ModerationOutcome.Status.APPROVED ? "PASS" : "FAIL"; checks.add(new IntegrationProbeCheckVO("微信图片异步接口", status, outcome.reason())); awaitingCallback = "PENDING".equals(status); @@ -199,7 +285,7 @@ public class IntegrationProbeServiceImpl implements IntegrationProbeService { checks.add(new IntegrationProbeCheckVO("微信图片异步接口", "FAIL", "临时图片上传或审核请求失败")); return result(TEXT, "IMAGE_CALLBACK", mode, "WECHAT", "FAIL", "微信图片审核探测失败", "IMAGE_PROBE_FAILED", checks); } finally { - if (uploaded != null && !awaitingCallback) try { uploaded.deleteFile(objectName); } catch (Exception ignored) { log.warn("清理接入测试临时图片失败"); } + if (uploaded != null && !awaitingCallback && !pendingSaved) try { uploaded.deleteFile(objectName); } catch (Exception ignored) { log.warn("清理接入测试临时图片失败"); } } } @@ -238,20 +324,30 @@ public class IntegrationProbeServiceImpl implements IntegrationProbeService { private void deleteTemporaryObject(IntegrationProbeResultDO row) { if (!StringUtils.hasText(row.getTemporaryObjectProvider()) || !StringUtils.hasText(row.getTemporaryObjectName())) return; - storageProviders.stream().filter(provider -> provider.providerCode().equals(row.getTemporaryObjectProvider())).findFirst().ifPresent(provider -> { - try { provider.deleteFile(row.getTemporaryObjectName()); } - catch (Exception ignored) { log.warn("清理接入测试临时图片失败,provider={}", provider.providerCode()); } - }); - row.setTemporaryObjectProvider(null); - row.setTemporaryObjectName(null); + ObjectStorageProvider provider = storageProviders.stream() + .filter(item -> item.providerCode().equals(row.getTemporaryObjectProvider())).findFirst().orElse(null); + if (provider == null) return; + try { + provider.deleteFile(row.getTemporaryObjectName()); + row.setTemporaryObjectProvider(null); + row.setTemporaryObjectName(null); + } catch (Exception ignored) { + log.warn("清理接入测试临时图片失败,provider={}", provider.providerCode()); + } } private IntegrationProbeResultVO probeMap(UserDO currentUser, String operation) { SecureIntegrationConfigVO config = secureIntegrationConfigService.getAdminConfig(currentUser); List checks = new ArrayList<>(); - boolean selectedKey = "AMAP".equals(config.getMapProvider()) ? Boolean.TRUE.equals(config.getAmapWebKeyConfigured()) : Boolean.TRUE.equals(config.getTencentWebKeyConfigured()); - checks.add(check("当前 Web Key", selectedKey, "已配置", "未配置")); - checks.add(new IntegrationProbeCheckVO("高德小程序 Key", Boolean.TRUE.equals(config.getAmapMiniKeyConfigured()) ? "PASS" : "WARN", Boolean.TRUE.equals(config.getAmapMiniKeyConfigured()) ? "已配置" : "未配置,仅影响小程序选点")); + boolean amapKey = Boolean.TRUE.equals(config.getAmapWebKeyConfigured()); + boolean tencentKey = Boolean.TRUE.equals(config.getTencentWebKeyConfigured()); + boolean miniKey = Boolean.TRUE.equals(config.getAmapMiniKeyConfigured()); + boolean selectedKey = "AMAP".equals(config.getMapProvider()) ? amapKey : tencentKey; + checks.add(check("当前渠道 Web Key", selectedKey, "已配置", "未配置")); + checks.add(new IntegrationProbeCheckVO("高德 Web Key", amapKey ? "PASS" : "WARN", amapKey ? "已配置" : "未配置")); + checks.add(new IntegrationProbeCheckVO("腾讯 Web Key", tencentKey ? "PASS" : "WARN", tencentKey ? "已配置" : "未配置")); + checks.add(new IntegrationProbeCheckVO("高德小程序 Key", miniKey ? "PASS" : "WARN", miniKey ? "已配置" : "未配置,仅影响小程序选点")); + if ("CONFIG".equals(operation)) return result(MAP, operation, "DIAGNOSTIC", config.getMapProvider(), statusForChecks(checks), "地图接入配置诊断完成", null, checks); if (!selectedKey) return result(MAP, operation, "DIAGNOSTIC", config.getMapProvider(), "FAIL", "当前地图渠道缺少 Web Key", "MAP_KEY_MISSING", checks); if (!Boolean.TRUE.equals(config.getMapEnabled())) return result(MAP, operation, "DIAGNOSTIC", config.getMapProvider(), "WARN", "地图服务当前已停用,保存并启用后才能测试真实请求", "MAP_DISABLED", checks); if ("CONFIG".equals(operation)) return result(MAP, operation, "DIAGNOSTIC", config.getMapProvider(), "PASS", "地图 Key 配置诊断完成", null, checks); @@ -277,7 +373,7 @@ public class IntegrationProbeServiceImpl implements IntegrationProbeService { for (ObjectStorageProvider provider : storageProviders) { checks.add(new IntegrationProbeCheckVO(provider.providerCode(), provider.isEnabled() ? "PASS" : "WARN", provider.isEnabled() ? "已启用并具备基本配置" : "未启用或配置不完整")); } - String status = checks.stream().anyMatch(item -> "WARN".equals(item.getStatus())) ? "WARN" : "PASS"; + String status = checks.isEmpty() ? "FAIL" : checks.stream().anyMatch(item -> "WARN".equals(item.getStatus())) ? "WARN" : "PASS"; return result(STORAGE, operation, "DIAGNOSTIC", "MULTI", status, status.equals("PASS") ? "对象存储配置完整" : "存在未启用的对象存储渠道", null, checks); } byte[] bytes = "salon-integration-probe".getBytes(StandardCharsets.UTF_8); @@ -290,6 +386,7 @@ public class IntegrationProbeServiceImpl implements IntegrationProbeService { continue; } enabled++; + boolean cleanupFailed = false; try { provider.uploadStream(new java.io.ByteArrayInputStream(bytes), bytes.length, "text/plain", objectName); try (InputStream input = provider.downloadFile(objectName)) { @@ -302,8 +399,10 @@ public class IntegrationProbeServiceImpl implements IntegrationProbeService { } catch (Exception exception) { checks.add(new IntegrationProbeCheckVO(provider.providerCode(), "FAIL", "上传或读取失败")); } finally { - try { provider.deleteFile(objectName); } catch (Exception ignored) { log.warn("清理对象存储测试文件失败,provider={}", provider.providerCode()); } + try { provider.deleteFile(objectName); } + catch (Exception ignored) { cleanupFailed = true; log.warn("清理对象存储测试文件失败,provider={}", provider.providerCode()); } } + if (cleanupFailed) checks.add(new IntegrationProbeCheckVO(provider.providerCode() + " 清理", "FAIL", "临时测试对象未能删除,请检查存储状态")); } String status = enabled == 0 ? "FAIL" : checks.stream().anyMatch(item -> "FAIL".equals(item.getStatus())) ? "FAIL" : checks.stream().anyMatch(item -> "WARN".equals(item.getStatus())) ? "WARN" : "PASS"; return result(STORAGE, operation, "DIAGNOSTIC", "MULTI", status, status.equals("PASS") ? "对象存储三副本往返测试成功" : "对象存储存在未就绪渠道", null, checks); @@ -316,9 +415,27 @@ public class IntegrationProbeServiceImpl implements IntegrationProbeService { List checks = new ArrayList<>(); List configs = messageHubPushConfigService.listConfigs(currentUser); List expectedScenes = List.of("USER_REGISTER_SMS_CODE", "USER_LOGIN_SMS_CODE", "USER_RESET_PASSWORD_SMS_CODE", "USER_BIND_PHONE_SMS_CODE", "USER_CHANGE_PHONE_SMS_CODE", "USER_CHANGE_PASSWORD_SMS_CODE"); - long enabled = expectedScenes.stream().filter(scene -> configs.stream().anyMatch(item -> scene.equals(item.getSceneCode()) && Integer.valueOf(1).equals(item.getEnabled()))).count(); - checks.add(new IntegrationProbeCheckVO("短信业务场景", enabled == expectedScenes.size() ? "PASS" : "FAIL", enabled + "/" + expectedScenes.size() + " 个场景已启用")); - boolean complete = enabled == expectedScenes.size(); + long enabled = expectedScenes.stream().filter(scene -> configs.stream().anyMatch(item -> scene.equals(item.getSceneCode()) + && "SMS".equalsIgnoreCase(item.getPlatform()) && Integer.valueOf(1).equals(item.getEnabled()) + && StringUtils.hasText(item.getSendMethod()) && StringUtils.hasText(item.getQueueName()) + && StringUtils.hasText(item.getTemplateCode()))).count(); + checks.add(new IntegrationProbeCheckVO("短信业务场景", enabled == expectedScenes.size() ? "PASS" : "FAIL", enabled + "/" + expectedScenes.size() + " 个场景配置完整并启用")); + String baseUrl = environment.getProperty("messagehub.client.base-url", "http://192.168.10.107:8080"); + String accessToken = environment.getProperty("messagehub.client.access-token"); + String exchange = environment.getProperty("messagehub.client.ingress-exchange", "messagehub.ingress.exchange"); + String routingKey = environment.getProperty("messagehub.client.ingress-routing-key", "message.send"); + String smsQueue = environment.getProperty("messagehub.client.sms-queue", "smsQueue"); + String sourceSystem = environment.getProperty("messagehub.client.source-system", "jayucloud-salon"); + String templateCode = environment.getProperty("messagehub.client.verify-template-code", "SPUG_SMS_VERIFY_1"); + String sendMethod = environment.getProperty("messagehub.client.send-method", "SPUG"); + boolean endpointConfigured = safeHttpUrl(baseUrl); + checks.add(check("MessageHub 地址", endpointConfigured, "已配置 HTTP(S) 地址", "地址未配置或格式无效")); + checks.add(check("MessageHub 访问凭据", StringUtils.hasText(accessToken), "已配置", "未配置")); + boolean deliveryConfigured = StringUtils.hasText(exchange) && StringUtils.hasText(routingKey) + && StringUtils.hasText(smsQueue) && StringUtils.hasText(sourceSystem) + && StringUtils.hasText(templateCode) && StringUtils.hasText(sendMethod); + checks.add(check("短信投递参数", deliveryConfigured, "交换机、路由、队列、来源和模板已配置", "部分投递参数缺失")); + boolean complete = enabled == expectedScenes.size() && endpointConfigured && StringUtils.hasText(accessToken) && deliveryConfigured; if ("CONFIG".equals(operation) || !"REAL".equals(mode)) return result(SMS, operation, mode, "MESSAGEHUB", complete ? "PASS" : "FAIL", complete ? "短信场景配置完整;未发送真实短信" : "部分短信场景未启用", null, checks); if (!complete) return result(SMS, operation, mode, "MESSAGEHUB", "FAIL", "短信场景配置不完整,未发送测试短信", "SMS_CONFIG_INCOMPLETE", checks); if (!StringUtils.hasText(phone) || !phone.matches("^1[3-9]\\d{9}$")) throw new IllegalArgumentException("真实短信测试需要填写有效手机号"); @@ -332,11 +449,21 @@ public class IntegrationProbeServiceImpl implements IntegrationProbeService { List checks = new ArrayList<>(); String provider = StringUtils.hasText(wechatMiniProperties.getSubscribeMessageProvider()) ? wechatMiniProperties.getSubscribeMessageProvider().trim().toLowerCase(Locale.ROOT) : "mock"; boolean enabled = Boolean.TRUE.equals(wechatMiniProperties.getSubscribeMessageEnabled()); - checks.add(new IntegrationProbeCheckVO("发送渠道", "wechat".equals(provider) && enabled ? "PASS" : "WARN", "wechat".equals(provider) && enabled ? "微信真实发送已启用" : "当前为 Mock 或已停用")); + boolean liveProvider = "wechat".equals(provider) && enabled; + checks.add(new IntegrationProbeCheckVO("发送渠道", liveProvider ? "PASS" : "WARN", liveProvider ? "微信真实发送已启用" : "当前为 Mock 或已停用")); + if (!liveProvider) { + checks.add(new IntegrationProbeCheckVO("小程序凭据", "WARN", "当前未调用微信接口,因此不校验真实凭据")); + checks.add(new IntegrationProbeCheckVO("固定模板", "PASS", "3 个固定模板 ID 已加载")); + return result(SUBSCRIBE, operation, mode, provider.toUpperCase(Locale.ROOT), "WARN", + "当前为 Mock 或已停用,未调用微信接口", null, checks); + } boolean credentials = StringUtils.hasText(wechatMiniProperties.getAppId()) && StringUtils.hasText(wechatMiniProperties.getAppSecret()); checks.add(check("小程序凭据", credentials, "已配置", "AppID 或 AppSecret 未配置")); if (!credentials) return result(SUBSCRIBE, operation, mode, "WECHAT", "FAIL", "订阅消息凭据不完整", "WECHAT_CREDENTIALS_MISSING", checks); - if (!"wechat".equals(provider) || !enabled) return result(SUBSCRIBE, operation, mode, provider.toUpperCase(Locale.ROOT), "WARN", "当前订阅消息未启用微信真实发送", "PROVIDER_NOT_LIVE", checks); + checks.add(check("固定模板", WechatSubscribeMessageService.TEMPLATE_APPOINTMENT.length() > 10 + && WechatSubscribeMessageService.TEMPLATE_CANCELLED.length() > 10 + && WechatSubscribeMessageService.TEMPLATE_SERVICE_START.length() > 10, + "3 个固定模板 ID 已加载", "固定模板 ID 不完整")); try { wechatMiniClientService.getAccessTokenForContentModeration(); checks.add(new IntegrationProbeCheckVO("access_token", "PASS", "获取成功")); @@ -360,7 +487,7 @@ public class IntegrationProbeServiceImpl implements IntegrationProbeService { private IntegrationProbeResultVO checkSubscribeTemplates(String operation, String mode, List checks) throws Exception { String accessToken = wechatMiniClientService.getAccessTokenForContentModeration(); - String url = "https://api.weixin.qq.com/cgi-bin/wxopen/template/list?access_token=" + java.net.URLEncoder.encode(accessToken, StandardCharsets.UTF_8); + String url = "https://api.weixin.qq.com/wxaapi/newtmpl/gettemplate?access_token=" + java.net.URLEncoder.encode(accessToken, StandardCharsets.UTF_8); JsonNode response = objectMapper.readTree(restTemplate.getForObject(url, String.class)); int errorCode = response.path("errcode").asInt(0); if (errorCode != 0) { @@ -390,9 +517,9 @@ public class IntegrationProbeServiceImpl implements IntegrationProbeService { private void validateOperation(String service, String operation, String mode) { boolean valid = switch (service) { - case TEXT -> List.of("CONFIG", "TEXT", "IMAGE_CALLBACK").contains(operation); - case MAP -> List.of("CONFIG", "REQUEST").contains(operation); - case STORAGE -> List.of("CONFIG", "ROUND_TRIP").contains(operation); + case TEXT -> "DIAGNOSTIC".equals(mode) && List.of("CONFIG", "TEXT", "IMAGE_CALLBACK").contains(operation); + case MAP -> "DIAGNOSTIC".equals(mode) && List.of("CONFIG", "REQUEST").contains(operation); + case STORAGE -> "DIAGNOSTIC".equals(mode) && List.of("CONFIG", "ROUND_TRIP").contains(operation); case SMS -> ("CONFIG".equals(operation) && "DIAGNOSTIC".equals(mode)) || ("SEND".equals(operation) && "REAL".equals(mode)); case SUBSCRIBE -> ("CONFIG".equals(operation) && "DIAGNOSTIC".equals(mode)) || ("SEND".equals(operation) && "REAL".equals(mode)); default -> false; @@ -434,6 +561,13 @@ public class IntegrationProbeServiceImpl implements IntegrationProbeService { } private String normalize(String value) { return StringUtils.hasText(value) ? value.trim().toUpperCase(Locale.ROOT) : ""; } + private boolean safeHttpUrl(String value) { + if (!StringUtils.hasText(value)) return false; + try { + java.net.URI uri = java.net.URI.create(value.trim()); + return ("http".equalsIgnoreCase(uri.getScheme()) || "https".equalsIgnoreCase(uri.getScheme())) && StringUtils.hasText(uri.getHost()); + } catch (IllegalArgumentException ignored) { return false; } + } private String safeMessage(RuntimeException exception) { return "探测请求未完成,请查看脱敏检查项"; } private String subscribeSendError(int code) { if (code == 43101) return "当前绑定账号尚未授权此订阅模板"; diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/vo/SecureIntegrationConfigVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/vo/SecureIntegrationConfigVO.java index 4c3be1a1..d8c3d72d 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/vo/SecureIntegrationConfigVO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/vo/SecureIntegrationConfigVO.java @@ -3,6 +3,7 @@ package com.xiaowang.jayucloud.salon.core.modules.system.vo; import lombok.Data; import java.time.LocalDateTime; +import java.util.List; @Data public class SecureIntegrationConfigVO { @@ -25,4 +26,6 @@ public class SecureIntegrationConfigVO { private Boolean encryptionKeyConfigured; private LocalDateTime updatedAt; + /** 最近一次各服务接入探测结果;仅返回脱敏摘要和检查项。 */ + private List probeResults; } diff --git a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/privacy/controller/front/WechatContentModerationCallbackControllerTest.java b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/privacy/controller/front/WechatContentModerationCallbackControllerTest.java index f7b50956..6b91d189 100644 --- a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/privacy/controller/front/WechatContentModerationCallbackControllerTest.java +++ b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/privacy/controller/front/WechatContentModerationCallbackControllerTest.java @@ -6,6 +6,7 @@ import com.xiaowang.jayucloud.salon.core.modules.privacy.service.ContentModerati import com.xiaowang.jayucloud.salon.core.modules.privacy.support.WechatCallbackCrypto; import com.xiaowang.jayucloud.salon.core.modules.system.secure.ModerationRuntimeConfig; import com.xiaowang.jayucloud.salon.core.modules.system.service.SecureIntegrationConfigService; +import com.xiaowang.jayucloud.salon.core.modules.system.service.IntegrationProbeService; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; @@ -37,6 +38,7 @@ class WechatContentModerationCallbackControllerTest { wechatProperties, crypto, mock(ContentModerationService.class), + mock(IntegrationProbeService.class), new ObjectMapper()); String result = controller.verifyEndpoint("1000", "nonce", "message-signature", null, "aes", "encrypted-echo"); @@ -58,6 +60,7 @@ class WechatContentModerationCallbackControllerTest { new WechatMiniProperties(), crypto, mock(ContentModerationService.class), + mock(IntegrationProbeService.class), new ObjectMapper()); assertEquals("echo", controller.verifyEndpoint("1000", "nonce", null, "plain-signature", null, "echo")); @@ -132,6 +135,6 @@ class WechatContentModerationCallbackControllerTest { WechatMiniProperties wechatProperties = new WechatMiniProperties(); wechatProperties.setAppId("mini-app-id"); return new WechatContentModerationCallbackController( - secureConfig, wechatProperties, crypto, moderationService, new ObjectMapper()); + secureConfig, wechatProperties, crypto, moderationService, mock(IntegrationProbeService.class), new ObjectMapper()); } } diff --git a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/system/service/impl/IntegrationProbeServiceImplTest.java b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/system/service/impl/IntegrationProbeServiceImplTest.java new file mode 100644 index 00000000..ea8eefd0 --- /dev/null +++ b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/system/service/impl/IntegrationProbeServiceImplTest.java @@ -0,0 +1,139 @@ +package com.xiaowang.jayucloud.salon.core.modules.system.service.impl; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.xiaowang.jayucloud.salon.core.config.WechatMiniProperties; +import com.xiaowang.jayucloud.salon.core.modules.file.service.ObjectStorageProvider; +import com.xiaowang.jayucloud.salon.core.modules.integration.entity.WechatMiniBindingDO; +import com.xiaowang.jayucloud.salon.core.modules.integration.mapper.WechatMiniBindingMapper; +import com.xiaowang.jayucloud.salon.core.modules.integration.service.MessageHubClientService; +import com.xiaowang.jayucloud.salon.core.modules.integration.service.MessageHubPushConfigService; +import com.xiaowang.jayucloud.salon.core.modules.integration.service.WechatMiniClientService; +import com.xiaowang.jayucloud.salon.core.modules.privacy.moderation.WechatContentModerationProvider; +import com.xiaowang.jayucloud.salon.core.modules.system.dto.IntegrationProbeRequestDTO; +import com.xiaowang.jayucloud.salon.core.modules.system.entity.IntegrationProbeResultDO; +import com.xiaowang.jayucloud.salon.core.modules.system.mapper.IntegrationProbeResultMapper; +import com.xiaowang.jayucloud.salon.core.modules.system.service.SecureIntegrationConfigService; +import com.xiaowang.jayucloud.salon.core.modules.system.vo.SecureIntegrationConfigVO; +import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; +import org.junit.jupiter.api.Test; +import org.springframework.core.env.Environment; +import org.springframework.web.client.RestTemplate; + +import java.time.LocalDateTime; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +class IntegrationProbeServiceImplTest { + private final IntegrationProbeResultMapper results = mock(IntegrationProbeResultMapper.class); + private final SecureIntegrationConfigService secureConfig = mock(SecureIntegrationConfigService.class); + private final WechatMiniProperties wechatProperties = new WechatMiniProperties(); + private final WechatMiniClientService wechatClient = mock(WechatMiniClientService.class); + private final WechatMiniBindingMapper bindings = mock(WechatMiniBindingMapper.class); + private final WechatContentModerationProvider moderationProvider = mock(WechatContentModerationProvider.class); + private final ObjectStorageProvider storageProvider = mock(ObjectStorageProvider.class); + private final MessageHubPushConfigService smsConfigs = mock(MessageHubPushConfigService.class); + private final MessageHubClientService smsClient = mock(MessageHubClientService.class); + private final RestTemplate restTemplate = mock(RestTemplate.class); + private final Environment environment = mock(Environment.class); + private final IntegrationProbeServiceImpl service = new IntegrationProbeServiceImpl( + results, new ObjectMapper(), secureConfig, wechatProperties, wechatClient, bindings, + moderationProvider, List.of(storageProvider), smsConfigs, smsClient, restTemplate, environment); + + @Test + void rejectsNonAdminBeforeAnyProbeSideEffect() { + UserDO manager = new UserDO(); + manager.setType(2); + + assertThrows(RuntimeException.class, () -> service.probe(manager, request("SMS", "CONFIG", "DIAGNOSTIC", false))); + verify(smsConfigs, never()).listConfigs(any()); + } + + @Test + void realSmsCannotBeSentWithoutExplicitConfirmation() { + assertThrows(IllegalArgumentException.class, + () -> service.probe(admin(), request("SMS", "SEND", "REAL", false))); + verify(smsClient, never()).sendSmsVerificationCode(any(), any(), any()); + } + + @Test + void devMockIsNotReportedAsAnAllowedMockWhenEnvironmentDisallowsIt() { + SecureIntegrationConfigVO config = new SecureIntegrationConfigVO(); + config.setModerationProvider("MOCK"); + config.setMockProviderAllowed(false); + when(secureConfig.getAdminConfig(any())).thenReturn(config); + when(results.selectOne(any())).thenReturn(null); + + var result = service.probe(admin(), request("CONTENT_MODERATION", "CONFIG", "DIAGNOSTIC", false)); + + assertEquals("FAIL", result.getStatus()); + verify(moderationProvider, never()).reviewText(any(), any(), any()); + } + + @Test + void subscribeDiagnosticInMockModeDoesNotFetchTokenOrSendAnything() { + wechatProperties.setAppId("test-app"); + wechatProperties.setAppSecret("test-secret"); + wechatProperties.setSubscribeMessageEnabled(true); + wechatProperties.setSubscribeMessageProvider("mock"); + when(results.selectOne(any())).thenReturn(null); + + var result = service.probe(admin(), request("SUBSCRIBE_MESSAGE", "CONFIG", "DIAGNOSTIC", false)); + + assertEquals("WARN", result.getStatus()); + verify(wechatClient, never()).getAccessTokenForContentModeration(); + verify(wechatClient, never()).sendSubscribeMessage(any(), any(), any(), any(), any()); + } + + @Test + void anOutstandingImageProbePreventsAnotherTemporaryUpload() throws Exception { + wechatProperties.setAppId("test-app"); + SecureIntegrationConfigVO config = new SecureIntegrationConfigVO(); + config.setModerationProvider("WECHAT"); + config.setModerationReady(true); + config.setModerationCallbackReady(true); + config.setEncryptionKeyConfigured(true); + config.setWechatMiniAppConfigured(true); + when(secureConfig.getAdminConfig(any())).thenReturn(config); + WechatMiniBindingDO binding = new WechatMiniBindingDO(); + binding.setOpenId("private-open-id"); + when(bindings.selectOne(any())).thenReturn(binding); + IntegrationProbeResultDO pending = new IntegrationProbeResultDO(); + pending.setId(10L); + pending.setServiceCode("CONTENT_MODERATION"); + pending.setOperationCode("IMAGE_CALLBACK"); + pending.setStatus("PENDING"); + pending.setExpiresAt(LocalDateTime.now().plusMinutes(2)); + when(results.selectOne(any())).thenReturn(pending); + + var result = service.probe(admin(), request("CONTENT_MODERATION", "IMAGE_CALLBACK", "DIAGNOSTIC", false)); + + assertEquals("PENDING", result.getStatus()); + verify(storageProvider, never()).uploadStream(any(), anyLong(), any(), any()); + verify(moderationProvider, never()).submitTestImage(any(), any(), any(), any()); + } + + private UserDO admin() { + UserDO user = new UserDO(); + user.setId(1L); + user.setType(4); + return user; + } + + private IntegrationProbeRequestDTO request(String service, String operation, String mode, boolean confirmed) { + IntegrationProbeRequestDTO request = new IntegrationProbeRequestDTO(); + request.setService(service); + request.setOperation(operation); + request.setMode(mode); + request.setConfirmed(confirmed); + request.setTargetPhone("13800138000"); + return request; + } +} diff --git a/JC-Salon-Frontend/src/utils/moderation-status.test.ts b/JC-Salon-Frontend/src/utils/moderation-status.test.ts new file mode 100644 index 00000000..899da260 --- /dev/null +++ b/JC-Salon-Frontend/src/utils/moderation-status.test.ts @@ -0,0 +1,35 @@ +import { describe, expect, it } from 'vitest' +import type { SecureIntegrationConfigVO } from '@/api/admin' +import { buildModerationNotice } from './moderation-status' + +function config(overrides: Partial = {}): SecureIntegrationConfigVO { + return { + mapProvider: 'TENCENT', mapEnabled: true, tencentWebKeyConfigured: false, amapWebKeyConfigured: false, + amapMiniKeyConfigured: false, mapLegacyMigrationPending: false, moderationProvider: 'DISABLED', + moderationCallbackUrl: '', moderationCallbackTokenConfigured: false, moderationEncodingAesKeyConfigured: false, + moderationCallbackReady: false, moderationReady: false, wechatMiniAppConfigured: false, + wechatMiniAppId: '', mockProviderAllowed: false, encryptionKeyConfigured: false, ...overrides + } +} + +describe('buildModerationNotice', () => { + it('only describes mock behavior when current environment permits it', () => { + expect(buildModerationNotice(config({ moderationProvider: 'MOCK', mockProviderAllowed: true })).title) + .toBe('当前使用本地模拟审核') + expect(buildModerationNotice(config({ moderationProvider: 'MOCK', mockProviderAllowed: false })).title) + .toBe('当前环境不允许模拟审核') + }) + + it('distinguishes disabled, incomplete and ready WeChat providers', () => { + expect(buildModerationNotice(config()).title).toBe('内容审核未启用') + expect(buildModerationNotice(config({ moderationProvider: 'WECHAT' })).title).toBe('微信内容审核尚未就绪') + expect(buildModerationNotice(config({ + moderationProvider: 'WECHAT', moderationReady: true, moderationCallbackReady: true, + wechatMiniAppConfigured: true, encryptionKeyConfigured: true + })).title).toBe('当前使用微信内容安全审核') + }) + + it('does not claim a provider when configuration cannot be read', () => { + expect(buildModerationNotice(null, true).title).toBe('无法读取内容审核状态') + }) +}) diff --git a/JC-Salon-Frontend/src/utils/moderation-status.ts b/JC-Salon-Frontend/src/utils/moderation-status.ts new file mode 100644 index 00000000..9055115e --- /dev/null +++ b/JC-Salon-Frontend/src/utils/moderation-status.ts @@ -0,0 +1,64 @@ +import type { SecureIntegrationConfigVO } from '@/api/admin' + +export type ModerationNotice = { + type: 'info' | 'warning' | 'error' | 'success' + title: string + description: string +} + +export function buildModerationNotice(config: SecureIntegrationConfigVO | null, statusUnavailable = false): ModerationNotice { + if (statusUnavailable) return { + type: 'error', + title: '无法读取内容审核状态', + description: '状态未知时请勿假设微信审核已生效;可重试加载或前往系统设置检查接入配置。' + } + if (!config) return { + type: 'info', + title: '正在读取内容审核状态', + description: '正在读取当前环境的真实审核渠道和最近探测结果。' + } + const latest = (config.probeResults || []) + .filter(item => item.service === 'CONTENT_MODERATION') + .sort((a, b) => String(b.checkedAt || '').localeCompare(String(a.checkedAt || '')))[0] + if (config.moderationProvider === 'MOCK' && config.mockProviderAllowed) return { + type: 'warning', + title: '当前使用本地模拟审核', + description: '不会调用微信内容安全接口,仅适用于当前允许模拟的开发环境。正式环境请切换为微信内容安全审核。' + } + if (config.moderationProvider === 'MOCK') return { + type: 'error', + title: '当前环境不允许模拟审核', + description: '已保存的模拟渠道不能在当前环境生效,内容仍保持隔离。请切换到微信审核或停用后人工处理。' + } + if (config.moderationProvider === 'DISABLED') return { + type: 'error', + title: '内容审核未启用', + description: '内容会保持隔离,不会自动放行。请在系统设置的服务接入中完成配置。' + } + if (!config.moderationReady) { + const missing = [ + !config.encryptionKeyConfigured && '服务端加密主密钥', + !config.wechatMiniAppConfigured && '小程序 AppID/AppSecret', + !config.moderationCallbackTokenConfigured && '回调 Token', + !config.moderationEncodingAesKeyConfigured && 'EncodingAESKey', + !config.moderationCallbackReady && '公网 HTTPS 回调' + ].filter(Boolean).join('、') + return { + type: 'warning', + title: '微信内容审核尚未就绪', + description: `当前已选择微信审核,但${missing || '配置校验未通过'}。请先完成配置并运行接入测试。` + } + } + const latestText = latest + ? `最近探测:${probeLabel(latest.status)} · ${latest.summary}(${latest.checkedAt ? new Date(latest.checkedAt).toLocaleString('zh-CN', { hour12: false }) : '暂无时间'})` + : '尚未运行接入探测。' + return { + type: 'success', + title: '当前使用微信内容安全审核', + description: `内容须通过微信审核后才会公开展示。${latestText}` + } +} + +function probeLabel(status?: string) { + return ({ PASS: '通过', WARN: '需关注', FAIL: '失败', PENDING: '等待回调' } as Record)[status || ''] || '未知' +} diff --git a/JC-Salon-Frontend/src/views/admin/PrivacyComplianceView.vue b/JC-Salon-Frontend/src/views/admin/PrivacyComplianceView.vue index b9b78461..0aa9ba22 100644 --- a/JC-Salon-Frontend/src/views/admin/PrivacyComplianceView.vue +++ b/JC-Salon-Frontend/src/views/admin/PrivacyComplianceView.vue @@ -9,11 +9,19 @@ + > + + @@ -74,7 +82,7 @@ - + @@ -325,6 +361,7 @@ onActivated(() => { .payload-preview { max-width: 420px; max-height: 180px; margin: 0; overflow: auto; white-space: pre-wrap; word-break: break-word; font-size: 12px; } .moderation-content { display: grid; gap: 6px; } .moderation-author { color: var(--ant-color-text-secondary); font-size: 12px; } +.moderation-provider-context { color: var(--ant-color-text-secondary); font-size: 12px; line-height: 1.55; } .image-pending { color: var(--ant-color-text-secondary); font-size: 12px; } .backfill-panel { width: 100%; padding: 8px 0; } .closure-shops { display: grid; gap: 12px; margin-bottom: 16px; } diff --git a/JC-Salon-Frontend/src/views/admin/SystemSettingsView.vue b/JC-Salon-Frontend/src/views/admin/SystemSettingsView.vue index 3658c4df..d0661038 100644 --- a/JC-Salon-Frontend/src/views/admin/SystemSettingsView.vue +++ b/JC-Salon-Frontend/src/views/admin/SystemSettingsView.vue @@ -36,27 +36,6 @@ -
-
接入诊断TEST
-
-
-
- {{ card.label }} - {{ card.description }} - 最近:{{ probeFor(card.service)?.summary }} · {{ formatProbeTime(probeFor(card.service)?.checkedAt) }} -
-
- {{ card.action }} - 图片回调 - 真实发送 -
- {{ probeStatusLabel(probeFor(card.service)?.status) }} - 未测试 -
-
-

配置保存后再测试。短信和订阅消息默认只诊断,真实发送会产生外部副作用并要求二次确认;对象存储测试文件会自动清理。

-
-
账号默认值USER保存密码设置
@@ -128,6 +107,34 @@
+
+
接入诊断TEST刷新最近结果
+
+
+
+ {{ card.label }} + {{ card.description }} +
+
+
+ {{ operation.label }} + {{ probeStatusLabel(probeFor(card.service, operation.code)?.status) }} + 未测试 + {{ probeFor(card.service, operation.code)?.summary }} · {{ formatProbeTime(probeFor(card.service, operation.code)?.checkedAt) }} + + +
+ {{ check.name }}{{ probeStatusLabel(check.status) }}{{ check.detail }} +
+
+
+
+
+
+
+

配置保存后再测试。短信和订阅消息默认只诊断,真实发送会产生外部副作用并要求二次确认;对象存储测试文件会自动清理。微信图片测试提交后显示等待回调,不会把异步结果误报为失败。

+
+
地图服务安全接入保存地图设置
@@ -279,10 +286,11 @@
- +