功能迭代

This commit is contained in:
张锐 committed 2026-12-02 16:10:54 +08:00
1 parent 5fc7d4564c
commit 84184a2dd1
41 files changed
+1054 -8

No files matched your search

+7
View File
@@ -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=
@@ -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);
@@ -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);
}
}
@@ -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) {
}
@@ -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) {
}
@@ -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) {
}
@@ -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) {
}
@@ -0,0 +1,6 @@
package com.shoplix.admin.modules.gsc.res;
/** GSC授权地址响应。 */
public record GscAuthorizationAdminRes(
/** Google OAuth授权地址。 */ String authorizationUrl) {
}
@@ -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<GscConnectionOperationEnum> operations,
/** 最后更新时间毫秒时间戳。 */ Long updateTime) {
}
@@ -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) {
}
@@ -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) {
}
@@ -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) {
}
@@ -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<GscTrendAdminRes> trends,
/** 关键词效果明细。 */ List<GscKeywordAdminRes> keywords,
/** 页面效果明细。 */ List<GscPageAdminRes> pages) {
}
@@ -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) {
}
@@ -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<GscProperty> 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()));
}
}
@@ -0,0 +1,7 @@
package com.shoplix.admin.third.gsc;
import java.util.List;
/** Google Search Analytics单行统计。 */
public record GscAnalyticsRow(List<String> keys, double clicks, double impressions, double ctr, double position) {
}
@@ -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<GscProperty> properties(String accessToken) {
List<GscProperty> 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<GscAnalyticsRow> analytics(String accessToken, String propertyUri, LocalDate startDate,
LocalDate endDate, List<String> 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<GscAnalyticsRow> result = new ArrayList<>();
for (JsonNode row : json.path("rows")) {
List<String> 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<String> 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<String, String> values) {
return values.entrySet().stream().map(item -> encode(item.getKey()) + "=" + encode(item.getValue()))
.collect(java.util.stream.Collectors.joining("&"));
}
}
@@ -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(); }
}
@@ -0,0 +1,5 @@
package com.shoplix.admin.third.gsc;
/** Google Search Console站点资源。 */
public record GscProperty(String siteUrl, String permissionLevel) {
}
@@ -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()));
}
}
@@ -0,0 +1,5 @@
package com.shoplix.admin.third.gsc;
/** Google OAuth令牌交换结果。 */
public record GscTokenResponse(String accessToken, String refreshToken, long expiresIn) {
}
+5
View File
@@ -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}
@@ -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临时状态';
@@ -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
@@ -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授权令牌读取失败,请重新授权
@@ -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授權權杖讀取失敗,請重新授權
@@ -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));
}
}
@@ -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;
@@ -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
}
@@ -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<GscConnectionOperationEnum> 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<GscConnectionOperationEnum> getOperations() { return operations; }
}
@@ -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; }
}
@@ -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;
}
@@ -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;
}
@@ -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<GscConnectionEntity> {
}
@@ -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<GscOauthStateEntity> {
}
@@ -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<GscConnectionEntity> findBySiteCode(String siteCode) {
return Optional.ofNullable(mapper.selectOne(Wrappers.<GscConnectionEntity>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); }
}
@@ -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<GscOauthStateEntity> findUsable(String stateCode, long currentTime) {
return Optional.ofNullable(mapper.selectOne(Wrappers.<GscOauthStateEntity>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.<GscOauthStateEntity>lambdaUpdate()
.eq(GscOauthStateEntity::getStateCode, stateCode).eq(GscOauthStateEntity::getUsed, GscOauthStateStatusEnum.UNUSED.getValue()));
}
}
+109
View File
@@ -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<Connection | null>(null);
const [statistics, setStatistics] = useState<Statistics | null>(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<Connection>("/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<Statistics>("/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 <div className="gsc-page">
<header className="gsc-title"><div><span>运营</span><h1>Google Search Console</h1><p>直接绑定店铺域名,查看收录、关键词和自然搜索效果。</p></div><SearchCheck size={36}/></header>
{error && <div className="gsc-error">{error}</div>}
<section className="gsc-panel gsc-connection">
<div><h2>域名授权</h2><p>{connection?.connected ? `${connection.accountEmail} · ${connection.propertyUri}` : "授权 Google 账户后自动匹配当前店铺域名对应的站点资源。"}</p></div>
{connection?.connected ? <div className="gsc-actions"><a href="https://search.google.com/search-console" target="_blank" rel="noreferrer"><ExternalLink size={16}/>打开 GSC</a><button onClick={disconnect}><Unlink size={16}/>解除授权</button></div>
: <button className="primary" disabled={loading || connection?.oauthConfigured === false} onClick={authorize}><Link2 size={16}/>授权当前域名</button>}
</section>
{connection?.oauthConfigured === false && <div className="gsc-notice">尚未配置 Google OAuth。请设置 SHOPLIX_GSC_CLIENT_ID、SHOPLIX_GSC_CLIENT_SECRET 和线上回调地址后重启后台服务。</div>}
<section className="gsc-panel gsc-toolbar"><div><h2>搜索效果</h2><p>Search Console 数据通常会延迟约 2–3 天。</p></div><div className="gsc-date"><input type="date" value={startDate} onChange={event => setStartDate(event.target.value)}/><span>至</span><input type="date" value={endDate} onChange={event => setEndDate(event.target.value)}/><button disabled={!connection?.connected || loading} onClick={() => { setLoading(true); loadStatistics().catch(reason => setError(reason.message)).finally(() => setLoading(false)); }}>查询</button></div></section>
<div className="gsc-metrics">
<article><span>已索引 URL</span><strong>{integer(statistics?.indexedUrls || 0)}</strong><small>站点地图提交 {integer(statistics?.submittedUrls || 0)}</small></article>
<article><span>关键词数</span><strong>{integer(statistics?.keywordCount || 0)}</strong><small>统计期内产生曝光</small></article>
<article><span>总点击次数</span><strong>{integer(statistics?.metric.clicks || 0)}</strong><small>自然搜索点击</small></article>
<article><span>总曝光次数</span><strong>{integer(statistics?.metric.impressions || 0)}</strong><small>Google 搜索曝光</small></article>
<article><span>平均点击率</span><strong>{((statistics?.metric.ctr || 0) * 100).toFixed(2)}%</strong><small>Clicks / Impressions</small></article>
<article><span>平均排名</span><strong>{(statistics?.metric.position || 0).toFixed(1)}</strong><small>数值越小排名越高</small></article>
</div>
<section className="gsc-panel"><div className="gsc-section-head"><div><h2>效果趋势</h2><p>每日点击与曝光变化</p></div><BarChart3 size={22}/></div><div className="gsc-trend">{statistics?.trends.length ? statistics.trends.map(item => { const max = Math.max(...statistics.trends.map(row => row.impressions), 1); return <div className="gsc-trend-item" key={item.date} title={`${item.date} · 曝光 ${integer(item.impressions)} · 点击 ${integer(item.clicks)}`}><i style={{height:`${Math.max(4, item.impressions / max * 100)}%`}}/><span>{item.date.slice(5)}</span></div>; }) : <div className="gsc-empty">{connection?.connected ? "所选日期暂无趋势数据" : "授权后展示搜索趋势"}</div>}</div></section>
<div className="gsc-tables">
<section className="gsc-panel"><h2>关键词效果</h2><div className="gsc-table-wrap"><table><thead><tr><th>关键词</th><th>点击</th><th>曝光</th><th>CTR</th><th>排名</th></tr></thead><tbody>{statistics?.keywords.slice(0, 100).map(item => <tr key={item.keyword}><td>{item.keyword}</td><td>{integer(item.clicks)}</td><td>{integer(item.impressions)}</td><td>{(item.ctr*100).toFixed(2)}%</td><td>{item.position.toFixed(1)}</td></tr>)}</tbody></table></div></section>
<section className="gsc-panel"><h2>页面收录效果</h2><div className="gsc-table-wrap"><table><thead><tr><th>页面</th><th>点击</th><th>曝光</th><th>CTR</th><th>排名</th></tr></thead><tbody>{statistics?.pages.slice(0, 100).map(item => <tr key={item.page}><td className="gsc-url" title={item.page}>{item.page}</td><td>{integer(item.clicks)}</td><td>{integer(item.impressions)}</td><td>{(item.ctr*100).toFixed(2)}%</td><td>{item.position.toFixed(1)}</td></tr>)}</tbody></table></div></section>
</div>
</div>;
}
+19 -5
View File
@@ -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<Section, string> = {
"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<Section>(
initialContentEditor?.contentType ||
(window.location.pathname.startsWith("/pages/") ? "pages" : "dashboard"),
);
const [section, setSection] = useState<Section>(initialContentEditor?.contentType ||
(new URLSearchParams(window.location.search).get("section") === "gsc" ? "gsc" :
(window.location.pathname.startsWith("/pages/") ? "pages" : "dashboard")));
const [items, setItems] = useState<Item[]>([]);
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({
<LayoutDashboard size={18} />
数据概览
</button>
<div className="nav-group">
<button className={section === "gsc" ? "group-active" : ""} onClick={() => setOperationsMenuOpen(!operationsMenuOpen)}>
<LineChart size={18} />运营<ChevronDown className={operationsMenuOpen ? "expanded" : ""} size={16}/>
</button>
{operationsMenuOpen && <div className="nav-children"><button className={section === "gsc" ? "active" : ""} onClick={() => navigateSection("gsc")}><Search size={15}/>Google Search Console</button></div>}
</div>
<div className="nav-group">
<button
className={
@@ -789,6 +801,8 @@ function App({
<DashboardPage
onNavigate={(next) => navigateSection(next as Section)}
/>
) : section === "gsc" ? (
<GscOperationsPage />
) : section === "crm-customers" ? (
<CrmCustomerPage />
) : section === "settings-store" ? (
+1
View File
@@ -4016,3 +4016,4 @@ header p {
@media (max-width: 900px) {
.template-related-products { grid-template-columns: 1fr; }
}
.gsc-page{padding:32px;display:grid;gap:18px;max-width:1500px;margin:0 auto}.gsc-title{display:flex;align-items:center;justify-content:space-between}.gsc-title span{font-size:13px;color:#147363;font-weight:700}.gsc-title h1{margin:5px 0 6px;font-size:28px}.gsc-title p,.gsc-panel p{margin:0;color:#667085}.gsc-panel{background:#fff;border:1px solid #e2e8f0;border-radius:12px;padding:20px}.gsc-panel h2{margin:0 0 7px;font-size:17px}.gsc-connection,.gsc-toolbar,.gsc-section-head{display:flex;align-items:center;justify-content:space-between;gap:20px}.gsc-actions,.gsc-date{display:flex;align-items:center;gap:10px}.gsc-actions a,.gsc-actions button,.gsc-connection>button,.gsc-date button{display:inline-flex;align-items:center;gap:7px;border:1px solid #d0d5dd;background:#fff;border-radius:7px;padding:9px 13px;text-decoration:none;color:#344054}.gsc-connection>button.primary{background:#126b5c;color:#fff;border-color:#126b5c}.gsc-date input{border:1px solid #d0d5dd;border-radius:6px;padding:8px}.gsc-error,.gsc-notice{padding:12px 15px;border-radius:8px}.gsc-error{background:#fff1f0;color:#b42318}.gsc-notice{background:#fffaeb;color:#854a0e}.gsc-metrics{display:grid;grid-template-columns:repeat(6,minmax(0,1fr));gap:12px}.gsc-metrics article{background:#fff;border:1px solid #e2e8f0;border-radius:10px;padding:18px}.gsc-metrics span{display:block;color:#667085;font-size:13px}.gsc-metrics strong{display:block;font-size:27px;margin:8px 0}.gsc-metrics small{color:#98a2b3}.gsc-trend{height:220px;display:flex;align-items:flex-end;gap:8px;padding-top:25px}.gsc-trend-item{height:100%;flex:1;min-width:12px;display:flex;flex-direction:column;justify-content:flex-end;align-items:center;gap:7px}.gsc-trend-item i{display:block;width:100%;max-width:26px;background:#168675;border-radius:4px 4px 0 0}.gsc-trend-item span{font-size:10px;color:#98a2b3;white-space:nowrap}.gsc-empty{margin:auto;color:#98a2b3}.gsc-tables{display:grid;grid-template-columns:1fr 1fr;gap:18px}.gsc-table-wrap{overflow:auto;max-height:520px}.gsc-table-wrap table{width:100%;border-collapse:collapse;margin-top:12px;font-size:13px}.gsc-table-wrap th,.gsc-table-wrap td{padding:10px 8px;border-bottom:1px solid #eef2f6;text-align:right}.gsc-table-wrap th:first-child,.gsc-table-wrap td:first-child{text-align:left}.gsc-url{max-width:310px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}@media(max-width:1100px){.gsc-metrics{grid-template-columns:repeat(3,1fr)}.gsc-tables{grid-template-columns:1fr}}@media(max-width:700px){.gsc-page{padding:18px}.gsc-connection,.gsc-toolbar{align-items:flex-start;flex-direction:column}.gsc-metrics{grid-template-columns:repeat(2,1fr)}.gsc-date{flex-wrap:wrap}}
+1 -1
View File
@@ -1 +1 @@
{"root":["./src/aboutussettingspage.tsx","./src/agreementsettingspage.tsx","./src/categorymanager.tsx","./src/contenteditor.tsx","./src/crmcustomerpage.tsx","./src/customcodemanager.tsx","./src/dashboardpage.tsx","./src/decorationeditor.tsx","./src/inquirysettingspanel.tsx","./src/loginpage.tsx","./src/mediacenter.tsx","./src/navigationmanager.tsx","./src/pageeditor.tsx","./src/producteditor.tsx","./src/producttemplatemanager.tsx","./src/seosettingspage.tsx","./src/settingspage.tsx","./src/api.ts","./src/main.tsx","./src/sitecontext.ts","./src/statuslabels.ts","./src/vite-env.d.ts"],"version":"5.7.3"}
{"root":["./src/aboutussettingspage.tsx","./src/agreementsettingspage.tsx","./src/categorymanager.tsx","./src/contenteditor.tsx","./src/crmcustomerpage.tsx","./src/customcodemanager.tsx","./src/dashboardpage.tsx","./src/decorationeditor.tsx","./src/gscoperationspage.tsx","./src/inquirysettingspanel.tsx","./src/loginpage.tsx","./src/mediacenter.tsx","./src/navigationmanager.tsx","./src/pageeditor.tsx","./src/producteditor.tsx","./src/producttemplatemanager.tsx","./src/seosettingspage.tsx","./src/settingspage.tsx","./src/api.ts","./src/main.tsx","./src/sitecontext.ts","./src/statuslabels.ts","./src/vite-env.d.ts"],"version":"5.7.3"}