增加系统接入诊断基础能力
This commit is contained in:
+15
-1
@@ -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("微信审核回调消息体为空");
|
||||
|
||||
+16
-1
@@ -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<String, String> 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);
|
||||
}
|
||||
|
||||
|
||||
+30
@@ -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<List<IntegrationProbeResultVO>> 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<IntegrationProbeResultVO> 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+18
@@ -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;
|
||||
}
|
||||
+54
@@ -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;
|
||||
}
|
||||
+9
@@ -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<IntegrationProbeResultDO> {
|
||||
}
|
||||
+15
@@ -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<IntegrationProbeResultVO> listLatest(UserDO currentUser);
|
||||
|
||||
boolean handleImageCallback(String taskId, String suggest, String probeId);
|
||||
}
|
||||
+447
@@ -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<ObjectStorageProvider> 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<IntegrationProbeResultVO> listLatest(UserDO currentUser) {
|
||||
requirePlatformAdmin(currentUser);
|
||||
return resultMapper.selectList(new LambdaQueryWrapper<IntegrationProbeResultDO>()
|
||||
.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<IntegrationProbeResultDO>()
|
||||
.eq(IntegrationProbeResultDO::getRemoteTaskId, taskId).last("LIMIT 1"));
|
||||
}
|
||||
if (row == null && StringUtils.hasText(probeId)) {
|
||||
row = resultMapper.selectOne(new LambdaQueryWrapper<IntegrationProbeResultDO>()
|
||||
.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<IntegrationProbeResultDO> expired = resultMapper.selectList(new LambdaQueryWrapper<IntegrationProbeResultDO>()
|
||||
.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<IntegrationProbeCheckVO> 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<IntegrationProbeCheckVO> 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<IntegrationProbeResultDO>()
|
||||
.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<IntegrationProbeResultDO>()
|
||||
.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<IntegrationProbeCheckVO> 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<String, String> 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<IntegrationProbeCheckVO> 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<IntegrationProbeCheckVO> checks = new ArrayList<>();
|
||||
List<com.xiaowang.jayucloud.salon.core.modules.integration.vo.MessageHubPushConfigVO> configs = messageHubPushConfigService.listConfigs(currentUser);
|
||||
List<String> 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<IntegrationProbeCheckVO> 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<IntegrationProbeCheckVO> 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<String> 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<String> 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<IntegrationProbeCheckVO> 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<IntegrationProbeCheckVO> 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<WechatMiniBindingDO>()
|
||||
.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<List<IntegrationProbeCheckVO>>() {})); } 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("仅平台管理员可以测试系统接入"); }
|
||||
}
|
||||
+14
@@ -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;
|
||||
}
|
||||
+20
@@ -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<IntegrationProbeCheckVO> checks = new ArrayList<>();
|
||||
}
|
||||
@@ -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='系统接入最近一次诊断结果';
|
||||
@@ -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<SecureIntegrationConfigVO>('/system-settings/secure-integration') as unknown as Promise<SecureIntegrationConfigVO>,
|
||||
listProbeResults: () => adminApi.get<IntegrationProbeResultVO[]>('/system-settings/secure-integration/probe-results') as unknown as Promise<IntegrationProbeResultVO[]>,
|
||||
probe: (data: IntegrationProbeRequest) => adminApi.post<IntegrationProbeResultVO>('/system-settings/secure-integration/probe', data) as unknown as Promise<IntegrationProbeResultVO>,
|
||||
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<SecureIntegrationConfigVO>('/system-settings/secure-integration/map', data) as unknown as Promise<SecureIntegrationConfigVO>,
|
||||
saveModerationConfig: (data: SecureIntegrationConfigUpdate) => adminApi.post<SecureIntegrationConfigVO>('/system-settings/secure-integration/content-moderation', data) as unknown as Promise<SecureIntegrationConfigVO>
|
||||
|
||||
@@ -36,6 +36,27 @@
|
||||
<span />
|
||||
</div>
|
||||
|
||||
<div class="setting-group probe-group">
|
||||
<div class="setting-group__head"><strong>接入诊断</strong><span>TEST</span></div>
|
||||
<div class="probe-list">
|
||||
<div v-for="card in probeCards" :key="card.service" class="probe-row">
|
||||
<div class="probe-row__copy">
|
||||
<strong>{{ card.label }}</strong>
|
||||
<span>{{ card.description }}</span>
|
||||
<small v-if="probeFor(card.service)">最近:{{ probeFor(card.service)?.summary }} · {{ formatProbeTime(probeFor(card.service)?.checkedAt) }}</small>
|
||||
</div>
|
||||
<div class="probe-row__actions">
|
||||
<a-button size="small" :loading="testingProbe === `${card.service}:${card.operation}`" @click="runProbe(card.service, card.operation)">{{ card.action }}</a-button>
|
||||
<a-button v-if="card.service === 'CONTENT_MODERATION'" size="small" type="link" :loading="testingProbe === 'CONTENT_MODERATION:IMAGE_CALLBACK'" @click="runProbe('CONTENT_MODERATION', 'IMAGE_CALLBACK')">图片回调</a-button>
|
||||
<a-button v-if="card.service === 'SMS' || card.service === 'SUBSCRIBE_MESSAGE'" size="small" type="link" @click="openRealProbe(card.service)">真实发送</a-button>
|
||||
</div>
|
||||
<span v-if="probeFor(card.service)" :class="['status-pill', `probe-status--${probeFor(card.service)?.status.toLowerCase()}`]">{{ probeStatusLabel(probeFor(card.service)?.status) }}</span>
|
||||
<span v-else class="status-pill is-muted">未测试</span>
|
||||
</div>
|
||||
</div>
|
||||
<p class="secure-note">配置保存后再测试。短信和订阅消息默认只诊断,真实发送会产生外部副作用并要求二次确认;对象存储测试文件会自动清理。</p>
|
||||
</div>
|
||||
|
||||
<div class="setting-group">
|
||||
<div class="setting-group__head setting-group__head--with-action"><strong>账号默认值</strong><span>USER</span><a-button size="small" type="primary" :loading="savingDefaultPassword" @click="saveDefaultPassword">保存密码设置</a-button></div>
|
||||
<div class="setting-row setting-row--last">
|
||||
@@ -257,6 +278,17 @@
|
||||
</section>
|
||||
</main>
|
||||
</div>
|
||||
|
||||
<a-modal v-model:open="realProbeOpen" title="确认真实接入测试" :confirm-loading="realProbeLoading" ok-text="确认发送" cancel-text="取消" @ok="submitRealProbe">
|
||||
<template v-if="realProbeService === 'SMS'">
|
||||
<p>将向指定手机号发送一条真实测试短信,可能产生费用。</p>
|
||||
<a-input v-model:value="realProbePhone" placeholder="请输入接收手机号" maxlength="11" />
|
||||
</template>
|
||||
<template v-else>
|
||||
<p>将向当前环境已有微信绑定账号发送一条真实订阅消息,可能消耗订阅额度。</p>
|
||||
<a-checkbox v-model:checked="realProbeConfirmed">我确认发送真实测试消息</a-checkbox>
|
||||
</template>
|
||||
</a-modal>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -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<SettingsSection>(route.query.section === 'account' ? 'account' : 'runtime')
|
||||
const loading = ref(false)
|
||||
const testingProbe = ref('')
|
||||
const probeResults = ref<IntegrationProbeResultVO[]>([])
|
||||
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<string, string>)[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) {
|
||||
|
||||
Reference in New Issue
Block a user