diff --git a/.env.example b/.env.example index 79dc364..0317288 100644 --- a/.env.example +++ b/.env.example @@ -10,3 +10,10 @@ SHOPLIX_OSS_REGION=us-east-1 SHOPLIX_OSS_ACCESS_KEY= SHOPLIX_OSS_SECRET_KEY= SHOPLIX_OSS_PATH_STYLE_ACCESS=true + +# Google Search Console OAuth。线上回调地址需同时加入 Google Cloud OAuth 客户端的授权重定向 URI。 +SHOPLIX_GSC_CLIENT_ID= +SHOPLIX_GSC_CLIENT_SECRET= +SHOPLIX_GSC_CALLBACK_URL=https://admin.steliro.com/api/admin/v1/gsc/oauth/callback +# 生产环境必须使用独立高强度随机密钥;修改后已有授权令牌将无法解密。 +SHOPLIX_GSC_TOKEN_KEY= diff --git a/admin/src/main/java/com/shoplix/admin/config/AdminSecurityConfig.java b/admin/src/main/java/com/shoplix/admin/config/AdminSecurityConfig.java index f04de1d..afb64e8 100644 --- a/admin/src/main/java/com/shoplix/admin/config/AdminSecurityConfig.java +++ b/admin/src/main/java/com/shoplix/admin/config/AdminSecurityConfig.java @@ -46,7 +46,7 @@ public class AdminSecurityConfig { public SecurityFilterChain securityFilterChain(HttpSecurity http, ObjectMapper mapper) throws Exception { return http.csrf(csrf -> csrf.disable()) .authorizeHttpRequests(auth -> auth - .requestMatchers("/api/admin/v1/auth/login", "/uploads/**").permitAll() + .requestMatchers("/api/admin/v1/auth/login", "/api/admin/v1/gsc/oauth/callback", "/uploads/**").permitAll() .requestMatchers("/api/admin/**").authenticated().anyRequest().permitAll()) .exceptionHandling(errors -> errors.authenticationEntryPoint((request, response, exception) -> { response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); diff --git a/admin/src/main/java/com/shoplix/admin/controller/AdminGscController.java b/admin/src/main/java/com/shoplix/admin/controller/AdminGscController.java new file mode 100644 index 0000000..33062c4 --- /dev/null +++ b/admin/src/main/java/com/shoplix/admin/controller/AdminGscController.java @@ -0,0 +1,55 @@ +package com.shoplix.admin.controller; + +import com.shoplix.admin.modules.common.res.CommonAdminRes; +import com.shoplix.admin.modules.gsc.req.*; +import com.shoplix.admin.modules.gsc.res.*; +import com.shoplix.admin.service.AdminGscService; +import jakarta.validation.Valid; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.ModelAttribute; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.servlet.view.RedirectView; + +/** 运营后台Google Search Console接口。 */ +@RestController +@RequestMapping("/api/admin/v1/gsc") +public class AdminGscController { + private final AdminGscService service; + + /** 注入Google Search Console业务。 */ + public AdminGscController(AdminGscService service) { this.service = service; } + + /** 查询当前站点GSC连接状态。 */ + @PostMapping("/connection") + public GscConnectionAdminRes connection(@Valid @RequestBody GscSiteAdminReq request) { + return service.connection(request.siteCode()); + } + + /** 创建Google OAuth授权地址。 */ + @PostMapping("/authorization") + public GscAuthorizationAdminRes authorization(@Valid @RequestBody GscAuthorizationAdminReq request) { + return service.authorization(request); + } + + /** 接收Google OAuth授权回调。 */ + @GetMapping("/oauth/callback") + public RedirectView callback(@Valid @ModelAttribute GscOauthCallbackAdminReq request) { + return new RedirectView(service.callback(request)); + } + + /** 解除当前站点GSC授权。 */ + @PostMapping("/disconnect") + public CommonAdminRes disconnect(@Valid @RequestBody GscSiteAdminReq request) { + service.disconnect(request.siteCode()); + return CommonAdminRes.success(); + } + + /** 查询关键词、页面与收录效果。 */ + @PostMapping("/statistics") + public GscStatisticsAdminRes statistics(@Valid @RequestBody GscStatisticsAdminReq request) { + return service.statistics(request); + } +} diff --git a/admin/src/main/java/com/shoplix/admin/modules/gsc/req/GscAuthorizationAdminReq.java b/admin/src/main/java/com/shoplix/admin/modules/gsc/req/GscAuthorizationAdminReq.java new file mode 100644 index 0000000..9727a3f --- /dev/null +++ b/admin/src/main/java/com/shoplix/admin/modules/gsc/req/GscAuthorizationAdminReq.java @@ -0,0 +1,12 @@ +package com.shoplix.admin.modules.gsc.req; + +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.Pattern; +import jakarta.validation.constraints.Size; + +/** 创建GSC授权地址请求。 */ +public record GscAuthorizationAdminReq( + /** 站点业务编号。 */ @NotBlank @Size(max = 16) String siteCode, + /** 授权结束后的管理后台绝对地址。 */ @NotBlank @Size(max = 500) + @Pattern(regexp = "^https?://.+") String returnUrl) { +} diff --git a/admin/src/main/java/com/shoplix/admin/modules/gsc/req/GscOauthCallbackAdminReq.java b/admin/src/main/java/com/shoplix/admin/modules/gsc/req/GscOauthCallbackAdminReq.java new file mode 100644 index 0000000..9117c32 --- /dev/null +++ b/admin/src/main/java/com/shoplix/admin/modules/gsc/req/GscOauthCallbackAdminReq.java @@ -0,0 +1,10 @@ +package com.shoplix.admin.modules.gsc.req; + +import jakarta.validation.constraints.Size; + +/** Google OAuth回调查询参数。 */ +public record GscOauthCallbackAdminReq( + /** Google授权码。 */ @Size(max = 1000) String code, + /** OAuth防重放状态码。 */ @Size(max = 64) String state, + /** Google返回的授权错误。 */ @Size(max = 200) String error) { +} diff --git a/admin/src/main/java/com/shoplix/admin/modules/gsc/req/GscSiteAdminReq.java b/admin/src/main/java/com/shoplix/admin/modules/gsc/req/GscSiteAdminReq.java new file mode 100644 index 0000000..3c6236f --- /dev/null +++ b/admin/src/main/java/com/shoplix/admin/modules/gsc/req/GscSiteAdminReq.java @@ -0,0 +1,9 @@ +package com.shoplix.admin.modules.gsc.req; + +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.Size; + +/** GSC站点级请求。 */ +public record GscSiteAdminReq( + /** 站点业务编号。 */ @NotBlank @Size(max = 16) String siteCode) { +} diff --git a/admin/src/main/java/com/shoplix/admin/modules/gsc/req/GscStatisticsAdminReq.java b/admin/src/main/java/com/shoplix/admin/modules/gsc/req/GscStatisticsAdminReq.java new file mode 100644 index 0000000..dc85e90 --- /dev/null +++ b/admin/src/main/java/com/shoplix/admin/modules/gsc/req/GscStatisticsAdminReq.java @@ -0,0 +1,13 @@ +package com.shoplix.admin.modules.gsc.req; + +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Size; +import java.time.LocalDate; + +/** 查询GSC统计数据请求。 */ +public record GscStatisticsAdminReq( + /** 站点业务编号。 */ @NotBlank @Size(max = 16) String siteCode, + /** 统计开始日期。 */ @NotNull LocalDate startDate, + /** 统计结束日期。 */ @NotNull LocalDate endDate) { +} diff --git a/admin/src/main/java/com/shoplix/admin/modules/gsc/res/GscAuthorizationAdminRes.java b/admin/src/main/java/com/shoplix/admin/modules/gsc/res/GscAuthorizationAdminRes.java new file mode 100644 index 0000000..348940e --- /dev/null +++ b/admin/src/main/java/com/shoplix/admin/modules/gsc/res/GscAuthorizationAdminRes.java @@ -0,0 +1,6 @@ +package com.shoplix.admin.modules.gsc.res; + +/** GSC授权地址响应。 */ +public record GscAuthorizationAdminRes( + /** Google OAuth授权地址。 */ String authorizationUrl) { +} diff --git a/admin/src/main/java/com/shoplix/admin/modules/gsc/res/GscConnectionAdminRes.java b/admin/src/main/java/com/shoplix/admin/modules/gsc/res/GscConnectionAdminRes.java new file mode 100644 index 0000000..3385d9f --- /dev/null +++ b/admin/src/main/java/com/shoplix/admin/modules/gsc/res/GscConnectionAdminRes.java @@ -0,0 +1,16 @@ +package com.shoplix.admin.modules.gsc.res; + +import com.shoplix.modules.gsc.enums.GscConnectionOperationEnum; +import java.util.List; + +/** GSC授权连接状态响应。 */ +public record GscConnectionAdminRes( + /** Google OAuth是否已配置。 */ boolean oauthConfigured, + /** 当前站点是否已连接。 */ boolean connected, + /** 授权Google账户邮箱。 */ String accountEmail, + /** 已匹配的Search Console站点资源。 */ String propertyUri, + /** 连接状态枚举值。 */ String status, + /** 连接状态文案。 */ String statusLabel, + /** 当前连接状态允许操作。 */ List operations, + /** 最后更新时间毫秒时间戳。 */ Long updateTime) { +} diff --git a/admin/src/main/java/com/shoplix/admin/modules/gsc/res/GscKeywordAdminRes.java b/admin/src/main/java/com/shoplix/admin/modules/gsc/res/GscKeywordAdminRes.java new file mode 100644 index 0000000..7105ac1 --- /dev/null +++ b/admin/src/main/java/com/shoplix/admin/modules/gsc/res/GscKeywordAdminRes.java @@ -0,0 +1,10 @@ +package com.shoplix.admin.modules.gsc.res; + +/** GSC关键词效果行。 */ +public record GscKeywordAdminRes( + /** 搜索关键词。 */ String keyword, + /** 点击次数。 */ double clicks, + /** 曝光次数。 */ double impressions, + /** 点击率,取值0至1。 */ double ctr, + /** 平均搜索排名。 */ double position) { +} diff --git a/admin/src/main/java/com/shoplix/admin/modules/gsc/res/GscMetricAdminRes.java b/admin/src/main/java/com/shoplix/admin/modules/gsc/res/GscMetricAdminRes.java new file mode 100644 index 0000000..36353ab --- /dev/null +++ b/admin/src/main/java/com/shoplix/admin/modules/gsc/res/GscMetricAdminRes.java @@ -0,0 +1,9 @@ +package com.shoplix.admin.modules.gsc.res; + +/** GSC核心效果指标。 */ +public record GscMetricAdminRes( + /** 总点击次数。 */ double clicks, + /** 总曝光次数。 */ double impressions, + /** 平均点击率,取值0至1。 */ double ctr, + /** 平均搜索排名。 */ double position) { +} diff --git a/admin/src/main/java/com/shoplix/admin/modules/gsc/res/GscPageAdminRes.java b/admin/src/main/java/com/shoplix/admin/modules/gsc/res/GscPageAdminRes.java new file mode 100644 index 0000000..20fbd2e --- /dev/null +++ b/admin/src/main/java/com/shoplix/admin/modules/gsc/res/GscPageAdminRes.java @@ -0,0 +1,10 @@ +package com.shoplix.admin.modules.gsc.res; + +/** GSC页面效果行。 */ +public record GscPageAdminRes( + /** 收录页面地址。 */ String page, + /** 点击次数。 */ double clicks, + /** 曝光次数。 */ double impressions, + /** 点击率,取值0至1。 */ double ctr, + /** 平均搜索排名。 */ double position) { +} diff --git a/admin/src/main/java/com/shoplix/admin/modules/gsc/res/GscStatisticsAdminRes.java b/admin/src/main/java/com/shoplix/admin/modules/gsc/res/GscStatisticsAdminRes.java new file mode 100644 index 0000000..579f4c3 --- /dev/null +++ b/admin/src/main/java/com/shoplix/admin/modules/gsc/res/GscStatisticsAdminRes.java @@ -0,0 +1,14 @@ +package com.shoplix.admin.modules.gsc.res; + +import java.util.List; + +/** GSC站点收录及搜索效果统计响应。 */ +public record GscStatisticsAdminRes( + /** 站点地图已提交URL数量。 */ long submittedUrls, + /** 站点地图已索引URL数量。 */ long indexedUrls, + /** 产生曝光的关键词数量。 */ int keywordCount, + /** 核心搜索效果指标。 */ GscMetricAdminRes metric, + /** 每日效果趋势。 */ List trends, + /** 关键词效果明细。 */ List keywords, + /** 页面效果明细。 */ List pages) { +} diff --git a/admin/src/main/java/com/shoplix/admin/modules/gsc/res/GscTrendAdminRes.java b/admin/src/main/java/com/shoplix/admin/modules/gsc/res/GscTrendAdminRes.java new file mode 100644 index 0000000..099b591 --- /dev/null +++ b/admin/src/main/java/com/shoplix/admin/modules/gsc/res/GscTrendAdminRes.java @@ -0,0 +1,12 @@ +package com.shoplix.admin.modules.gsc.res; + +import java.time.LocalDate; + +/** GSC每日效果趋势。 */ +public record GscTrendAdminRes( + /** 统计日期。 */ LocalDate date, + /** 点击次数。 */ double clicks, + /** 曝光次数。 */ double impressions, + /** 点击率,取值0至1。 */ double ctr, + /** 平均搜索排名。 */ double position) { +} diff --git a/admin/src/main/java/com/shoplix/admin/service/AdminGscService.java b/admin/src/main/java/com/shoplix/admin/service/AdminGscService.java new file mode 100644 index 0000000..07e5ee6 --- /dev/null +++ b/admin/src/main/java/com/shoplix/admin/service/AdminGscService.java @@ -0,0 +1,233 @@ +package com.shoplix.admin.service; + +import com.shoplix.admin.modules.gsc.req.GscAuthorizationAdminReq; +import com.shoplix.admin.modules.gsc.req.GscOauthCallbackAdminReq; +import com.shoplix.admin.modules.gsc.req.GscStatisticsAdminReq; +import com.shoplix.admin.modules.gsc.res.*; +import com.shoplix.admin.third.gsc.*; +import com.shoplix.common.code.enums.BusinessCodePrefixEnum; +import com.shoplix.common.exception.BusinessException; +import com.shoplix.common.utils.BusinessCodeUtils; +import com.shoplix.modules.gsc.repository.entity.GscConnectionEntity; +import com.shoplix.modules.gsc.enums.GscConnectionStatusEnum; +import com.shoplix.modules.gsc.enums.GscOauthStateStatusEnum; +import com.shoplix.modules.gsc.repository.entity.GscOauthStateEntity; +import com.shoplix.modules.gsc.repository.service.GscConnectionRepositoryService; +import com.shoplix.modules.gsc.repository.service.GscOauthStateRepositoryService; +import com.shoplix.modules.site.repository.service.SiteDomainRepositoryService; +import java.net.URI; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.security.SecureRandom; +import java.time.LocalDate; +import java.time.temporal.ChronoUnit; +import java.util.Base64; +import java.util.Comparator; +import java.util.List; +import java.util.Locale; +import org.springframework.context.MessageSource; +import org.springframework.context.i18n.LocaleContextHolder; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +/** Google Search Console授权与统计业务。 */ +@Service +public class AdminGscService { + private final GscConnectionRepositoryService connectionRepository; + private final GscOauthStateRepositoryService stateRepository; + private final SiteDomainRepositoryService domainRepository; + private final GscClient client; + private final GscProperties properties; + private final GscTokenCipher tokenCipher; + private final BusinessCodeUtils codeUtils; + private final MessageSource messageSource; + + /** 注入GSC业务依赖。 */ + public AdminGscService(GscConnectionRepositoryService connectionRepository, + GscOauthStateRepositoryService stateRepository, + SiteDomainRepositoryService domainRepository, GscClient client, + GscProperties properties, GscTokenCipher tokenCipher, + BusinessCodeUtils codeUtils, MessageSource messageSource) { + this.connectionRepository = connectionRepository; + this.stateRepository = stateRepository; + this.domainRepository = domainRepository; + this.client = client; + this.properties = properties; + this.tokenCipher = tokenCipher; + this.codeUtils = codeUtils; + this.messageSource = messageSource; + } + + /** 查询当前站点GSC连接状态。 */ + public GscConnectionAdminRes connection(String siteCode) { + return connectionRepository.findBySiteCode(siteCode) + .map(item -> { + GscConnectionStatusEnum status = GscConnectionStatusEnum.valueOf(item.getStatus()); + return new GscConnectionAdminRes(properties.configured(), status == GscConnectionStatusEnum.CONNECTED, + item.getAccountEmail(), item.getPropertyUri(), status.name(), status.getLabel(), status.getOperations(), item.getUpdateTime()); + }) + .orElseGet(() -> new GscConnectionAdminRes(properties.configured(), false, null, null, + GscConnectionStatusEnum.DISCONNECTED.name(), GscConnectionStatusEnum.DISCONNECTED.getLabel(), + GscConnectionStatusEnum.DISCONNECTED.getOperations(), null)); + } + + /** 创建一次性Google OAuth授权地址。 */ + @Transactional + public GscAuthorizationAdminRes authorization(GscAuthorizationAdminReq request) { + requireConfigured(); + validateReturnUrl(request.returnUrl()); + domainRepository.findPrimaryBySiteCode(request.siteCode()) + .orElseThrow(() -> exception("GSC_DOMAIN_REQUIRED", "gsc.domain.required")); + String stateCode = randomState(); + long now = System.currentTimeMillis(); + GscOauthStateEntity state = new GscOauthStateEntity(); + state.setStateCode(stateCode); + state.setSiteCode(request.siteCode()); + state.setRedirectUri(request.returnUrl()); + state.setExpireTime(now + 10 * 60 * 1000L); + state.setUsed(GscOauthStateStatusEnum.UNUSED.getValue()); + state.setCreateTime(now); + if (stateRepository.insert(state) != 1) throw exception("GSC_STATE_SAVE_FAILED", "gsc.state.save.failed"); + return new GscAuthorizationAdminRes(client.authorizationUrl(stateCode)); + } + + /** 处理Google OAuth回调并返回管理后台跳转地址。 */ + @Transactional + public String callback(GscOauthCallbackAdminReq request) { + if (request.state() == null || request.state().isBlank()) return "/?gscAuth=failed"; + GscOauthStateEntity state = stateRepository.findUsable(request.state(), System.currentTimeMillis()).orElse(null); + if (state == null || stateRepository.markUsed(request.state()) != 1) return "/?gscAuth=expired"; + if (request.error() != null || request.code() == null || request.code().isBlank()) { + return appendResult(state.getRedirectUri(), "denied"); + } + try { + GscTokenResponse token = client.exchangeCode(request.code()); + if (token.refreshToken() == null || token.refreshToken().isBlank()) { + throw exception("GSC_REFRESH_TOKEN_REQUIRED", "gsc.refresh-token.required"); + } + String domain = domainRepository.findPrimaryBySiteCode(state.getSiteCode()) + .orElseThrow(() -> exception("GSC_DOMAIN_REQUIRED", "gsc.domain.required")).getDomain(); + String propertyUri = matchProperty(domain, client.properties(token.accessToken())); + saveConnection(state.getSiteCode(), propertyUri, client.accountEmail(token.accessToken()), token.refreshToken()); + return appendResult(state.getRedirectUri(), "success"); + } catch (BusinessException exception) { + return appendResult(state.getRedirectUri(), "failed"); + } + } + + /** 解除当前站点Google Search Console授权。 */ + @Transactional + public void disconnect(String siteCode) { + GscConnectionEntity entity = connected(siteCode); + client.revoke(tokenCipher.decrypt(entity.getRefreshTokenCiphertext())); + entity.setStatus(GscConnectionStatusEnum.DISCONNECTED.name()); + entity.setRefreshTokenCiphertext(""); + entity.setUpdateTime(System.currentTimeMillis()); + if (connectionRepository.update(entity) != 1) throw exception("GSC_DISCONNECT_FAILED", "gsc.disconnect.failed"); + } + + /** 查询当前站点关键词、页面与收录效果。 */ + public GscStatisticsAdminRes statistics(GscStatisticsAdminReq request) { + validateDateRange(request.startDate(), request.endDate()); + GscConnectionEntity connection = connected(request.siteCode()); + String accessToken = client.refreshAccessToken(tokenCipher.decrypt(connection.getRefreshTokenCiphertext())); + var metricRows = client.analytics(accessToken, connection.getPropertyUri(), request.startDate(), request.endDate(), List.of(), 1); + var metric = metricRows.isEmpty() ? new GscMetricAdminRes(0, 0, 0, 0) : toMetric(metricRows.getFirst()); + var trends = client.analytics(accessToken, connection.getPropertyUri(), request.startDate(), request.endDate(), List.of("date"), 500) + .stream().map(row -> new GscTrendAdminRes(LocalDate.parse(row.keys().getFirst()), row.clicks(), row.impressions(), row.ctr(), row.position())) + .sorted(Comparator.comparing(GscTrendAdminRes::date)).toList(); + var keywords = client.analytics(accessToken, connection.getPropertyUri(), request.startDate(), request.endDate(), List.of("query"), 1000) + .stream().map(row -> new GscKeywordAdminRes(row.keys().getFirst(), row.clicks(), row.impressions(), row.ctr(), row.position())).toList(); + var pages = client.analytics(accessToken, connection.getPropertyUri(), request.startDate(), request.endDate(), List.of("page"), 500) + .stream().map(row -> new GscPageAdminRes(row.keys().getFirst(), row.clicks(), row.impressions(), row.ctr(), row.position())).toList(); + long[] coverage = client.sitemapCoverage(accessToken, connection.getPropertyUri()); + return new GscStatisticsAdminRes(coverage[0], coverage[1], keywords.size(), metric, trends, keywords, pages); + } + + /** 保存或覆盖站点GSC连接。 */ + private void saveConnection(String siteCode, String propertyUri, String email, String refreshToken) { + long now = System.currentTimeMillis(); + GscConnectionEntity entity = connectionRepository.findBySiteCode(siteCode).orElseGet(() -> { + GscConnectionEntity created = new GscConnectionEntity(); + created.setConnectionCode(codeUtils.generate(BusinessCodePrefixEnum.GSC_CONNECTION)); + created.setSiteCode(siteCode); + created.setCreateTime(now); + return created; + }); + entity.setPropertyUri(propertyUri); + entity.setAccountEmail(email); + entity.setRefreshTokenCiphertext(tokenCipher.encrypt(refreshToken)); + entity.setStatus(GscConnectionStatusEnum.CONNECTED.name()); + entity.setUpdateTime(now); + int affected = entity.getId() == null ? connectionRepository.insert(entity) : connectionRepository.update(entity); + if (affected != 1) throw exception("GSC_CONNECTION_SAVE_FAILED", "gsc.connection.save.failed"); + } + + /** 匹配店铺域名对应的GSC资源。 */ + private String matchProperty(String domain, List properties) { + String normalized = domain.toLowerCase(Locale.ROOT).replaceFirst("^www\\.", ""); + return properties.stream().map(GscProperty::siteUrl) + .filter(value -> propertyDomain(value).equals(normalized)).findFirst() + .orElseThrow(() -> exception("GSC_PROPERTY_NOT_FOUND", "gsc.property.not-found")); + } + + /** 从域名属性或URL前缀属性提取主机名。 */ + private String propertyDomain(String propertyUri) { + try { + if (propertyUri.startsWith("sc-domain:")) return propertyUri.substring(10).replaceFirst("^www\\.", "").toLowerCase(Locale.ROOT); + return URI.create(propertyUri).getHost().replaceFirst("^www\\.", "").toLowerCase(Locale.ROOT); + } catch (Exception exception) { return ""; } + } + + /** 查询有效连接。 */ + private GscConnectionEntity connected(String siteCode) { + return connectionRepository.findBySiteCode(siteCode).filter(item -> GscConnectionStatusEnum.CONNECTED.name().equals(item.getStatus())) + .orElseThrow(() -> exception("GSC_NOT_CONNECTED", "gsc.not-connected")); + } + + /** 校验统计日期范围。 */ + private void validateDateRange(LocalDate startDate, LocalDate endDate) { + if (endDate.isBefore(startDate) || ChronoUnit.DAYS.between(startDate, endDate) > 365) { + throw exception("GSC_DATE_RANGE_INVALID", "gsc.date-range.invalid"); + } + } + + /** 转换核心效果指标。 */ + private GscMetricAdminRes toMetric(GscAnalyticsRow row) { + return new GscMetricAdminRes(row.clicks(), row.impressions(), row.ctr(), row.position()); + } + + /** 确认Google OAuth客户端已配置。 */ + private void requireConfigured() { + if (!properties.configured()) throw exception("GSC_OAUTH_NOT_CONFIGURED", "gsc.oauth.not-configured"); + } + + /** 限制OAuth完成后的回跳地址必须与后台回调使用同一主机。 */ + private void validateReturnUrl(String returnUrl) { + try { + String returnHost = URI.create(returnUrl).getHost(); + String callbackHost = URI.create(properties.getCallbackUrl()).getHost(); + if (returnHost == null || !returnHost.equalsIgnoreCase(callbackHost)) { + throw exception("GSC_RETURN_URL_INVALID", "gsc.return-url.invalid"); + } + } catch (BusinessException exception) { throw exception; } + catch (Exception exception) { throw exception("GSC_RETURN_URL_INVALID", "gsc.return-url.invalid"); } + } + + /** 生成不可预测的一次性OAuth状态码。 */ + private String randomState() { + byte[] bytes = new byte[32]; + new SecureRandom().nextBytes(bytes); + return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes); + } + + /** 为回跳地址追加授权结果。 */ + private String appendResult(String url, String result) { + return url + (url.contains("?") ? "&" : "?") + "gscAuth=" + URLEncoder.encode(result, StandardCharsets.UTF_8); + } + + /** 创建多语言业务异常。 */ + private BusinessException exception(String code, String messageKey) { + return new BusinessException(code, messageSource.getMessage(messageKey, null, LocaleContextHolder.getLocale())); + } +} diff --git a/admin/src/main/java/com/shoplix/admin/third/gsc/GscAnalyticsRow.java b/admin/src/main/java/com/shoplix/admin/third/gsc/GscAnalyticsRow.java new file mode 100644 index 0000000..5f311a9 --- /dev/null +++ b/admin/src/main/java/com/shoplix/admin/third/gsc/GscAnalyticsRow.java @@ -0,0 +1,7 @@ +package com.shoplix.admin.third.gsc; + +import java.util.List; + +/** Google Search Analytics单行统计。 */ +public record GscAnalyticsRow(List keys, double clicks, double impressions, double ctr, double position) { +} diff --git a/admin/src/main/java/com/shoplix/admin/third/gsc/GscClient.java b/admin/src/main/java/com/shoplix/admin/third/gsc/GscClient.java new file mode 100644 index 0000000..1402713 --- /dev/null +++ b/admin/src/main/java/com/shoplix/admin/third/gsc/GscClient.java @@ -0,0 +1,147 @@ +package com.shoplix.admin.third.gsc; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.shoplix.common.exception.BusinessException; +import java.net.URI; +import java.net.URLEncoder; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import org.springframework.stereotype.Component; +import org.springframework.context.MessageSource; +import org.springframework.context.i18n.LocaleContextHolder; + +/** Google OAuth与Search Console外部接口客户端。 */ +@Component +public class GscClient { + private static final String SCOPE = "https://www.googleapis.com/auth/webmasters.readonly https://www.googleapis.com/auth/userinfo.email"; + private final GscProperties properties; + private final ObjectMapper objectMapper; + private final MessageSource messageSource; + private final HttpClient httpClient = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(15)).build(); + + /** 注入GSC配置与JSON解析器。 */ + public GscClient(GscProperties properties, ObjectMapper objectMapper, MessageSource messageSource) { + this.properties = properties; + this.objectMapper = objectMapper; + this.messageSource = messageSource; + } + + /** 生成Google OAuth授权地址。 */ + public String authorizationUrl(String state) { + return "https://accounts.google.com/o/oauth2/v2/auth?client_id=" + encode(properties.getClientId()) + + "&redirect_uri=" + encode(properties.getCallbackUrl()) + "&response_type=code&scope=" + encode(SCOPE) + + "&access_type=offline&prompt=consent&include_granted_scopes=true&state=" + encode(state); + } + + /** 使用授权码交换访问及刷新令牌。 */ + public GscTokenResponse exchangeCode(String code) { + String body = form(Map.of("code", code, "client_id", properties.getClientId(), + "client_secret", properties.getClientSecret(), "redirect_uri", properties.getCallbackUrl(), + "grant_type", "authorization_code")); + JsonNode json = send(HttpRequest.newBuilder(URI.create("https://oauth2.googleapis.com/token")) + .header("Content-Type", "application/x-www-form-urlencoded").POST(HttpRequest.BodyPublishers.ofString(body)).build()); + return new GscTokenResponse(json.path("access_token").asText(), json.path("refresh_token").asText(), json.path("expires_in").asLong()); + } + + /** 使用刷新令牌取得短期访问令牌。 */ + public String refreshAccessToken(String refreshToken) { + String body = form(Map.of("refresh_token", refreshToken, "client_id", properties.getClientId(), + "client_secret", properties.getClientSecret(), "grant_type", "refresh_token")); + return send(HttpRequest.newBuilder(URI.create("https://oauth2.googleapis.com/token")) + .header("Content-Type", "application/x-www-form-urlencoded").POST(HttpRequest.BodyPublishers.ofString(body)).build()) + .path("access_token").asText(); + } + + /** 查询授权Google账户邮箱。 */ + public String accountEmail(String accessToken) { + return get("https://www.googleapis.com/oauth2/v2/userinfo", accessToken).path("email").asText(); + } + + /** 查询账户可访问的Search Console站点资源。 */ + public List properties(String accessToken) { + List result = new ArrayList<>(); + for (JsonNode item : get("https://www.googleapis.com/webmasters/v3/sites", accessToken).path("siteEntry")) { + result.add(new GscProperty(item.path("siteUrl").asText(), item.path("permissionLevel").asText())); + } + return result; + } + + /** 查询Search Analytics统计行。 */ + public List analytics(String accessToken, String propertyUri, LocalDate startDate, + LocalDate endDate, List dimensions, int rowLimit) { + try { + String body = objectMapper.writeValueAsString(Map.of("startDate", startDate.toString(), "endDate", endDate.toString(), + "dimensions", dimensions, "rowLimit", rowLimit, "dataState", "all")); + JsonNode json = send(HttpRequest.newBuilder(URI.create("https://www.googleapis.com/webmasters/v3/sites/" + + encode(propertyUri) + "/searchAnalytics/query")) + .header("Authorization", "Bearer " + accessToken).header("Content-Type", "application/json") + .POST(HttpRequest.BodyPublishers.ofString(body)).build()); + List result = new ArrayList<>(); + for (JsonNode row : json.path("rows")) { + List keys = new ArrayList<>(); + row.path("keys").forEach(key -> keys.add(key.asText())); + result.add(new GscAnalyticsRow(keys, row.path("clicks").asDouble(), row.path("impressions").asDouble(), + row.path("ctr").asDouble(), row.path("position").asDouble())); + } + return result; + } catch (BusinessException exception) { throw exception; } + catch (Exception exception) { throw externalError(exception); } + } + + /** 统计站点地图已发现与已索引URL数量。 */ + public long[] sitemapCoverage(String accessToken, String propertyUri) { + JsonNode json = get("https://www.googleapis.com/webmasters/v3/sites/" + encode(propertyUri) + "/sitemaps", accessToken); + long submitted = 0L; + long indexed = 0L; + for (JsonNode sitemap : json.path("sitemap")) { + for (JsonNode content : sitemap.path("contents")) { + submitted += content.path("submitted").asLong(); + indexed += content.path("indexed").asLong(); + } + } + return new long[]{submitted, indexed}; + } + + /** 撤销Google刷新令牌。 */ + public void revoke(String refreshToken) { + send(HttpRequest.newBuilder(URI.create("https://oauth2.googleapis.com/revoke?token=" + encode(refreshToken))) + .header("Content-Type", "application/x-www-form-urlencoded").POST(HttpRequest.BodyPublishers.noBody()).build()); + } + + /** 发送Bearer GET请求。 */ + private JsonNode get(String url, String accessToken) { + return send(HttpRequest.newBuilder(URI.create(url)).header("Authorization", "Bearer " + accessToken).GET().build()); + } + + /** 发送外部请求并统一检查响应。 */ + private JsonNode send(HttpRequest request) { + try { + HttpResponse response = httpClient.send(request, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8)); + if (response.statusCode() < 200 || response.statusCode() >= 300) { + throw externalError(null); + } + return response.body().isBlank() ? objectMapper.createObjectNode() : objectMapper.readTree(response.body()); + } catch (BusinessException exception) { throw exception; } + catch (Exception exception) { throw externalError(exception); } + } + + /** 创建统一外部接口异常。 */ + private BusinessException externalError(Exception exception) { + return new BusinessException("GSC_EXTERNAL_REQUEST_FAILED", + messageSource.getMessage("gsc.external.request.failed", null, LocaleContextHolder.getLocale())); + } + + /** URL编码文本。 */ private String encode(String value) { return URLEncoder.encode(value, StandardCharsets.UTF_8); } + /** 构建表单请求体。 */ private String form(Map values) { + return values.entrySet().stream().map(item -> encode(item.getKey()) + "=" + encode(item.getValue())) + .collect(java.util.stream.Collectors.joining("&")); + } +} diff --git a/admin/src/main/java/com/shoplix/admin/third/gsc/GscProperties.java b/admin/src/main/java/com/shoplix/admin/third/gsc/GscProperties.java new file mode 100644 index 0000000..46879e4 --- /dev/null +++ b/admin/src/main/java/com/shoplix/admin/third/gsc/GscProperties.java @@ -0,0 +1,30 @@ +package com.shoplix.admin.third.gsc; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +/** Google Search Console外部接口配置。 */ +@Component +public class GscProperties { + /** Google OAuth客户端编号。 */ private final String clientId; + /** Google OAuth客户端密钥。 */ private final String clientSecret; + /** Google OAuth回调地址。 */ private final String callbackUrl; + /** OAuth令牌本地加密密钥。 */ private final String tokenKey; + + /** 注入Google Search Console配置。 */ + public GscProperties(@Value("${shoplix.gsc.client-id:}") String clientId, + @Value("${shoplix.gsc.client-secret:}") String clientSecret, + @Value("${shoplix.gsc.callback-url:http://localhost:8081/api/admin/v1/gsc/oauth/callback}") String callbackUrl, + @Value("${shoplix.gsc.token-key:shoplix-local-gsc-token-key-change-in-production}") String tokenKey) { + this.clientId = clientId; + this.clientSecret = clientSecret; + this.callbackUrl = callbackUrl; + this.tokenKey = tokenKey; + } + + /** 获取OAuth客户端编号。 */ public String getClientId() { return clientId; } + /** 获取OAuth客户端密钥。 */ public String getClientSecret() { return clientSecret; } + /** 获取OAuth回调地址。 */ public String getCallbackUrl() { return callbackUrl; } + /** 获取令牌加密密钥。 */ public String getTokenKey() { return tokenKey; } + /** 判断Google OAuth是否完成配置。 */ public boolean configured() { return !clientId.isBlank() && !clientSecret.isBlank(); } +} diff --git a/admin/src/main/java/com/shoplix/admin/third/gsc/GscProperty.java b/admin/src/main/java/com/shoplix/admin/third/gsc/GscProperty.java new file mode 100644 index 0000000..1e3ff53 --- /dev/null +++ b/admin/src/main/java/com/shoplix/admin/third/gsc/GscProperty.java @@ -0,0 +1,5 @@ +package com.shoplix.admin.third.gsc; + +/** Google Search Console站点资源。 */ +public record GscProperty(String siteUrl, String permissionLevel) { +} diff --git a/admin/src/main/java/com/shoplix/admin/third/gsc/GscTokenCipher.java b/admin/src/main/java/com/shoplix/admin/third/gsc/GscTokenCipher.java new file mode 100644 index 0000000..dfa2905 --- /dev/null +++ b/admin/src/main/java/com/shoplix/admin/third/gsc/GscTokenCipher.java @@ -0,0 +1,69 @@ +package com.shoplix.admin.third.gsc; + +import com.shoplix.common.exception.BusinessException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.SecureRandom; +import java.util.Base64; +import javax.crypto.Cipher; +import javax.crypto.spec.GCMParameterSpec; +import javax.crypto.spec.SecretKeySpec; +import org.springframework.context.MessageSource; +import org.springframework.context.i18n.LocaleContextHolder; +import org.springframework.stereotype.Component; + +/** 使用AES-GCM保护持久化OAuth令牌。 */ +@Component +public class GscTokenCipher { + private static final int IV_LENGTH = 12; + private final SecretKeySpec key; + private final MessageSource messageSource; + + /** 根据配置密钥初始化令牌加密器。 */ + public GscTokenCipher(GscProperties properties, MessageSource messageSource) { + this.messageSource = messageSource; + try { + byte[] digest = MessageDigest.getInstance("SHA-256") + .digest(properties.getTokenKey().getBytes(StandardCharsets.UTF_8)); + this.key = new SecretKeySpec(digest, "AES"); + } catch (Exception exception) { + throw new IllegalStateException("Unable to initialize GSC token cipher", exception); + } + } + + /** 加密OAuth令牌。 */ + public String encrypt(String value) { + try { + byte[] iv = new byte[IV_LENGTH]; + new SecureRandom().nextBytes(iv); + Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); + cipher.init(Cipher.ENCRYPT_MODE, key, new GCMParameterSpec(128, iv)); + byte[] encrypted = cipher.doFinal(value.getBytes(StandardCharsets.UTF_8)); + byte[] output = new byte[iv.length + encrypted.length]; + System.arraycopy(iv, 0, output, 0, iv.length); + System.arraycopy(encrypted, 0, output, iv.length, encrypted.length); + return Base64.getEncoder().encodeToString(output); + } catch (Exception exception) { + throw exception("GSC_TOKEN_ENCRYPT_FAILED", "gsc.token.encrypt.failed"); + } + } + + /** 解密OAuth令牌。 */ + public String decrypt(String value) { + try { + byte[] input = Base64.getDecoder().decode(value); + byte[] iv = java.util.Arrays.copyOfRange(input, 0, IV_LENGTH); + byte[] encrypted = java.util.Arrays.copyOfRange(input, IV_LENGTH, input.length); + Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); + cipher.init(Cipher.DECRYPT_MODE, key, new GCMParameterSpec(128, iv)); + return new String(cipher.doFinal(encrypted), StandardCharsets.UTF_8); + } catch (Exception exception) { + throw exception("GSC_TOKEN_DECRYPT_FAILED", "gsc.token.decrypt.failed"); + } + } + + /** 创建多语言令牌处理异常。 */ + private BusinessException exception(String code, String messageKey) { + return new BusinessException(code, messageSource.getMessage(messageKey, null, LocaleContextHolder.getLocale())); + } +} diff --git a/admin/src/main/java/com/shoplix/admin/third/gsc/GscTokenResponse.java b/admin/src/main/java/com/shoplix/admin/third/gsc/GscTokenResponse.java new file mode 100644 index 0000000..1cd96fe --- /dev/null +++ b/admin/src/main/java/com/shoplix/admin/third/gsc/GscTokenResponse.java @@ -0,0 +1,5 @@ +package com.shoplix.admin.third.gsc; + +/** Google OAuth令牌交换结果。 */ +public record GscTokenResponse(String accessToken, String refreshToken, long expiresIn) { +} diff --git a/admin/src/main/resources/application.yml b/admin/src/main/resources/application.yml index 8060904..bfbaf36 100644 --- a/admin/src/main/resources/application.yml +++ b/admin/src/main/resources/application.yml @@ -45,3 +45,8 @@ shoplix: access-key: ${SHOPLIX_OSS_ACCESS_KEY:shoplix-test} secret-key: ${SHOPLIX_OSS_SECRET_KEY:shoplix-test} path-style-access: ${SHOPLIX_OSS_PATH_STYLE_ACCESS:true} + gsc: + client-id: ${SHOPLIX_GSC_CLIENT_ID:} + client-secret: ${SHOPLIX_GSC_CLIENT_SECRET:} + callback-url: ${SHOPLIX_GSC_CALLBACK_URL:http://localhost:8081/api/admin/v1/gsc/oauth/callback} + token-key: ${SHOPLIX_GSC_TOKEN_KEY:shoplix-local-gsc-token-key-change-in-production} diff --git a/admin/src/main/resources/db/migration/V20__google_search_console.sql b/admin/src/main/resources/db/migration/V20__google_search_console.sql new file mode 100644 index 0000000..dae9caf --- /dev/null +++ b/admin/src/main/resources/db/migration/V20__google_search_console.sql @@ -0,0 +1,27 @@ +CREATE TABLE gsc_connection ( + id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '数据库内部主键', + connection_code CHAR(16) NOT NULL COMMENT 'GSC连接业务编号', + site_code CHAR(16) NOT NULL COMMENT '所属站点业务编号', + property_uri VARCHAR(500) NOT NULL COMMENT 'Google Search Console站点资源地址', + account_email VARCHAR(200) NOT NULL COMMENT '授权Google账户邮箱', + refresh_token_ciphertext TEXT NOT NULL COMMENT '加密后的OAuth刷新令牌', + status VARCHAR(20) NOT NULL COMMENT '连接状态:CONNECTED已连接,DISCONNECTED已解绑,EXPIRED授权失效', + create_time BIGINT NOT NULL COMMENT '创建时间毫秒时间戳', + update_time BIGINT NOT NULL COMMENT '更新时间毫秒时间戳', + PRIMARY KEY (id), + UNIQUE KEY uk_gsc_connection_code (connection_code), + UNIQUE KEY uk_gsc_connection_site (site_code) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='Google Search Console站点授权连接'; + +CREATE TABLE gsc_oauth_state ( + id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '数据库内部主键', + state_code CHAR(64) NOT NULL COMMENT 'OAuth防重放随机状态码', + site_code CHAR(16) NOT NULL COMMENT '发起授权的站点业务编号', + redirect_uri VARCHAR(500) NOT NULL COMMENT '授权完成后的后台跳转地址', + expire_time BIGINT NOT NULL COMMENT '状态码失效时间毫秒时间戳', + used TINYINT NOT NULL DEFAULT 0 COMMENT '使用状态:0未使用,1已使用', + create_time BIGINT NOT NULL COMMENT '创建时间毫秒时间戳', + PRIMARY KEY (id), + UNIQUE KEY uk_gsc_oauth_state_code (state_code), + KEY idx_gsc_oauth_state_expire (expire_time, used) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='Google Search Console OAuth临时状态'; diff --git a/admin/src/main/resources/messages.properties b/admin/src/main/resources/messages.properties index 8e33d26..9e037a6 100644 --- a/admin/src/main/resources/messages.properties +++ b/admin/src/main/resources/messages.properties @@ -20,3 +20,16 @@ crm.tag.save-failed=Failed to save customer tag store.domain.exists=This domain is already bound to another store store.domain.save-failed=Failed to save the store domain store.domain.invalid=Enter a valid domain, for example www.example.com +gsc.domain.required=Configure the store domain before connecting Google Search Console +gsc.state.save.failed=Failed to create the Google authorization state +gsc.refresh-token.required=Google did not return a refresh token; revoke the app authorization and reconnect +gsc.property.not-found=No Search Console property matching the store domain was found in this Google account +gsc.connection.save.failed=Failed to save the Google Search Console connection +gsc.disconnect.failed=Failed to disconnect Google Search Console +gsc.not-connected=This store is not connected to Google Search Console +gsc.date-range.invalid=The date range is invalid; each query supports up to 365 days +gsc.oauth.not-configured=The Google OAuth client is not configured +gsc.return-url.invalid=The Google authorization return URL is invalid +gsc.external.request.failed=Google Search Console is temporarily unavailable; check the authorization and retry +gsc.token.encrypt.failed=Failed to save the Google authorization token +gsc.token.decrypt.failed=Failed to read the Google authorization token; reconnect the account diff --git a/admin/src/main/resources/messages_zh_CN.properties b/admin/src/main/resources/messages_zh_CN.properties index 680d393..9966897 100644 --- a/admin/src/main/resources/messages_zh_CN.properties +++ b/admin/src/main/resources/messages_zh_CN.properties @@ -20,3 +20,16 @@ crm.tag.save-failed=客户标签保存失败 store.domain.exists=该域名已绑定其他店铺 store.domain.save-failed=店铺域名保存失败 store.domain.invalid=请输入有效域名,例如 www.example.com +gsc.domain.required=请先在店铺信息中配置店铺域名 +gsc.state.save.failed=Google授权状态创建失败 +gsc.refresh-token.required=Google未返回刷新令牌,请撤销应用授权后重新连接 +gsc.property.not-found=当前Google账户中未找到与店铺域名匹配的Search Console资源,请先完成域名验证 +gsc.connection.save.failed=Google Search Console连接保存失败 +gsc.disconnect.failed=Google Search Console解绑失败 +gsc.not-connected=当前店铺尚未连接Google Search Console +gsc.date-range.invalid=统计日期范围无效,单次最多查询365天 +gsc.oauth.not-configured=系统尚未配置Google OAuth客户端 +gsc.return-url.invalid=Google授权回跳地址不合法 +gsc.external.request.failed=Google Search Console接口暂时不可用,请检查授权后重试 +gsc.token.encrypt.failed=Google授权令牌保存失败 +gsc.token.decrypt.failed=Google授权令牌读取失败,请重新授权 diff --git a/admin/src/main/resources/messages_zh_TW.properties b/admin/src/main/resources/messages_zh_TW.properties index b1196be..231db80 100644 --- a/admin/src/main/resources/messages_zh_TW.properties +++ b/admin/src/main/resources/messages_zh_TW.properties @@ -20,3 +20,16 @@ crm.tag.save-failed=客戶標籤儲存失敗 store.domain.exists=該網域已綁定其他店鋪 store.domain.save-failed=店鋪網域儲存失敗 store.domain.invalid=請輸入有效網域,例如 www.example.com +gsc.domain.required=請先在店鋪資訊中設定店鋪網域 +gsc.state.save.failed=Google授權狀態建立失敗 +gsc.refresh-token.required=Google未傳回刷新權杖,請撤銷應用程式授權後重新連線 +gsc.property.not-found=目前Google帳戶中找不到與店鋪網域相符的Search Console資源,請先完成網域驗證 +gsc.connection.save.failed=Google Search Console連線儲存失敗 +gsc.disconnect.failed=Google Search Console解除連線失敗 +gsc.not-connected=目前店鋪尚未連線Google Search Console +gsc.date-range.invalid=統計日期範圍無效,單次最多查詢365天 +gsc.oauth.not-configured=系統尚未設定Google OAuth客戶端 +gsc.return-url.invalid=Google授權回跳地址不合法 +gsc.external.request.failed=Google Search Console介面暫時無法使用,請檢查授權後重試 +gsc.token.encrypt.failed=Google授權權杖儲存失敗 +gsc.token.decrypt.failed=Google授權權杖讀取失敗,請重新授權 diff --git a/admin/src/test/java/com/shoplix/admin/third/gsc/GscTokenCipherTest.java b/admin/src/test/java/com/shoplix/admin/third/gsc/GscTokenCipherTest.java new file mode 100644 index 0000000..4c26c08 --- /dev/null +++ b/admin/src/test/java/com/shoplix/admin/third/gsc/GscTokenCipherTest.java @@ -0,0 +1,20 @@ +package com.shoplix.admin.third.gsc; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; + +import org.junit.jupiter.api.Test; +import org.springframework.context.support.StaticMessageSource; + +/** GSC OAuth令牌加密器测试。 */ +class GscTokenCipherTest { + /** 验证令牌加密后不可读且能够完整解密。 */ + @Test + void shouldEncryptAndDecryptToken() { + GscProperties properties = new GscProperties("client", "secret", "http://localhost/callback", "unit-test-token-key"); + GscTokenCipher cipher = new GscTokenCipher(properties, new StaticMessageSource()); + String encrypted = cipher.encrypt("refresh-token-value"); + assertNotEquals("refresh-token-value", encrypted); + assertEquals("refresh-token-value", cipher.decrypt(encrypted)); + } +} diff --git a/service/src/main/java/com/shoplix/common/code/enums/BusinessCodePrefixEnum.java b/service/src/main/java/com/shoplix/common/code/enums/BusinessCodePrefixEnum.java index b00e11d..8f774d4 100644 --- a/service/src/main/java/com/shoplix/common/code/enums/BusinessCodePrefixEnum.java +++ b/service/src/main/java/com/shoplix/common/code/enums/BusinessCodePrefixEnum.java @@ -14,7 +14,7 @@ public enum BusinessCodePrefixEnum { INQUIRY_LOG("ILG"), INQUIRY_RECEIVER("IRC"), MAIL_TASK("MLT"), CUSTOMER("CUS"), CONTACT("CON"), LEAD("LED"), FOLLOW_UP("FLW"), MEDIA("MED"), SEO("SEO"), SEO_HEADING("SEH"), PUBLISH("PUB"), JOB("JOB"), USER("USR"), USER_SITE("UST"), ROLE("ROL"), FLOW_LOG("FLO"), SOCIAL_CHANNEL("SOC"), - CRM_TAG("CTG"), CRM_TAG_RELATION("CTR"); + CRM_TAG("CTG"), CRM_TAG_RELATION("CTR"), GSC_CONNECTION("GSC"); /** 三位业务前缀。 */ private final String prefix; diff --git a/service/src/main/java/com/shoplix/modules/gsc/enums/GscConnectionOperationEnum.java b/service/src/main/java/com/shoplix/modules/gsc/enums/GscConnectionOperationEnum.java new file mode 100644 index 0000000..cd3ffa3 --- /dev/null +++ b/service/src/main/java/com/shoplix/modules/gsc/enums/GscConnectionOperationEnum.java @@ -0,0 +1,9 @@ +package com.shoplix.modules.gsc.enums; + +/** Google Search Console连接允许操作。 */ +public enum GscConnectionOperationEnum { + /** 发起Google授权。 */ AUTHORIZE, + /** 解除Google授权。 */ DISCONNECT, + /** 重新发起Google授权。 */ REAUTHORIZE, + /** 查询Search Console统计。 */ QUERY_STATISTICS +} diff --git a/service/src/main/java/com/shoplix/modules/gsc/enums/GscConnectionStatusEnum.java b/service/src/main/java/com/shoplix/modules/gsc/enums/GscConnectionStatusEnum.java new file mode 100644 index 0000000..a0478de --- /dev/null +++ b/service/src/main/java/com/shoplix/modules/gsc/enums/GscConnectionStatusEnum.java @@ -0,0 +1,17 @@ +package com.shoplix.modules.gsc.enums; + +/** Google Search Console连接状态。 */ +public enum GscConnectionStatusEnum { + /** 已成功授权并可查询数据。 */ CONNECTED("已连接", GscConnectionOperationEnum.DISCONNECT, GscConnectionOperationEnum.QUERY_STATISTICS), + /** 已主动解除授权。 */ DISCONNECTED("未连接", GscConnectionOperationEnum.AUTHORIZE), + /** Google授权已失效。 */ EXPIRED("授权已失效", GscConnectionOperationEnum.REAUTHORIZE); + + private final String label; + private final java.util.List operations; + /** 创建连接状态。 */ GscConnectionStatusEnum(String label, GscConnectionOperationEnum... operations) { + this.label = label; + this.operations = java.util.List.of(operations); + } + /** 获取状态文案。 */ public String getLabel() { return label; } + /** 获取当前状态允许操作。 */ public java.util.List getOperations() { return operations; } +} diff --git a/service/src/main/java/com/shoplix/modules/gsc/enums/GscOauthStateStatusEnum.java b/service/src/main/java/com/shoplix/modules/gsc/enums/GscOauthStateStatusEnum.java new file mode 100644 index 0000000..8213b7d --- /dev/null +++ b/service/src/main/java/com/shoplix/modules/gsc/enums/GscOauthStateStatusEnum.java @@ -0,0 +1,11 @@ +package com.shoplix.modules.gsc.enums; + +/** Google OAuth临时状态使用状态。 */ +public enum GscOauthStateStatusEnum { + /** 尚未使用。 */ UNUSED(0), + /** 已使用。 */ USED(1); + + private final int value; + /** 创建OAuth状态枚举。 */ GscOauthStateStatusEnum(int value) { this.value = value; } + /** 获取数据库状态值。 */ public int getValue() { return value; } +} diff --git a/service/src/main/java/com/shoplix/modules/gsc/repository/entity/GscConnectionEntity.java b/service/src/main/java/com/shoplix/modules/gsc/repository/entity/GscConnectionEntity.java new file mode 100644 index 0000000..b42b725 --- /dev/null +++ b/service/src/main/java/com/shoplix/modules/gsc/repository/entity/GscConnectionEntity.java @@ -0,0 +1,21 @@ +package com.shoplix.modules.gsc.repository.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +/** Google Search Console站点授权连接持久化实体。 */ +@Data +@TableName("gsc_connection") +public class GscConnectionEntity { + /** 数据库内部主键。 */ @TableId(type = IdType.AUTO) private Long id; + /** GSC连接业务编号。 */ private String connectionCode; + /** 所属站点业务编号。 */ private String siteCode; + /** Google Search Console站点资源地址。 */ private String propertyUri; + /** 授权Google账户邮箱。 */ private String accountEmail; + /** 加密后的OAuth刷新令牌。 */ private String refreshTokenCiphertext; + /** 连接状态:CONNECTED已连接,DISCONNECTED已解绑,EXPIRED授权失效。 */ private String status; + /** 创建时间毫秒时间戳。 */ private Long createTime; + /** 更新时间毫秒时间戳。 */ private Long updateTime; +} diff --git a/service/src/main/java/com/shoplix/modules/gsc/repository/entity/GscOauthStateEntity.java b/service/src/main/java/com/shoplix/modules/gsc/repository/entity/GscOauthStateEntity.java new file mode 100644 index 0000000..13dd6a9 --- /dev/null +++ b/service/src/main/java/com/shoplix/modules/gsc/repository/entity/GscOauthStateEntity.java @@ -0,0 +1,19 @@ +package com.shoplix.modules.gsc.repository.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +/** Google Search Console OAuth临时状态持久化实体。 */ +@Data +@TableName("gsc_oauth_state") +public class GscOauthStateEntity { + /** 数据库内部主键。 */ @TableId(type = IdType.AUTO) private Long id; + /** OAuth防重放随机状态码。 */ private String stateCode; + /** 发起授权的站点业务编号。 */ private String siteCode; + /** 授权完成后的后台跳转地址。 */ private String redirectUri; + /** 状态码失效时间毫秒时间戳。 */ private Long expireTime; + /** 使用状态:0未使用,1已使用。 */ private Integer used; + /** 创建时间毫秒时间戳。 */ private Long createTime; +} diff --git a/service/src/main/java/com/shoplix/modules/gsc/repository/mapper/GscConnectionMapper.java b/service/src/main/java/com/shoplix/modules/gsc/repository/mapper/GscConnectionMapper.java new file mode 100644 index 0000000..121eb43 --- /dev/null +++ b/service/src/main/java/com/shoplix/modules/gsc/repository/mapper/GscConnectionMapper.java @@ -0,0 +1,8 @@ +package com.shoplix.modules.gsc.repository.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.shoplix.modules.gsc.repository.entity.GscConnectionEntity; + +/** Google Search Console连接Mapper。 */ +public interface GscConnectionMapper extends BaseMapper { +} diff --git a/service/src/main/java/com/shoplix/modules/gsc/repository/mapper/GscOauthStateMapper.java b/service/src/main/java/com/shoplix/modules/gsc/repository/mapper/GscOauthStateMapper.java new file mode 100644 index 0000000..e5c0c45 --- /dev/null +++ b/service/src/main/java/com/shoplix/modules/gsc/repository/mapper/GscOauthStateMapper.java @@ -0,0 +1,8 @@ +package com.shoplix.modules.gsc.repository.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.shoplix.modules.gsc.repository.entity.GscOauthStateEntity; + +/** Google Search Console OAuth状态Mapper。 */ +public interface GscOauthStateMapper extends BaseMapper { +} diff --git a/service/src/main/java/com/shoplix/modules/gsc/repository/service/GscConnectionRepositoryService.java b/service/src/main/java/com/shoplix/modules/gsc/repository/service/GscConnectionRepositoryService.java new file mode 100644 index 0000000..1823937 --- /dev/null +++ b/service/src/main/java/com/shoplix/modules/gsc/repository/service/GscConnectionRepositoryService.java @@ -0,0 +1,25 @@ +package com.shoplix.modules.gsc.repository.service; + +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.shoplix.modules.gsc.repository.entity.GscConnectionEntity; +import com.shoplix.modules.gsc.repository.mapper.GscConnectionMapper; +import java.util.Optional; +import org.springframework.stereotype.Service; + +/** Google Search Console连接单表数据源服务。 */ +@Service +public class GscConnectionRepositoryService { + private final GscConnectionMapper mapper; + + /** 注入GSC连接Mapper。 */ + public GscConnectionRepositoryService(GscConnectionMapper mapper) { this.mapper = mapper; } + + /** 按站点查询GSC连接。 */ + public Optional findBySiteCode(String siteCode) { + return Optional.ofNullable(mapper.selectOne(Wrappers.lambdaQuery() + .eq(GscConnectionEntity::getSiteCode, siteCode))); + } + + /** 新增GSC连接。 */ public int insert(GscConnectionEntity entity) { return mapper.insert(entity); } + /** 更新GSC连接。 */ public int update(GscConnectionEntity entity) { return mapper.updateById(entity); } +} diff --git a/service/src/main/java/com/shoplix/modules/gsc/repository/service/GscOauthStateRepositoryService.java b/service/src/main/java/com/shoplix/modules/gsc/repository/service/GscOauthStateRepositoryService.java new file mode 100644 index 0000000..bd27ef2 --- /dev/null +++ b/service/src/main/java/com/shoplix/modules/gsc/repository/service/GscOauthStateRepositoryService.java @@ -0,0 +1,34 @@ +package com.shoplix.modules.gsc.repository.service; + +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.shoplix.modules.gsc.repository.entity.GscOauthStateEntity; +import com.shoplix.modules.gsc.repository.mapper.GscOauthStateMapper; +import com.shoplix.modules.gsc.enums.GscOauthStateStatusEnum; +import java.util.Optional; +import org.springframework.stereotype.Service; + +/** Google Search Console OAuth状态单表数据源服务。 */ +@Service +public class GscOauthStateRepositoryService { + private final GscOauthStateMapper mapper; + + /** 注入OAuth状态Mapper。 */ + public GscOauthStateRepositoryService(GscOauthStateMapper mapper) { this.mapper = mapper; } + + /** 新增OAuth状态。 */ public int insert(GscOauthStateEntity entity) { return mapper.insert(entity); } + + /** 查询尚未使用的OAuth状态。 */ + public Optional findUsable(String stateCode, long currentTime) { + return Optional.ofNullable(mapper.selectOne(Wrappers.lambdaQuery() + .eq(GscOauthStateEntity::getStateCode, stateCode).eq(GscOauthStateEntity::getUsed, GscOauthStateStatusEnum.UNUSED.getValue()) + .gt(GscOauthStateEntity::getExpireTime, currentTime))); + } + + /** 将OAuth状态原子标记为已使用。 */ + public int markUsed(String stateCode) { + GscOauthStateEntity update = new GscOauthStateEntity(); + update.setUsed(GscOauthStateStatusEnum.USED.getValue()); + return mapper.update(update, Wrappers.lambdaUpdate() + .eq(GscOauthStateEntity::getStateCode, stateCode).eq(GscOauthStateEntity::getUsed, GscOauthStateStatusEnum.UNUSED.getValue())); + } +} diff --git a/web-admin/src/GscOperationsPage.tsx b/web-admin/src/GscOperationsPage.tsx new file mode 100644 index 0000000..8735f34 --- /dev/null +++ b/web-admin/src/GscOperationsPage.tsx @@ -0,0 +1,109 @@ +import { useEffect, useMemo, useState } from "react"; +import { BarChart3, ExternalLink, Link2, SearchCheck, Unlink } from "lucide-react"; +import { apiPost } from "./api"; +import { getCurrentSiteCode } from "./siteContext"; + +type Connection = { + oauthConfigured: boolean; + connected: boolean; + accountEmail?: string; + propertyUri?: string; + status: string; + statusLabel: string; + operations: string[]; + updateTime?: number; +}; +type Metric = { clicks: number; impressions: number; ctr: number; position: number }; +type Trend = Metric & { date: string }; +type Keyword = Metric & { keyword: string }; +type Page = Metric & { page: string }; +type Statistics = { + submittedUrls: number; + indexedUrls: number; + keywordCount: number; + metric: Metric; + trends: Trend[]; + keywords: Keyword[]; + pages: Page[]; +}; + +/** 格式化日期为接口使用的ISO日期。 */ +function isoDate(date: Date): string { return date.toISOString().slice(0, 10); } +/** 格式化整数指标。 */ +function integer(value: number): string { return new Intl.NumberFormat("zh-CN", { maximumFractionDigits: 0 }).format(value || 0); } + +/** Google Search Console授权与效果统计页面。 */ +export default function GscOperationsPage() { + const siteCode = getCurrentSiteCode(); + const defaultEnd = useMemo(() => new Date(), []); + const defaultStart = useMemo(() => new Date(defaultEnd.getTime() - 27 * 86400000), [defaultEnd]); + const [connection, setConnection] = useState(null); + const [statistics, setStatistics] = useState(null); + const [startDate, setStartDate] = useState(isoDate(defaultStart)); + const [endDate, setEndDate] = useState(isoDate(defaultEnd)); + const [loading, setLoading] = useState(true); + const [error, setError] = useState(""); + + /** 加载授权状态,并在已授权时加载统计。 */ + const load = async () => { + try { + setLoading(true); setError(""); + const value = await apiPost("/gsc/connection", { siteCode }); + setConnection(value); + if (value.connected) await loadStatistics(); else setStatistics(null); + } catch (reason) { setError(reason instanceof Error ? reason.message : "加载失败"); } + finally { setLoading(false); } + }; + + /** 查询所选日期范围的GSC统计。 */ + const loadStatistics = async () => { + const value = await apiPost("/gsc/statistics", { siteCode, startDate, endDate }); + setStatistics(value); + }; + + /** 跳转Google OAuth授权页面。 */ + const authorize = async () => { + try { + setError(""); + const result = await apiPost<{ authorizationUrl: string }>("/gsc/authorization", { + siteCode, + returnUrl: `${window.location.origin}/?section=gsc`, + }); + window.location.assign(result.authorizationUrl); + } catch (reason) { setError(reason instanceof Error ? reason.message : "授权失败"); } + }; + + /** 解除当前站点GSC授权。 */ + const disconnect = async () => { + if (!window.confirm("确认解除当前域名的 Google Search Console 授权吗?")) return; + try { await apiPost("/gsc/disconnect", { siteCode }); await load(); } + catch (reason) { setError(reason instanceof Error ? reason.message : "解绑失败"); } + }; + + useEffect(() => { void load(); }, [siteCode]); + + return
+
运营

Google Search Console

直接绑定店铺域名,查看收录、关键词和自然搜索效果。

+ {error &&
{error}
} +
+

域名授权

{connection?.connected ? `${connection.accountEmail} · ${connection.propertyUri}` : "授权 Google 账户后自动匹配当前店铺域名对应的站点资源。"}

+ {connection?.connected ?
打开 GSC
+ : } +
+ {connection?.oauthConfigured === false &&
尚未配置 Google OAuth。请设置 SHOPLIX_GSC_CLIENT_ID、SHOPLIX_GSC_CLIENT_SECRET 和线上回调地址后重启后台服务。
} +

搜索效果

Search Console 数据通常会延迟约 2–3 天。

setStartDate(event.target.value)}/>至 setEndDate(event.target.value)}/>
+
+
已索引 URL{integer(statistics?.indexedUrls || 0)}站点地图提交 {integer(statistics?.submittedUrls || 0)}
+
关键词数{integer(statistics?.keywordCount || 0)}统计期内产生曝光
+
总点击次数{integer(statistics?.metric.clicks || 0)}自然搜索点击
+
总曝光次数{integer(statistics?.metric.impressions || 0)}Google 搜索曝光
+
平均点击率{((statistics?.metric.ctr || 0) * 100).toFixed(2)}%Clicks / Impressions
+
平均排名{(statistics?.metric.position || 0).toFixed(1)}数值越小排名越高
+
+

效果趋势

每日点击与曝光变化

{statistics?.trends.length ? statistics.trends.map(item => { const max = Math.max(...statistics.trends.map(row => row.impressions), 1); return
{item.date.slice(5)}
; }) :
{connection?.connected ? "所选日期暂无趋势数据" : "授权后展示搜索趋势"}
}
+
+

关键词效果

{statistics?.keywords.slice(0, 100).map(item => )}
关键词点击曝光CTR排名
{item.keyword}{integer(item.clicks)}{integer(item.impressions)}{(item.ctr*100).toFixed(2)}%{item.position.toFixed(1)}
+

页面收录效果

{statistics?.pages.slice(0, 100).map(item => )}
页面点击曝光CTR排名
{item.page}{integer(item.clicks)}{integer(item.impressions)}{(item.ctr*100).toFixed(2)}%{item.position.toFixed(1)}
+
+
; +} diff --git a/web-admin/src/main.tsx b/web-admin/src/main.tsx index ca928b6..9540938 100644 --- a/web-admin/src/main.tsx +++ b/web-admin/src/main.tsx @@ -9,6 +9,7 @@ import { FolderTree, Globe2, LayoutDashboard, + LineChart, HelpCircle, Image, Mail, @@ -44,6 +45,7 @@ import AgreementSettingsPage from "./AgreementSettingsPage"; import AboutUsSettingsPage from "./AboutUsSettingsPage"; import DashboardPage from "./DashboardPage"; import CrmCustomerPage from "./CrmCustomerPage"; +import GscOperationsPage from "./GscOperationsPage"; import { apiPost, assetUrl } from "./api"; import { statusLabel } from "./statusLabels"; import { @@ -82,7 +84,8 @@ type Section = | "settings-store" | "settings-account" | "settings-social" - | "crm-customers"; + | "crm-customers" + | "gsc"; type EditorialSection = "NEWS" | "CASE" | "HELP"; type ContentEditorState = { contentType: EditorialSection; @@ -183,6 +186,7 @@ const sectionLabels: Record = { "settings-account": "账户与安全", "settings-social": "社媒渠道", "crm-customers": "客户列表", + gsc: "Google Search Console", }; function App({ account, @@ -212,10 +216,9 @@ function App({ }; }; const initialContentEditor = resolveContentRoute(); - const [section, setSection] = useState
( - initialContentEditor?.contentType || - (window.location.pathname.startsWith("/pages/") ? "pages" : "dashboard"), - ); + const [section, setSection] = useState
(initialContentEditor?.contentType || + (new URLSearchParams(window.location.search).get("section") === "gsc" ? "gsc" : + (window.location.pathname.startsWith("/pages/") ? "pages" : "dashboard"))); const [items, setItems] = useState([]); const [error, setError] = useState(""); const [query, setQuery] = useState(""); @@ -289,6 +292,7 @@ function App({ const [frontSiteMenuOpen, setFrontSiteMenuOpen] = useState(false); const [systemSettingsOpen, setSystemSettingsOpen] = useState(false); const [crmMenuOpen, setCrmMenuOpen] = useState(false); + const [operationsMenuOpen, setOperationsMenuOpen] = useState(false); const navigateSection = (next: Section) => { setEditingProduct(null); setEditingContent(null); @@ -313,6 +317,8 @@ function App({ ? { items: [] } : section.startsWith("settings-") ? { items: [] } + : section === "gsc" + ? { items: [] } : section === "navigation" ? { items: [] } : section === "agreements" @@ -582,6 +588,12 @@ function App({ 数据概览 +
+ + {operationsMenuOpen &&
} +