feat: 新增拼多多店铺授权

This commit is contained in:
2026-08-03 16:08:27 +08:00
parent 4e58b67c13
commit 4aa76cefdf
38 changed files with 1339 additions and 96 deletions
@@ -408,11 +408,13 @@ CREATE TABLE `ec_shop` (
`name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '店铺名称', `name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '店铺名称',
`logo_image_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT 'logo图片ID', `logo_image_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT 'logo图片ID',
`platform_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT '平台ID', `platform_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT '平台ID',
`external_shop_id` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '外部店铺ID(如拼多多 mall_id;与 platform_id 组合关联平台店铺)',
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
`create_by` bigint UNSIGNED NULL DEFAULT NULL COMMENT '创建人ID', `create_by` bigint UNSIGNED NULL DEFAULT NULL COMMENT '创建人ID',
`update_by` bigint UNSIGNED NULL DEFAULT NULL COMMENT '更新人ID', `update_by` bigint UNSIGNED NULL DEFAULT NULL COMMENT '更新人ID',
PRIMARY KEY (`id`) USING BTREE, PRIMARY KEY (`id`) USING BTREE,
UNIQUE INDEX `uk_ec_shop_company_platform_external`(`company_id` ASC, `platform_id` ASC, `external_shop_id` ASC) USING BTREE COMMENT '同一公司同一平台下外部店铺ID唯一(NULL 可重复,手工店)',
INDEX `idx_company_id`(`company_id` ASC) USING BTREE, INDEX `idx_company_id`(`company_id` ASC) USING BTREE,
INDEX `idx_platform_id`(`platform_id` ASC) USING BTREE, INDEX `idx_platform_id`(`platform_id` ASC) USING BTREE,
INDEX `fk_ec_shop_logo_image`(`logo_image_id` ASC) USING BTREE, INDEX `fk_ec_shop_logo_image`(`logo_image_id` ASC) USING BTREE,
@@ -3,11 +3,10 @@
-- 对应接口 pop_auth_token_create 响应体 pop_auth_token_create_response -- 对应接口 pop_auth_token_create 响应体 pop_auth_token_create_response
-- 字段说明:仅保留业务必需项;w1/w2/r1/r2、expires_in、request_id 等存入 raw_response -- 字段说明:仅保留业务必需项;w1/w2/r1/r2、expires_in、request_id 等存入 raw_response
-- ======================================== -- ========================================
DROP TABLE IF EXISTS `open_pdd_auth`; DROP TABLE IF EXISTS `ec_pdd_auth`;
CREATE TABLE `open_pdd_auth` ( CREATE TABLE `ec_pdd_auth` (
`id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键ID', `id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`company_id` bigint UNSIGNED NOT NULL COMMENT '所属公司ID', `company_id` bigint UNSIGNED NOT NULL COMMENT '所属公司ID',
`shop_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT '关联店铺ID(ec_shop.id),授权后绑定',
`owner_id` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '拼多多授权主体ID(owner_id)', `owner_id` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '拼多多授权主体ID(owner_id)',
`access_token` varchar(512) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '访问令牌', `access_token` varchar(512) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '访问令牌',
`refresh_token` varchar(512) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '刷新令牌', `refresh_token` varchar(512) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '刷新令牌',
@@ -20,10 +19,8 @@ CREATE TABLE `open_pdd_auth` (
`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`) USING BTREE, PRIMARY KEY (`id`) USING BTREE,
UNIQUE INDEX `uk_open_pdd_auth_company_owner`(`company_id` ASC, `owner_id` ASC) USING BTREE COMMENT '同一公司下拼多多 owner_id 唯一', UNIQUE INDEX `uk_open_pdd_auth_company_owner`(`company_id` ASC, `owner_id` ASC) USING BTREE COMMENT '同一公司下拼多多 owner_id 唯一',
INDEX `idx_open_pdd_auth_shop`(`shop_id` ASC) USING BTREE,
INDEX `idx_open_pdd_auth_status`(`status` ASC) USING BTREE, INDEX `idx_open_pdd_auth_status`(`status` ASC) USING BTREE,
INDEX `idx_open_pdd_auth_expires_at`(`expires_at` ASC) USING BTREE COMMENT '定时刷新 access_token', INDEX `idx_open_pdd_auth_expires_at`(`expires_at` ASC) USING BTREE COMMENT '定时刷新 access_token',
INDEX `idx_open_pdd_auth_refresh_expires`(`refresh_token_expires_at` ASC) USING BTREE, INDEX `idx_open_pdd_auth_refresh_expires`(`refresh_token_expires_at` ASC) USING BTREE,
CONSTRAINT `fk_open_pdd_auth_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `fk_open_pdd_auth_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
CONSTRAINT `fk_open_pdd_auth_shop` FOREIGN KEY (`shop_id`) REFERENCES `ec_shop` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '开放接口-拼多多 OAuth 授权凭证表' ROW_FORMAT = Dynamic; ) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '开放接口-拼多多 OAuth 授权凭证表' ROW_FORMAT = Dynamic;
@@ -16,7 +16,7 @@ CREATE TABLE `ec_pdd_order` (
`id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键ID', `id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID', `company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID',
`shop_id` bigint UNSIGNED NOT NULL COMMENT '店铺ID(ec_shop.id)', `shop_id` bigint UNSIGNED NOT NULL COMMENT '店铺ID(ec_shop.id)',
`pdd_auth_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT '拼多多授权ID(open_pdd_auth.id)', `pdd_auth_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT '拼多多授权ID(ec_pdd_auth.id)',
`order_sn` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '拼多多订单号', `order_sn` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '拼多多订单号',
`order_status` int NOT NULL COMMENT '订单状态(order_status 1:待发货,2:已发货待签收,3:已签收)', `order_status` int NOT NULL COMMENT '订单状态(order_status 1:待发货,2:已发货待签收,3:已签收)',
`refund_status` int NULL DEFAULT NULL COMMENT '退款状态(refund_status 1:无售后或售后关闭,2:售后处理中,3:退款中,4: 退款成功)', `refund_status` int NULL DEFAULT NULL COMMENT '退款状态(refund_status 1:无售后或售后关闭,2:售后处理中,3:退款中,4: 退款成功)',
@@ -62,7 +62,7 @@ CREATE TABLE `ec_pdd_order` (
INDEX `idx_ec_pdd_order_auth`(`pdd_auth_id` ASC) USING BTREE, INDEX `idx_ec_pdd_order_auth`(`pdd_auth_id` ASC) USING BTREE,
CONSTRAINT `fk_ec_pdd_order_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `fk_ec_pdd_order_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_ec_pdd_order_shop` FOREIGN KEY (`shop_id`) REFERENCES `ec_shop` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `fk_ec_pdd_order_shop` FOREIGN KEY (`shop_id`) REFERENCES `ec_shop` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_ec_pdd_order_auth` FOREIGN KEY (`pdd_auth_id`) REFERENCES `open_pdd_auth` (`id`) ON DELETE SET NULL ON UPDATE CASCADE CONSTRAINT `fk_ec_pdd_order_auth` FOREIGN KEY (`pdd_auth_id`) REFERENCES `ec_pdd_auth` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '拼多多-订单主表' ROW_FORMAT = Dynamic; ) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '拼多多-订单主表' ROW_FORMAT = Dynamic;
-- ======================================== -- ========================================
@@ -2,16 +2,16 @@
-- 拼多多店铺对接数据库设计 -- 拼多多店铺对接数据库设计
-- 数据来源:pdd.mall.info.get → mall_info_get_response -- 数据来源:pdd.mall.info.get → mall_info_get_response
-- 设计原则: -- 设计原则:
-- 1. 与 ec_shop(内部店铺)分离,存拼多多平台店铺信息 -- 1. 与 ec_shop(内部店铺)分离,本表只存拼多多平台店铺镜像
-- 2. 授权后可拉取店铺信息写入本表,并回写绑定 ec_shop / open_pdd_auth -- 2. 不主动 FK 关联 ec_shop;绑定由 ec_shop.platform_id + external_shop_id(= mall_id)维护
-- 3. 授权后拉取写入本表,再按公司 + 拼多多平台 + mall_id upsert ec_shop
-- ======================================== -- ========================================
DROP TABLE IF EXISTS `ec_pdd_shop`; DROP TABLE IF EXISTS `ec_pdd_shop`;
CREATE TABLE `ec_pdd_shop` ( CREATE TABLE `ec_pdd_shop` (
`id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键ID', `id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID', `company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID',
`shop_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT '内部店铺ID(ec_shop.id),绑定后填写', `pdd_auth_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT '拼多多授权ID(ec_pdd_auth.id)',
`pdd_auth_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT '拼多多授权ID(open_pdd_auth.id)',
`mall_id` bigint UNSIGNED NOT NULL COMMENT '拼多多店铺ID(mall_id)', `mall_id` bigint UNSIGNED NOT NULL COMMENT '拼多多店铺ID(mall_id)',
`mall_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '店铺名称(mall_name)', `mall_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '店铺名称(mall_name)',
`logo` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '店铺logo(logo)', `logo` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '店铺logo(logo)',
@@ -24,8 +24,6 @@ CREATE TABLE `ec_pdd_shop` (
PRIMARY KEY (`id`) USING BTREE, PRIMARY KEY (`id`) USING BTREE,
UNIQUE INDEX `uk_ec_pdd_shop_company_mall`(`company_id` ASC, `mall_id` ASC) USING BTREE, UNIQUE INDEX `uk_ec_pdd_shop_company_mall`(`company_id` ASC, `mall_id` ASC) USING BTREE,
UNIQUE INDEX `uk_ec_pdd_shop_auth`(`pdd_auth_id` ASC) USING BTREE COMMENT '一个授权对应一个拼多多店铺', UNIQUE INDEX `uk_ec_pdd_shop_auth`(`pdd_auth_id` ASC) USING BTREE COMMENT '一个授权对应一个拼多多店铺',
INDEX `idx_ec_pdd_shop_shop`(`shop_id` ASC) USING BTREE,
CONSTRAINT `fk_ec_pdd_shop_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `fk_ec_pdd_shop_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_ec_pdd_shop_ec_shop` FOREIGN KEY (`shop_id`) REFERENCES `ec_shop` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, CONSTRAINT `fk_ec_pdd_shop_auth` FOREIGN KEY (`pdd_auth_id`) REFERENCES `ec_pdd_auth` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
CONSTRAINT `fk_ec_pdd_shop_auth` FOREIGN KEY (`pdd_auth_id`) REFERENCES `open_pdd_auth` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '拼多多-店铺信息表' ROW_FORMAT = Dynamic; ) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '拼多多-店铺信息表' ROW_FORMAT = Dynamic;
@@ -0,0 +1,14 @@
-- ================================================
-- ec_shop:新增 external_shop_id(外部店铺ID)
-- 与 platform_id 组合关联平台侧店铺(如拼多多 mall_id)
-- ================================================
ALTER TABLE `ec_shop`
ADD COLUMN `external_shop_id` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL
COMMENT '外部店铺ID(如拼多多 mall_id;与 platform_id 组合关联平台店铺)'
AFTER `platform_id`;
ALTER TABLE `ec_shop`
ADD UNIQUE INDEX `uk_ec_shop_company_platform_external`
(`company_id` ASC, `platform_id` ASC, `external_shop_id` ASC)
COMMENT '同一公司同一平台下外部店铺ID唯一(NULL 可重复,手工店)';
@@ -0,0 +1,63 @@
-- 拼多多授权/店铺表 + 授权管理权限
CREATE TABLE IF NOT EXISTS `ec_pdd_auth` (
`id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`company_id` bigint UNSIGNED NOT NULL COMMENT '所属公司ID',
`owner_id` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '拼多多授权主体ID(owner_id)',
`access_token` varchar(512) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '访问令牌',
`refresh_token` varchar(512) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '刷新令牌',
`expires_at` datetime NOT NULL COMMENT 'access_token 过期时间',
`refresh_token_expires_at` datetime NULL DEFAULT NULL COMMENT 'refresh_token 过期时间',
`scope` json NULL COMMENT '授权 scope 列表(JSON 数组)',
`raw_response` json NULL COMMENT '最近一次授权完整响应 JSON',
`status` tinyint NOT NULL DEFAULT 1 COMMENT '状态:0=失效 1=正常 2=已撤销',
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`) USING BTREE,
UNIQUE INDEX `uk_ec_pdd_auth_company_owner`(`company_id` ASC, `owner_id` ASC) USING BTREE,
INDEX `idx_ec_pdd_auth_status`(`status` ASC) USING BTREE,
INDEX `idx_ec_pdd_auth_expires_at`(`expires_at` ASC) USING BTREE,
INDEX `idx_ec_pdd_auth_refresh_expires`(`refresh_token_expires_at` ASC) USING BTREE,
CONSTRAINT `fk_ec_pdd_auth_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '拼多多 OAuth 授权凭证表';
CREATE TABLE IF NOT EXISTS `ec_pdd_shop` (
`id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID',
`pdd_auth_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT '拼多多授权ID(ec_pdd_auth.id)',
`mall_id` bigint UNSIGNED NOT NULL COMMENT '拼多多店铺ID(mall_id)',
`mall_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '店铺名称',
`logo` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '店铺logo',
`mall_desc` varchar(1000) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '店铺描述',
`merchant_type` tinyint NOT NULL COMMENT '店铺类型:1个人 2企业 3旗舰店 4专卖店 5专营店 6普通店',
`mall_character` tinyint NOT NULL DEFAULT 2 COMMENT '店铺身份:0厂商 1分销商 2都不是 3都是',
`last_sync_time` datetime NOT NULL COMMENT '最近一次同步时间',
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`) USING BTREE,
UNIQUE INDEX `uk_ec_pdd_shop_company_mall`(`company_id` ASC, `mall_id` ASC) USING BTREE,
UNIQUE INDEX `uk_ec_pdd_shop_auth`(`pdd_auth_id` ASC) USING BTREE,
CONSTRAINT `fk_ec_pdd_shop_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_ec_pdd_shop_auth` FOREIGN KEY (`pdd_auth_id`) REFERENCES `ec_pdd_auth` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '拼多多-店铺信息表';
-- 权限:拼多多授权管理
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 3600, (SELECT id FROM `sys_permission` WHERE `code` = 'MODULE:ecom' LIMIT 1),
'biz:pdd', '拼多多', 'module', 1, '拼多多对接', 360
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `code` = 'biz:pdd');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 3601, (SELECT id FROM `sys_permission` WHERE `code` = 'biz:pdd' LIMIT 1),
'biz:pdd:auth:manage', '拼多多授权管理', 'api', 1, '生成授权链接/管理授权', 361
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `code` = 'biz:pdd:auth:manage');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 3602, (SELECT id FROM `sys_permission` WHERE `code` = 'biz:pdd' LIMIT 1),
'biz:pdd:shop:read', '拼多多店铺查看', 'api', 1, '', 362
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `code` = 'biz:pdd:shop:read');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 3603, (SELECT id FROM `sys_permission` WHERE `code` = 'biz:pdd' LIMIT 1),
'biz:pdd:shop:manage', '拼多多店铺管理', 'api', 1, '', 363
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `code` = 'biz:pdd:shop:manage');
@@ -46,6 +46,7 @@ public class SecurityConfig {
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(auth -> auth .authorizeHttpRequests(auth -> auth
.requestMatchers("/auth/login", "/auth/register", "/auth/refresh").permitAll() .requestMatchers("/auth/login", "/auth/register", "/auth/refresh").permitAll()
.requestMatchers("/ec/pdd/auth/callback").permitAll()
.requestMatchers("/uploads/**").permitAll() // 允许直接访问上传的文件 .requestMatchers("/uploads/**").permitAll() // 允许直接访问上传的文件
.requestMatchers("/doc.html", "/webjars/**", "/v3/api-docs/**", "/swagger-resources/**", .requestMatchers("/doc.html", "/webjars/**", "/v3/api-docs/**", "/swagger-resources/**",
"/swagger-ui/**", "/swagger-ui.html") "/swagger-ui/**", "/swagger-ui.html")
@@ -29,7 +29,10 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {
@Override @Override
protected boolean shouldNotFilter(@NonNull HttpServletRequest request) { protected boolean shouldNotFilter(@NonNull HttpServletRequest request) {
String uri = request.getRequestURI(); String uri = request.getRequestURI();
return uri != null && uri.startsWith("/open/"); if (uri == null) {
return false;
}
return uri.startsWith("/open/") || uri.startsWith("/ec/pdd/auth/callback");
} }
@Override @Override
@@ -0,0 +1,29 @@
package top.xyquan.ecomdmbbackend.modules.ecom.pdd.auth.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* 拼多多 OAuth 配置
*/
@Data
@Component
@ConfigurationProperties(prefix = "pdd.oauth")
public class PddOAuthProperties {
/** 应用 client_id */
private String clientId = "";
/** 应用 client_secret */
private String clientSecret = "";
/** 回调地址(须与开放平台应用配置一致,指向后端 /ec/pdd/auth/callback) */
private String redirectUri = "";
/** 店铺 WEB 授权页 */
private String authorizeUrl = "https://fuwu.pinduoduo.com/service-market/auth";
/** state 在 Redis 中的有效期(秒) */
private long stateTtlSeconds = 600;
}
@@ -0,0 +1,50 @@
package top.xyquan.ecomdmbbackend.modules.ecom.pdd.auth.controller;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import top.xyquan.ecomdmbbackend.common.annotation.RequirePermission;
import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.auth.model.vo.PddAuthorizeUrlVO;
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.auth.service.PddAuthService;
/**
* 拼多多 OAuth 授权
*/
@Tag(name = "拼多多-授权", description = "拼多多店铺 OAuth 授权跳转与回调")
@RestController
@RequestMapping("/ec/pdd/auth")
public class PddAuthController {
private final PddAuthService pddAuthService;
public PddAuthController(PddAuthService pddAuthService) {
this.pddAuthService = pddAuthService;
}
@Operation(summary = "获取授权跳转 URL", description = "为指定内部店铺生成拼多多授权页链接,前端新窗口打开后引导商家授权")
@GetMapping("/authorize-url")
@RequirePermission(value = "biz:pdd:auth:manage", description = "拼多多授权管理", allowSuper = true)
public ApiResponse<PddAuthorizeUrlVO> authorizeUrl(
@Parameter(description = "内部店铺 ID(ec_shop.id)", required = true)
@RequestParam("shopId") Long shopId) {
return ApiResponse.success(pddAuthService.buildAuthorizeUrl(shopId));
}
@Operation(summary = "授权回调", description = "拼多多回调入口:接收 code 换取 token、绑定内部店铺,返回提示 HTML(3 秒后关闭)")
@GetMapping(value = "/callback", produces = MediaType.TEXT_HTML_VALUE)
public ResponseEntity<String> callback(
@Parameter(description = "授权码") @RequestParam(value = "code", required = false) String code,
@Parameter(description = "自定义 state") @RequestParam(value = "state", required = false) String state) {
String html = pddAuthService.handleCallback(code, state);
return ResponseEntity.ok()
.contentType(MediaType.TEXT_HTML)
.body(html);
}
}
@@ -0,0 +1,9 @@
package top.xyquan.ecomdmbbackend.modules.ecom.pdd.auth.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.auth.model.po.PddAuthPO;
@Mapper
public interface PddAuthMapper extends BaseMapper<PddAuthPO> {
}
@@ -0,0 +1,58 @@
package top.xyquan.ecomdmbbackend.modules.ecom.pdd.auth.model.po;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.time.LocalDateTime;
/**
* 拼多多 OAuth 授权凭证
*/
@Data
@TableName("ec_pdd_auth")
public class PddAuthPO {
@TableId(value = "id", type = IdType.AUTO)
private Long id;
@TableField("company_id")
private Long companyId;
/** 拼多多授权主体 ID(等同 mall_id) */
@TableField("owner_id")
private String ownerId;
@TableField("access_token")
private String accessToken;
@TableField("refresh_token")
private String refreshToken;
@TableField("expires_at")
private LocalDateTime expiresAt;
@TableField("refresh_token_expires_at")
private LocalDateTime refreshTokenExpiresAt;
/** scope JSON 数组字符串 */
@TableField("scope")
private String scope;
/** 最近一次授权完整响应 JSON */
@TableField("raw_response")
private String rawResponse;
/** 状态:0=失效 1=正常 2=已撤销 */
@TableField("status")
private Integer status;
@TableField(value = "create_time", fill = FieldFill.INSERT)
private LocalDateTime createTime;
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
}
@@ -0,0 +1,17 @@
package top.xyquan.ecomdmbbackend.modules.ecom.pdd.auth.model.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Builder;
import lombok.Data;
@Data
@Builder
@Schema(description = "拼多多授权跳转信息")
public class PddAuthorizeUrlVO {
@Schema(description = "拼多多授权页完整 URL,前端直接打开")
private String authorizeUrl;
@Schema(description = "本次授权 state(调试用;回调时拼多多会原样带回)")
private String state;
}
@@ -0,0 +1,23 @@
package top.xyquan.ecomdmbbackend.modules.ecom.pdd.auth.service;
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.auth.model.vo.PddAuthorizeUrlVO;
/**
* 拼多多 OAuth 授权服务
*/
public interface PddAuthService {
/**
* 生成授权跳转 URL(需登录;绑定指定内部店铺)
*
* @param shopId 内部店铺 ID(ec_shop.id)
*/
PddAuthorizeUrlVO buildAuthorizeUrl(Long shopId);
/**
* 处理授权回调:用 code 换 token、同步 PDD 店铺,并将外部店绑定到 state 中的内部店铺
*
* @return 提示用 HTML 页面(3 秒后尝试关闭窗口)
*/
String handleCallback(String code, String state);
}
@@ -0,0 +1,39 @@
package top.xyquan.ecomdmbbackend.modules.ecom.pdd.auth.service;
import com.pdd.pop.sdk.http.PopClient;
import com.pdd.pop.sdk.http.PopHttpClient;
import com.pdd.pop.sdk.http.PopAccessTokenClient;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.auth.config.PddOAuthProperties;
/**
* 拼多多 POP SDK 客户端工厂
*/
@Component
public class PddPopClientFactory {
private final PddOAuthProperties properties;
public PddPopClientFactory(PddOAuthProperties properties) {
this.properties = properties;
}
public PopAccessTokenClient createAccessTokenClient() {
assertConfigured();
return new PopAccessTokenClient(properties.getClientId(), properties.getClientSecret());
}
public PopClient createHttpClient() {
assertConfigured();
return new PopHttpClient(properties.getClientId(), properties.getClientSecret());
}
private void assertConfigured() {
if (!StringUtils.hasText(properties.getClientId())
|| !StringUtils.hasText(properties.getClientSecret())) {
throw new BusinessException("拼多多 OAuth 未配置 client-id / client-secret");
}
}
}
@@ -0,0 +1,502 @@
package top.xyquan.ecomdmbbackend.modules.ecom.pdd.auth.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.pdd.pop.sdk.http.PopAccessTokenClient;
import com.pdd.pop.sdk.http.PopClient;
import com.pdd.pop.sdk.http.api.pop.request.PddMallInfoGetRequest;
import com.pdd.pop.sdk.http.api.pop.response.PddMallInfoGetResponse;
import com.pdd.pop.sdk.http.token.AccessTokenResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.util.HtmlUtils;
import org.springframework.web.util.UriComponentsBuilder;
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.auth.config.PddOAuthProperties;
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.auth.mapper.PddAuthMapper;
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.auth.model.po.PddAuthPO;
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.auth.model.vo.PddAuthorizeUrlVO;
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.auth.service.PddAuthService;
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.auth.service.PddPopClientFactory;
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.shop.mapper.PddShopMapper;
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.shop.model.po.PddShopPO;
import top.xyquan.ecomdmbbackend.modules.ecom.platform.mapper.PlatformMapper;
import top.xyquan.ecomdmbbackend.modules.ecom.platform.model.po.PlatformPO;
import top.xyquan.ecomdmbbackend.modules.ecom.shop.mapper.ShopMapper;
import top.xyquan.ecomdmbbackend.modules.ecom.shop.model.po.ShopPO;
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
/**
* 拼多多 OAuth 授权服务实现:生成授权链接、处理回调换票、同步外部店并绑定内部店。
*/
@Slf4j
@Service
public class PddAuthServiceImpl implements PddAuthService {
private static final String STATE_KEY_PREFIX = "pdd:oauth:state:";
private static final String PLATFORM_CODE_PDD = "pdd";
private final PddOAuthProperties properties;
private final PddPopClientFactory popClientFactory;
private final StringRedisTemplate stringRedisTemplate;
private final CurrentUserContext currentUserContext;
private final PddAuthMapper pddAuthMapper;
private final PddShopMapper pddShopMapper;
private final ShopMapper shopMapper;
private final PlatformMapper platformMapper;
private final ObjectMapper objectMapper;
public PddAuthServiceImpl(PddOAuthProperties properties,
PddPopClientFactory popClientFactory,
StringRedisTemplate stringRedisTemplate,
CurrentUserContext currentUserContext,
PddAuthMapper pddAuthMapper,
PddShopMapper pddShopMapper,
ShopMapper shopMapper,
PlatformMapper platformMapper,
ObjectMapper objectMapper) {
this.properties = properties;
this.popClientFactory = popClientFactory;
this.stringRedisTemplate = stringRedisTemplate;
this.currentUserContext = currentUserContext;
this.pddAuthMapper = pddAuthMapper;
this.pddShopMapper = pddShopMapper;
this.shopMapper = shopMapper;
this.platformMapper = platformMapper;
this.objectMapper = objectMapper;
}
/**
* 为指定内部店铺生成拼多多授权跳转 URL,并将 companyId/userId/shopId 写入 Redis state。
*/
@Override
public PddAuthorizeUrlVO buildAuthorizeUrl(Long shopId) {
assertOAuthConfigured();
if (!StringUtils.hasText(properties.getRedirectUri())) {
throw new BusinessException("拼多多 OAuth 未配置 redirect-uri");
}
if (shopId == null) {
throw new BusinessException("请指定要授权绑定的内部店铺");
}
Long companyId = currentUserContext.getCurrentCompanyId();
Long userId = currentUserContext.getCurrentUserId();
validateInternalShopForAuth(companyId, shopId);
String state = UUID.randomUUID().toString().replace("-", "");
Map<String, Object> payload = new HashMap<>();
payload.put("companyId", companyId);
payload.put("userId", userId);
payload.put("shopId", shopId);
try {
stringRedisTemplate.opsForValue().set(
STATE_KEY_PREFIX + state,
objectMapper.writeValueAsString(payload),
properties.getStateTtlSeconds(),
TimeUnit.SECONDS);
} catch (JsonProcessingException e) {
throw new BusinessException("写入授权 state 失败");
}
String authorizeUrl = UriComponentsBuilder
.fromHttpUrl(properties.getAuthorizeUrl())
.queryParam("response_type", "code")
.queryParam("client_id", properties.getClientId())
.queryParam("redirect_uri", properties.getRedirectUri())
.queryParam("state", state)
.encode()
.build()
.toUriString();
return PddAuthorizeUrlVO.builder()
.authorizeUrl(authorizeUrl)
.state(state)
.build();
}
/**
* 处理拼多多授权回调:校验并消费 state → code 换 token → 落库授权与外部店 → 绑定内部店 → 返回提示 HTML。
*/
@Override
@Transactional(rollbackFor = Exception.class)
public String handleCallback(String code, String state) {
try {
if (!StringUtils.hasText(code)) {
return buildResultHtml(false, "缺少授权码 code");
}
if (!StringUtils.hasText(state)) {
return buildResultHtml(false, "缺少 state");
}
String stateKey = STATE_KEY_PREFIX + state;
String stateJson = stringRedisTemplate.opsForValue().get(stateKey);
if (!StringUtils.hasText(stateJson)) {
return buildResultHtml(false, "授权状态无效或已过期,请重新发起授权");
}
stringRedisTemplate.delete(stateKey);
@SuppressWarnings("unchecked")
Map<String, Object> statePayload = objectMapper.readValue(stateJson, Map.class);
Long companyId = toLong(statePayload.get("companyId"));
Long userId = toLong(statePayload.get("userId"));
Long shopId = toLong(statePayload.get("shopId"));
if (companyId == null || userId == null || shopId == null) {
return buildResultHtml(false, "授权状态数据不完整,请重新发起授权");
}
AccessTokenResponse tokenResponse = exchangeCode(code);
if (tokenResponse == null || !StringUtils.hasText(tokenResponse.getAccessToken())) {
return buildResultHtml(false, "换取 access_token 失败");
}
if (tokenResponse.getErrorResponse() != null) {
String msg = tokenResponse.getErrorResponse().getErrorMsg();
log.warn("拼多多换票失败: {}", msg);
return buildResultHtml(false, "换取 access_token 失败" + (StringUtils.hasText(msg) ? ":" + msg : ""));
}
if (!StringUtils.hasText(tokenResponse.getOwnerId())) {
return buildResultHtml(false, "授权响应缺少店铺 owner_id");
}
PddAuthPO auth = upsertAuth(companyId, tokenResponse);
PddMallInfoGetResponse.MallInfoGetResponse mallInfo = fetchMallInfo(tokenResponse.getAccessToken());
Long mallId = resolveMallId(tokenResponse.getOwnerId(), mallInfo);
if (mallId == null) {
return buildResultHtml(false, "无法解析拼多多店铺 mall_id");
}
upsertPddShop(companyId, auth.getId(), mallId, mallInfo, tokenResponse.getOwnerName());
bindInternalShop(companyId, userId, shopId, mallId, mallInfo, tokenResponse.getOwnerName());
String shopName = firstNonBlank(
mallInfo != null ? mallInfo.getMallName() : null,
tokenResponse.getOwnerName(),
"PDD-" + mallId);
return buildResultHtml(true, "授权成功,已绑定店铺「" + shopName + "」(mall_id=" + mallId + ")");
} catch (BusinessException e) {
log.warn("拼多多授权回调业务失败: {}", e.getMessage());
return buildResultHtml(false, e.getMessage());
} catch (Exception e) {
log.error("拼多多授权回调异常", e);
return buildResultHtml(false, "授权处理异常,请稍后重试");
}
}
/**
* 校验内部店铺存在、属于当前公司,且平台为拼多多。
*/
private void validateInternalShopForAuth(Long companyId, Long shopId) {
ShopPO shop = shopMapper.selectById(shopId);
if (shop == null || !companyId.equals(shop.getCompanyId())) {
throw new BusinessException("内部店铺不存在或不属于当前公司");
}
PlatformPO platform = platformMapper.selectById(shop.getPlatformId());
if (platform == null || !PLATFORM_CODE_PDD.equals(platform.getPlatformCode())) {
throw new BusinessException("仅支持对拼多多平台的内部店铺发起授权");
}
}
/**
* 使用授权码向拼多多换取 access_token。
*/
private AccessTokenResponse exchangeCode(String code) throws Exception {
PopAccessTokenClient client = popClientFactory.createAccessTokenClient();
try {
return client.generate(code);
} finally {
try {
client.destroy();
} catch (Exception ignored) {
// ignore
}
}
}
/**
* 按 company_id + owner_id 新增或覆盖写入 ec_pdd_auth(重复授权会使旧 token 失效)。
*/
private PddAuthPO upsertAuth(Long companyId, AccessTokenResponse token) {
LocalDateTime now = LocalDateTime.now();
LocalDateTime expiresAt = plusSeconds(now, token.getExpiresIn());
// AccessTokenResponse 无 refresh 过期秒数时,与 access 同 TTL 兜底
LocalDateTime refreshExpiresAt = plusSeconds(now, token.getExpiresIn());
LambdaQueryWrapper<PddAuthPO> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(PddAuthPO::getCompanyId, companyId)
.eq(PddAuthPO::getOwnerId, token.getOwnerId());
PddAuthPO existing = pddAuthMapper.selectOne(wrapper);
PddAuthPO auth = existing != null ? existing : new PddAuthPO();
auth.setCompanyId(companyId);
auth.setOwnerId(token.getOwnerId());
auth.setAccessToken(token.getAccessToken());
auth.setRefreshToken(token.getRefreshToken());
auth.setExpiresAt(expiresAt);
auth.setRefreshTokenExpiresAt(refreshExpiresAt);
auth.setScope(writeJson(token.getScope()));
auth.setRawResponse(writeJson(token));
auth.setStatus(1);
if (existing == null) {
pddAuthMapper.insert(auth);
} else {
pddAuthMapper.updateById(auth);
}
return auth;
}
/**
* 调用 pdd.mall.info.get 拉取拼多多店铺详情;失败时返回 null(由调用方用 owner 信息兜底)。
*/
private PddMallInfoGetResponse.MallInfoGetResponse fetchMallInfo(String accessToken) {
try {
PopClient client = popClientFactory.createHttpClient();
PddMallInfoGetResponse response = client.syncInvoke(new PddMallInfoGetRequest(), accessToken);
if (response == null) {
return null;
}
if (response.getErrorResponse() != null) {
log.warn("pdd.mall.info.get 失败: {}", response.getErrorResponse().getErrorMsg());
return null;
}
return response.getMallInfoGetResponse();
} catch (Exception e) {
log.warn("调用 pdd.mall.info.get 异常: {}", e.getMessage());
return null;
}
}
/**
* 解析 mall_id:优先使用 mall.info 返回值,否则将 owner_id 解析为 Long。
*/
private Long resolveMallId(String ownerId, PddMallInfoGetResponse.MallInfoGetResponse mallInfo) {
if (mallInfo != null && mallInfo.getMallId() != null) {
return mallInfo.getMallId();
}
try {
return Long.parseLong(ownerId.trim());
} catch (NumberFormatException e) {
return null;
}
}
/**
* 按 company_id + mall_id 新增或更新 ec_pdd_shop,并绑定 pdd_auth_id。
*/
private void upsertPddShop(Long companyId,
Long authId,
Long mallId,
PddMallInfoGetResponse.MallInfoGetResponse mallInfo,
String ownerName) {
LambdaQueryWrapper<PddShopPO> byMall = new LambdaQueryWrapper<>();
byMall.eq(PddShopPO::getCompanyId, companyId).eq(PddShopPO::getMallId, mallId);
PddShopPO shop = pddShopMapper.selectOne(byMall);
// 若该授权已绑其他店铺,先解绑(uk_ec_pdd_shop_auth)
LambdaQueryWrapper<PddShopPO> byAuth = new LambdaQueryWrapper<>();
byAuth.eq(PddShopPO::getPddAuthId, authId);
PddShopPO authBound = pddShopMapper.selectOne(byAuth);
if (authBound != null && (shop == null || !authBound.getId().equals(shop.getId()))) {
authBound.setPddAuthId(null);
pddShopMapper.updateById(authBound);
}
if (shop == null) {
shop = new PddShopPO();
shop.setCompanyId(companyId);
shop.setMallId(mallId);
}
shop.setPddAuthId(authId);
shop.setMallName(firstNonBlank(
mallInfo != null ? mallInfo.getMallName() : null,
ownerName,
"PDD-" + mallId));
if (mallInfo != null) {
shop.setLogo(mallInfo.getLogo());
shop.setMallDesc(mallInfo.getMallDesc());
if (mallInfo.getMerchantType() != null) {
shop.setMerchantType(mallInfo.getMerchantType());
}
if (mallInfo.getMallCharacter() != null) {
shop.setMallCharacter(mallInfo.getMallCharacter());
}
}
if (shop.getMerchantType() == null) {
shop.setMerchantType(6);
}
if (shop.getMallCharacter() == null) {
shop.setMallCharacter(2);
}
shop.setLastSyncTime(LocalDateTime.now());
if (shop.getId() == null) {
pddShopMapper.insert(shop);
} else {
pddShopMapper.updateById(shop);
}
}
/**
* 将拼多多 mall_id 写入指定内部店铺的 external_shop_id;若已被其他内部店占用则先解绑再改绑。
*/
private void bindInternalShop(Long companyId,
Long userId,
Long shopId,
Long mallId,
PddMallInfoGetResponse.MallInfoGetResponse mallInfo,
String ownerName) {
ShopPO shop = shopMapper.selectById(shopId);
if (shop == null || !companyId.equals(shop.getCompanyId())) {
throw new BusinessException("授权关联的内部店铺不存在或不属于当前公司");
}
PlatformPO platform = platformMapper.selectById(shop.getPlatformId());
if (platform == null || !PLATFORM_CODE_PDD.equals(platform.getPlatformCode())) {
throw new BusinessException("内部店铺不是拼多多平台,无法绑定");
}
String externalShopId = String.valueOf(mallId);
// 同一公司+平台下外部店 ID 唯一:若已被其他内部店占用则解绑
ShopPO occupied = shopMapper.selectOne(new LambdaQueryWrapper<ShopPO>()
.eq(ShopPO::getCompanyId, companyId)
.eq(ShopPO::getPlatformId, shop.getPlatformId())
.eq(ShopPO::getExternalShopId, externalShopId)
.ne(ShopPO::getId, shopId)
.last("LIMIT 1"));
if (occupied != null) {
shopMapper.update(null, new LambdaUpdateWrapper<ShopPO>()
.eq(ShopPO::getId, occupied.getId())
.set(ShopPO::getExternalShopId, null)
.set(ShopPO::getUpdateBy, userId));
log.info("拼多多外部店 {} 从内部店 {} 解绑,改绑至 {}", externalShopId, occupied.getId(), shopId);
}
shop.setExternalShopId(externalShopId);
String mallName = firstNonBlank(
mallInfo != null ? mallInfo.getMallName() : null,
ownerName);
if (StringUtils.hasText(mallName)) {
shop.setName(mallName);
}
shop.setUpdateBy(userId);
shopMapper.updateById(shop);
}
/**
* 校验 OAuth client-id / client-secret 已配置。
*/
private void assertOAuthConfigured() {
if (!StringUtils.hasText(properties.getClientId())
|| !StringUtils.hasText(properties.getClientSecret())) {
throw new BusinessException("拼多多 OAuth 未配置 client-id / client-secret");
}
}
/**
* 构造授权结果提示页 HTML(成功/失败),3 秒后尝试关闭窗口。
*/
private static String buildResultHtml(boolean success, String message) {
String title = success ? "授权成功" : "授权失败";
String color = success ? "#067d3f" : "#b42318";
String safeMessage = HtmlUtils.htmlEscape(message == null ? "" : message);
return """
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>%s</title>
<style>
body{font-family:system-ui,-apple-system,sans-serif;display:flex;align-items:center;justify-content:center;
min-height:100vh;margin:0;background:#f6f7f9;color:#1f2937}
.box{text-align:center;padding:28px 32px;background:#fff;border-radius:12px;
box-shadow:0 8px 24px rgba(15,23,42,.08);max-width:420px}
h1{margin:0 0 12px;font-size:22px;color:%s}
p{margin:0;line-height:1.6;color:#4b5563}
.hint{margin-top:16px;font-size:13px;color:#9ca3af}
</style>
</head>
<body>
<div class="box">
<h1>%s</h1>
<p>%s</p>
<p class="hint">本页将在 3 秒后自动关闭,若未关闭请手动关闭</p>
</div>
<script>setTimeout(function(){window.close();},3000);</script>
</body>
</html>
""".formatted(title, color, title, safeMessage);
}
/**
* 以当前时刻为基准加上 expires_in 秒,得到过期时间;非法值时默认 24 小时。
*/
private static LocalDateTime plusSeconds(LocalDateTime base, Integer seconds) {
if (seconds == null || seconds <= 0) {
return base.plusHours(24);
}
return LocalDateTime.ofInstant(
Instant.now().plusSeconds(seconds),
ZoneId.systemDefault());
}
/**
* 将对象序列化为 JSON 字符串;失败时返回 null。
*/
private String writeJson(Object value) {
if (value == null) {
return null;
}
try {
return objectMapper.writeValueAsString(value);
} catch (JsonProcessingException e) {
log.warn("序列化 JSON 失败: {}", e.getMessage());
return null;
}
}
/**
* 将 Redis/JSON 中的数值或字符串安全转为 Long。
*/
private static Long toLong(Object value) {
if (value == null) {
return null;
}
if (value instanceof Number number) {
return number.longValue();
}
try {
return Long.parseLong(String.valueOf(value));
} catch (NumberFormatException e) {
return null;
}
}
/**
* 返回参数中第一个非空白字符串。
*/
private static String firstNonBlank(String... values) {
if (values == null) {
return null;
}
for (String v : values) {
if (StringUtils.hasText(v)) {
return v;
}
}
return null;
}
}
@@ -11,10 +11,7 @@ import java.time.LocalDateTime;
@Schema(description = "创建拼多多店铺DTO") @Schema(description = "创建拼多多店铺DTO")
public class CreatePddShopDTO { public class CreatePddShopDTO {
@Schema(description = "内部店铺ID(ec_shop.id)") @Schema(description = "拼多多授权ID(ec_pdd_auth.id)")
private Long shopId;
@Schema(description = "拼多多授权ID(open_pdd_auth.id)")
private Long pddAuthId; private Long pddAuthId;
@Schema(description = "拼多多店铺ID(mall_id)", requiredMode = Schema.RequiredMode.REQUIRED) @Schema(description = "拼多多店铺ID(mall_id)", requiredMode = Schema.RequiredMode.REQUIRED)
@@ -16,9 +16,6 @@ public class PddShopFilterDTO {
@Schema(description = "店铺身份") @Schema(description = "店铺身份")
private Integer mallCharacter; private Integer mallCharacter;
@Schema(description = "内部店铺ID")
private Long shopId;
@Schema(description = "拼多多授权ID") @Schema(description = "拼多多授权ID")
private Long pddAuthId; private Long pddAuthId;
} }
@@ -11,10 +11,7 @@ import java.time.LocalDateTime;
@Schema(description = "更新拼多多店铺DTO") @Schema(description = "更新拼多多店铺DTO")
public class UpdatePddShopDTO { public class UpdatePddShopDTO {
@Schema(description = "内部店铺ID(ec_shop.id)") @Schema(description = "拼多多授权ID(ec_pdd_auth.id)")
private Long shopId;
@Schema(description = "拼多多授权ID(open_pdd_auth.id)")
private Long pddAuthId; private Long pddAuthId;
@Schema(description = "拼多多店铺ID(mall_id)", requiredMode = Schema.RequiredMode.REQUIRED) @Schema(description = "拼多多店铺ID(mall_id)", requiredMode = Schema.RequiredMode.REQUIRED)
@@ -1,6 +1,10 @@
package top.xyquan.ecomdmbbackend.modules.ecom.pdd.shop.model.po; package top.xyquan.ecomdmbbackend.modules.ecom.pdd.shop.model.po;
import com.baomidou.mybatisplus.annotation.*; import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data; import lombok.Data;
import java.time.LocalDateTime; import java.time.LocalDateTime;
@@ -15,9 +19,6 @@ public class PddShopPO {
@TableField("company_id") @TableField("company_id")
private Long companyId; private Long companyId;
@TableField("shop_id")
private Long shopId;
@TableField("pdd_auth_id") @TableField("pdd_auth_id")
private Long pddAuthId; private Long pddAuthId;
@@ -15,10 +15,7 @@ public class PddShopVO {
@Schema(description = "公司ID") @Schema(description = "公司ID")
private Long companyId; private Long companyId;
@Schema(description = "内部店铺ID(ec_shop.id)") @Schema(description = "拼多多授权ID(ec_pdd_auth.id)")
private Long shopId;
@Schema(description = "拼多多授权ID(open_pdd_auth.id)")
private Long pddAuthId; private Long pddAuthId;
@Schema(description = "拼多多店铺ID(mall_id)") @Schema(description = "拼多多店铺ID(mall_id)")
@@ -126,9 +126,6 @@ public class PddShopServiceImpl extends ServiceImpl<PddShopMapper, PddShopPO> im
if (filter.getMallCharacter() != null) { if (filter.getMallCharacter() != null) {
wrapper.eq(PddShopPO::getMallCharacter, filter.getMallCharacter()); wrapper.eq(PddShopPO::getMallCharacter, filter.getMallCharacter());
} }
if (filter.getShopId() != null) {
wrapper.eq(PddShopPO::getShopId, filter.getShopId());
}
if (filter.getPddAuthId() != null) { if (filter.getPddAuthId() != null) {
wrapper.eq(PddShopPO::getPddAuthId, filter.getPddAuthId()); wrapper.eq(PddShopPO::getPddAuthId, filter.getPddAuthId());
} }
@@ -68,7 +68,7 @@ public class ShopController {
return ApiResponse.success("店铺删除成功"); return ApiResponse.success("店铺删除成功");
} }
@Operation(summary = "分页获取店铺列表", description = "分页获取店铺列表,支持条件过滤") @Operation(summary = "分页获取店铺列表", description = "分页获取店铺列表,支持条件过滤;已绑定外部店时附带对应外部店铺 VO(如 pddShop)")
@PostMapping("/list") @PostMapping("/list")
@RequirePermission(value = "ecom:shop:read", description = "查询店铺列表", allowSuper = true) @RequirePermission(value = "ecom:shop:read", description = "查询店铺列表", allowSuper = true)
public ApiResponse<PageResultVO<ShopVO>> getShopPage( public ApiResponse<PageResultVO<ShopVO>> getShopPage(
@@ -29,4 +29,10 @@ public class CreateShopDTO {
*/ */
@Schema(description = "平台ID", example = "1") @Schema(description = "平台ID", example = "1")
private Long platformId; private Long platformId;
/**
* 外部店铺ID(平台侧店铺标识,如拼多多 mall_id)
*/
@Schema(description = "外部店铺ID(平台侧店铺标识,如拼多多 mall_id)", example = "123456789")
private String externalShopId;
} }
@@ -29,4 +29,10 @@ public class UpdateShopDTO {
*/ */
@Schema(description = "平台ID", example = "1") @Schema(description = "平台ID", example = "1")
private Long platformId; private Long platformId;
/**
* 外部店铺ID(平台侧店铺标识,如拼多多 mall_id)
*/
@Schema(description = "外部店铺ID(平台侧店铺标识,如拼多多 mall_id)", example = "123456789")
private String externalShopId;
} }
@@ -44,6 +44,12 @@ public class ShopPO {
@TableField("platform_id") @TableField("platform_id")
private Long platformId; private Long platformId;
/**
* 外部店铺ID(如拼多多 mall_id;与 platform_id 组合关联平台店铺)
*/
@TableField("external_shop_id")
private String externalShopId;
/** /**
* 创建时间 * 创建时间
*/ */
@@ -2,6 +2,7 @@ package top.xyquan.ecomdmbbackend.modules.ecom.shop.model.vo;
import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data; import lombok.Data;
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.shop.model.vo.PddShopVO;
import java.time.LocalDateTime; import java.time.LocalDateTime;
@@ -42,6 +43,18 @@ public class ShopVO {
@Schema(description = "平台ID", example = "1") @Schema(description = "平台ID", example = "1")
private Long platformId; private Long platformId;
/**
* 外部店铺ID(平台侧店铺标识,如拼多多 mall_id)
*/
@Schema(description = "外部店铺ID(平台侧店铺标识,如拼多多 mall_id)", example = "123456789")
private String externalShopId;
/**
* 关联的拼多多外部店铺(仅 platform=pdd 且已绑定 externalShopId 时有值)
*/
@Schema(description = "关联的拼多多外部店铺(已授权绑定时返回)")
private PddShopVO pddShop;
/** /**
* 平台名称 * 平台名称
*/ */
@@ -15,6 +15,9 @@ import top.xyquan.ecomdmbbackend.modules.ecom.brushorder.model.po.BrushOrderPO;
import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderMapper; import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderMapper;
import top.xyquan.ecomdmbbackend.modules.ecom.product.mapper.ProductMapper; import top.xyquan.ecomdmbbackend.modules.ecom.product.mapper.ProductMapper;
import top.xyquan.ecomdmbbackend.modules.ecom.promotion.mapper.PromotionFeeMapper; import top.xyquan.ecomdmbbackend.modules.ecom.promotion.mapper.PromotionFeeMapper;
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.shop.mapper.PddShopMapper;
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.shop.model.po.PddShopPO;
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.shop.model.vo.PddShopVO;
import top.xyquan.ecomdmbbackend.modules.ecom.platform.mapper.PlatformMapper; import top.xyquan.ecomdmbbackend.modules.ecom.platform.mapper.PlatformMapper;
import top.xyquan.ecomdmbbackend.modules.ecom.platform.model.po.PlatformPO; import top.xyquan.ecomdmbbackend.modules.ecom.platform.model.po.PlatformPO;
import top.xyquan.ecomdmbbackend.modules.ecom.shop.mapper.ShopMapper; import top.xyquan.ecomdmbbackend.modules.ecom.shop.mapper.ShopMapper;
@@ -48,7 +51,12 @@ import java.math.RoundingMode;
import java.time.LocalDate; import java.time.LocalDate;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors; import java.util.stream.Collectors;
/** /**
@@ -57,6 +65,8 @@ import java.util.stream.Collectors;
@Service @Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, ShopPO> implements ShopService { public class ShopServiceImpl extends ServiceImpl<ShopMapper, ShopPO> implements ShopService {
private static final String PLATFORM_CODE_PDD = "pdd";
private final CurrentUserContext currentUserContext; private final CurrentUserContext currentUserContext;
private final SysFileService sysFileService; private final SysFileService sysFileService;
private final OrderMapper orderMapper; private final OrderMapper orderMapper;
@@ -65,6 +75,7 @@ public class ShopServiceImpl extends ServiceImpl<ShopMapper, ShopPO> implements
private final ShopProductRelationMapper shopProductRelationMapper; private final ShopProductRelationMapper shopProductRelationMapper;
private final ProductSpecService productSpecService; private final ProductSpecService productSpecService;
private final PlatformMapper platformMapper; private final PlatformMapper platformMapper;
private final PddShopMapper pddShopMapper;
private final BrushOrderMapper brushOrderMapper; private final BrushOrderMapper brushOrderMapper;
private final ShopMonthlyTargetMapper shopMonthlyTargetMapper; private final ShopMonthlyTargetMapper shopMonthlyTargetMapper;
@@ -72,7 +83,7 @@ public class ShopServiceImpl extends ServiceImpl<ShopMapper, ShopPO> implements
OrderMapper orderMapper, PromotionFeeMapper promotionFeeMapper, OrderMapper orderMapper, PromotionFeeMapper promotionFeeMapper,
ProductMapper productMapper, ProductMapper productMapper,
ShopProductRelationMapper shopProductRelationMapper, ProductSpecService productSpecService, ShopProductRelationMapper shopProductRelationMapper, ProductSpecService productSpecService,
PlatformMapper platformMapper, PlatformMapper platformMapper, PddShopMapper pddShopMapper,
BrushOrderMapper brushOrderMapper, ShopMonthlyTargetMapper shopMonthlyTargetMapper) { BrushOrderMapper brushOrderMapper, ShopMonthlyTargetMapper shopMonthlyTargetMapper) {
this.currentUserContext = currentUserContext; this.currentUserContext = currentUserContext;
this.sysFileService = sysFileService; this.sysFileService = sysFileService;
@@ -82,6 +93,7 @@ public class ShopServiceImpl extends ServiceImpl<ShopMapper, ShopPO> implements
this.shopProductRelationMapper = shopProductRelationMapper; this.shopProductRelationMapper = shopProductRelationMapper;
this.productSpecService = productSpecService; this.productSpecService = productSpecService;
this.platformMapper = platformMapper; this.platformMapper = platformMapper;
this.pddShopMapper = pddShopMapper;
this.brushOrderMapper = brushOrderMapper; this.brushOrderMapper = brushOrderMapper;
this.shopMonthlyTargetMapper = shopMonthlyTargetMapper; this.shopMonthlyTargetMapper = shopMonthlyTargetMapper;
} }
@@ -218,11 +230,15 @@ public class ShopServiceImpl extends ServiceImpl<ShopMapper, ShopPO> implements
// 执行分页查询 // 执行分页查询
IPage<ShopPO> pageResult = this.page(page, wrapper); IPage<ShopPO> pageResult = this.page(page, wrapper);
List<ShopPO> records = pageResult.getRecords();
// 转换为VO // 批量加载平台,避免 N+1
List<ShopVO> voList = pageResult.getRecords().stream() Map<Long, PlatformPO> platformMap = loadPlatformMap(companyId, records);
.map(this::convertToVO)
List<ShopVO> voList = records.stream()
.map(shop -> convertToVO(shop, platformMap.get(shop.getPlatformId())))
.collect(Collectors.toList()); .collect(Collectors.toList());
fillExternalShops(voList, records, companyId, platformMap);
// 构建分页结果 // 构建分页结果
return PageResultVO.create(voList, pageResult.getTotal(), pageQueryDTO.getPage(), pageQueryDTO.getPageSize()); return PageResultVO.create(voList, pageResult.getTotal(), pageQueryDTO.getPage(), pageQueryDTO.getPageSize());
@@ -244,29 +260,120 @@ public class ShopServiceImpl extends ServiceImpl<ShopMapper, ShopPO> implements
} }
/** /**
* 转换为VO * 转换为VO(单条;创建/更新等场景)
*/ */
private ShopVO convertToVO(ShopPO shop) { private ShopVO convertToVO(ShopPO shop) {
PlatformPO platform = null;
if (shop.getPlatformId() != null) {
Long companyId = currentUserContext.getCurrentCompanyId();
platform = platformMapper.selectOne(new LambdaQueryWrapper<PlatformPO>()
.eq(PlatformPO::getId, shop.getPlatformId())
.eq(PlatformPO::getCompanyId, companyId));
}
ShopVO shopVO = convertToVO(shop, platform);
if (platform != null && PLATFORM_CODE_PDD.equals(platform.getPlatformCode())
&& shop.getExternalShopId() != null && !shop.getExternalShopId().isBlank()) {
Long mallId = parseMallId(shop.getExternalShopId());
if (mallId != null) {
PddShopPO pddShop = pddShopMapper.selectOne(new LambdaQueryWrapper<PddShopPO>()
.eq(PddShopPO::getCompanyId, shop.getCompanyId())
.eq(PddShopPO::getMallId, mallId)
.last("LIMIT 1"));
if (pddShop != null) {
shopVO.setPddShop(convertPddShopToVO(pddShop));
}
}
}
return shopVO;
}
private ShopVO convertToVO(ShopPO shop, PlatformPO platform) {
ShopVO shopVO = new ShopVO(); ShopVO shopVO = new ShopVO();
BeanCopyUtils.copyProperties(shop, shopVO); BeanCopyUtils.copyProperties(shop, shopVO);
if (shop.getLogoImageId() != null) { if (shop.getLogoImageId() != null) {
shopVO.setLogo(sysFileService.getFileAccessUrl(shop.getLogoImageId())); shopVO.setLogo(sysFileService.getFileAccessUrl(shop.getLogoImageId()));
} }
// 获取平台名称
if (shop.getPlatformId() != null) {
Long companyId = currentUserContext.getCurrentCompanyId();
LambdaQueryWrapper<PlatformPO> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(PlatformPO::getId, shop.getPlatformId())
.eq(PlatformPO::getCompanyId, companyId);
PlatformPO platform = platformMapper.selectOne(wrapper);
if (platform != null) { if (platform != null) {
shopVO.setPlatformName(platform.getPlatformName()); shopVO.setPlatformName(platform.getPlatformName());
} }
return shopVO;
} }
return shopVO; private Map<Long, PlatformPO> loadPlatformMap(Long companyId, List<ShopPO> shops) {
Set<Long> platformIds = shops.stream()
.map(ShopPO::getPlatformId)
.filter(Objects::nonNull)
.collect(Collectors.toSet());
if (platformIds.isEmpty()) {
return Collections.emptyMap();
}
List<PlatformPO> platforms = platformMapper.selectList(new LambdaQueryWrapper<PlatformPO>()
.eq(PlatformPO::getCompanyId, companyId)
.in(PlatformPO::getId, platformIds));
return platforms.stream().collect(Collectors.toMap(PlatformPO::getId, Function.identity(), (a, b) -> a));
}
/**
* 批量填充已绑定的外部店铺 VO(当前支持拼多多)
*/
private void fillExternalShops(List<ShopVO> voList,
List<ShopPO> shops,
Long companyId,
Map<Long, PlatformPO> platformMap) {
if (voList.isEmpty()) {
return;
}
Map<Long, ShopVO> voById = voList.stream()
.filter(v -> v.getId() != null)
.collect(Collectors.toMap(ShopVO::getId, Function.identity(), (a, b) -> a));
Map<Long, Long> shopIdToMallId = new HashMap<>();
for (ShopPO shop : shops) {
if (shop.getExternalShopId() == null || shop.getExternalShopId().isBlank()) {
continue;
}
PlatformPO platform = platformMap.get(shop.getPlatformId());
if (platform == null || !PLATFORM_CODE_PDD.equals(platform.getPlatformCode())) {
continue;
}
Long mallId = parseMallId(shop.getExternalShopId());
if (mallId != null) {
shopIdToMallId.put(shop.getId(), mallId);
}
}
if (shopIdToMallId.isEmpty()) {
return;
}
List<PddShopPO> pddShops = pddShopMapper.selectList(new LambdaQueryWrapper<PddShopPO>()
.eq(PddShopPO::getCompanyId, companyId)
.in(PddShopPO::getMallId, shopIdToMallId.values()));
Map<Long, PddShopVO> pddByMallId = pddShops.stream()
.collect(Collectors.toMap(PddShopPO::getMallId, this::convertPddShopToVO, (a, b) -> a));
shopIdToMallId.forEach((shopId, mallId) -> {
ShopVO vo = voById.get(shopId);
PddShopVO pddShop = pddByMallId.get(mallId);
if (vo != null && pddShop != null) {
vo.setPddShop(pddShop);
}
});
}
private static Long parseMallId(String externalShopId) {
try {
return Long.parseLong(externalShopId.trim());
} catch (NumberFormatException e) {
return null;
}
}
private PddShopVO convertPddShopToVO(PddShopPO pddShop) {
PddShopVO vo = new PddShopVO();
BeanCopyUtils.copyProperties(pddShop, vo);
return vo;
} }
/** /**
@@ -5,9 +5,9 @@ server:
spring: spring:
datasource: datasource:
url: jdbc:mysql://192.168.3.100:3306/ecom_dmb_test?characterEncoding=utf-8&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true&nullCatalogMeansCurrent=true url: jdbc:mysql://192.168.3.100:3306/ecom_dmb_dev?characterEncoding=utf-8&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true&nullCatalogMeansCurrent=true
username: ecom_dmb_test username: ecom_dmb_dev
password: ecom_dmb_test password: ecom_dmb_dev
data: data:
redis: redis:
host: 192.168.3.100 host: 192.168.3.100
@@ -125,6 +125,15 @@ oss:
endpoint: https://oss-cn-guangzhou.aliyuncs.com endpoint: https://oss-cn-guangzhou.aliyuncs.com
bucket-name: xyquan bucket-name: xyquan
# 拼多多开放平台 OAuth
pdd:
oauth:
client-id: 9b71d887c8dc4b46998dedfdeca9b866
client-secret: c626f640a6fd5f56b2c8c009a5eb2d5683e6b955
redirect-uri: https://ecbi.newloop.top/api-dev/ec/pdd/auth/callback
authorize-url: https://fuwu.pinduoduo.com/service-market/auth
state-ttl-seconds: 600
# License 授权(开关与公钥见 LicenseEnforcement 源码硬编码) # License 授权(开关与公钥见 LicenseEnforcement 源码硬编码)
ecom: ecom:
license: license:
@@ -109,6 +109,22 @@ INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status
SELECT 3400, (SELECT id FROM `sys_permission` WHERE `code` = 'MODULE:ecom' LIMIT 1), 'ecom:platform', '平台管理', 'module', 1, '', 330 SELECT 3400, (SELECT id FROM `sys_permission` WHERE `code` = 'MODULE:ecom' LIMIT 1), 'ecom:platform', '平台管理', 'module', 1, '', 330
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `code` = 'ecom:platform'); FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `code` = 'ecom:platform');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 3600, (SELECT id FROM `sys_permission` WHERE `code` = 'MODULE:ecom' LIMIT 1), 'biz:pdd', '拼多多', 'module', 1, '拼多多对接', 360
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `code` = 'biz:pdd');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 3601, (SELECT id FROM `sys_permission` WHERE `code` = 'biz:pdd' LIMIT 1), 'biz:pdd:auth:manage', '拼多多授权管理', 'api', 1, '生成授权链接/管理授权', 361
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `code` = 'biz:pdd:auth:manage');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 3602, (SELECT id FROM `sys_permission` WHERE `code` = 'biz:pdd' LIMIT 1), 'biz:pdd:shop:read', '拼多多店铺查看', 'api', 1, '', 362
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `code` = 'biz:pdd:shop:read');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 3603, (SELECT id FROM `sys_permission` WHERE `code` = 'biz:pdd' LIMIT 1), 'biz:pdd:shop:manage', '拼多多店铺管理', 'api', 1, '', 363
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `code` = 'biz:pdd:shop:manage');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`) INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 4100, (SELECT id FROM `sys_permission` WHERE `code` = 'MODULE:data' LIMIT 1), 'data:import-group', '数据导入', 'module', 1, '', 400 SELECT 4100, (SELECT id FROM `sys_permission` WHERE `code` = 'MODULE:data' LIMIT 1), 'data:import-group', '数据导入', 'module', 1, '', 400
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `code` = 'data:import-group'); FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `code` = 'data:import-group');
@@ -0,0 +1,12 @@
import type { PddAuthVO } from './types';
import { requestClient } from '#/api/request';
/**
* 获取拼多多店铺授权跳转 URL(绑定指定内部店铺)
*/
export async function getPddAuthorizeUrlApi(shopId: number) {
return requestClient.get<PddAuthVO.AuthorizeUrl>('/ec/pdd/auth/authorize-url', {
params: { shopId },
});
}
@@ -0,0 +1,2 @@
export * from './apis';
export * from './types';
@@ -0,0 +1 @@
export * from './types.vo';
@@ -0,0 +1,12 @@
/**
* 拼多多授权相关 VO
*/
export namespace PddAuthVO {
/** 授权跳转信息 */
export interface AuthorizeUrl {
/** 拼多多授权页完整 URL */
authorizeUrl: string;
/** 本次授权 state */
state: string;
}
}
@@ -2,6 +2,34 @@
* 店铺相关VO类型定义 * 店铺相关VO类型定义
*/ */
/** 拼多多外部店铺信息(列表关联返回) */
export interface PddShopInfo {
/** 主键ID */
id: number;
/** 公司ID */
companyId: number;
/** 拼多多授权ID */
pddAuthId?: null | number;
/** 拼多多店铺ID(mall_id) */
mallId: number;
/** 店铺名称 */
mallName?: string;
/** 店铺logo */
logo?: string;
/** 店铺描述 */
mallDesc?: string;
/** 店铺类型:1个人 2企业 3旗舰店 4专卖店 5专营店 6普通店 */
merchantType?: number;
/** 店铺身份:0厂商 1分销商 2都不是 3都是 */
mallCharacter?: number;
/** 最近一次同步时间 */
lastSyncTime?: string;
/** 创建时间 */
createTime?: string;
/** 更新时间 */
updateTime?: string;
}
export namespace ShopVO { export namespace ShopVO {
/** 店铺信息 */ /** 店铺信息 */
export interface Info { export interface Info {
@@ -19,6 +47,10 @@ export namespace ShopVO {
platformId?: number; platformId?: number;
/** 平台名称 */ /** 平台名称 */
platformName?: string; platformName?: string;
/** 外部店铺ID(如拼多多 mall_id) */
externalShopId?: null | string;
/** 关联的拼多多外部店铺(已授权绑定时返回) */
pddShop?: null | PddShopInfo;
/** 创建时间 */ /** 创建时间 */
createTime: string; createTime: string;
/** 更新时间 */ /** 更新时间 */
@@ -0,0 +1,107 @@
<script lang="ts" setup>
import type { PddShopInfo } from '#/api/ecommerce/shop/types';
import { computed, ref } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { Descriptions, Tag } from 'ant-design-vue';
const MERCHANT_TYPE_MAP: Record<number, string> = {
1: '个人',
2: '企业',
3: '旗舰店',
4: '专卖店',
5: '专营店',
6: '普通店',
};
const MALL_CHARACTER_MAP: Record<number, string> = {
0: '厂商',
1: '分销商',
2: '都不是',
3: '都是',
};
const pddShop = ref<null | PddShopInfo>(null);
const internalShopName = ref('');
const [Modal, modalApi] = useVbenModal({
draggable: true,
class: 'w-[640px]',
showConfirmButton: false,
cancelText: '关闭',
});
const merchantTypeLabel = computed(() => {
const type = pddShop.value?.merchantType;
if (type == null) return '-';
return MERCHANT_TYPE_MAP[type] ?? String(type);
});
const mallCharacterLabel = computed(() => {
const character = pddShop.value?.mallCharacter;
if (character == null) return '-';
return MALL_CHARACTER_MAP[character] ?? String(character);
});
function open(shop: PddShopInfo, shopName?: string) {
pddShop.value = shop;
internalShopName.value = shopName || '';
modalApi.open();
}
defineExpose({ open });
</script>
<template>
<Modal title="拼多多外部店铺" content-class="px-5 py-4">
<div v-if="pddShop" class="space-y-4">
<div class="flex items-center gap-3">
<img
v-if="pddShop.logo"
:src="pddShop.logo"
:alt="pddShop.mallName"
class="h-14 w-14 rounded-md border border-slate-200 object-cover"
/>
<div>
<div class="text-base font-medium">
{{ pddShop.mallName || '-' }}
</div>
<div v-if="internalShopName" class="mt-1 text-xs text-slate-500">
内部店铺:{{ internalShopName }}
</div>
</div>
</div>
<Descriptions :column="1" bordered size="small">
<Descriptions.Item label="mall_id">
{{ pddShop.mallId }}
</Descriptions.Item>
<Descriptions.Item label="授权状态">
<Tag :color="pddShop.pddAuthId ? 'success' : 'default'">
{{ pddShop.pddAuthId ? '已绑定授权' : '未绑定授权' }}
</Tag>
</Descriptions.Item>
<Descriptions.Item label="店铺类型">
{{ merchantTypeLabel }}
</Descriptions.Item>
<Descriptions.Item label="店铺身份">
{{ mallCharacterLabel }}
</Descriptions.Item>
<Descriptions.Item label="店铺描述">
{{ pddShop.mallDesc || '-' }}
</Descriptions.Item>
<Descriptions.Item label="最近同步">
{{ pddShop.lastSyncTime || '-' }}
</Descriptions.Item>
<Descriptions.Item label="创建时间">
{{ pddShop.createTime || '-' }}
</Descriptions.Item>
<Descriptions.Item label="更新时间">
{{ pddShop.updateTime || '-' }}
</Descriptions.Item>
</Descriptions>
</div>
</Modal>
</template>
@@ -1,44 +1,48 @@
<script lang="ts" setup> <script lang="ts" setup>
import type { VxeGridProps } from '#/adapter/vxe-table'; import type { VxeGridProps } from '#/adapter/vxe-table';
import type { PlatformVO } from '#/api/ecommerce/platform/types';
import type { ShopDTO, ShopVO } from '#/api/ecommerce/shop/types'; import type { ShopDTO, ShopVO } from '#/api/ecommerce/shop/types';
import type { PageQueryDTO } from '#/types/common'; import type { PageQueryDTO } from '#/types/common';
import { computed, ref } from 'vue'; import { computed, onMounted, onUnmounted, ref } from 'vue';
import { useRouter } from 'vue-router'; import { useRouter } from 'vue-router';
import { Page } from '@vben/common-ui'; import { Page } from '@vben/common-ui';
import { createIconifyIcon } from '@vben/icons'; import { createIconifyIcon } from '@vben/icons';
import { Button, message, Popconfirm, Space } from 'ant-design-vue'; import { Button, message, Popconfirm, Space, Tag } from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table'; import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { getPddAuthorizeUrlApi } from '#/api/ecommerce/pdd/auth';
import { getActivePlatformsApi } from '#/api/ecommerce/platform';
import { deleteShopApi, getShopPageApi } from '#/api/ecommerce/shop'; import { deleteShopApi, getShopPageApi } from '#/api/ecommerce/shop';
import PddShopDetailModal from './components/PddShopDetailModal.vue';
import ShopFormModal from './components/ShopFormModal.vue'; import ShopFormModal from './components/ShopFormModal.vue';
defineOptions({ name: 'ShopManagement' }); defineOptions({ name: 'ShopManagement' });
const PLATFORM_CODE_PDD = 'pdd';
const router = useRouter(); const router = useRouter();
// 创建图标组件
const PlusIcon = createIconifyIcon('lucide:plus'); const PlusIcon = createIconifyIcon('lucide:plus');
// 响应式数据
const loading = ref(false); const loading = ref(false);
const authorizing = ref(false);
const shopFormModalRef = ref(); const shopFormModalRef = ref();
const pddShopDetailModalRef = ref();
// 搜索表单
const searchForm = ref({ const searchForm = ref({
name: '', name: '',
platformId: undefined as number | undefined, platformId: undefined as number | undefined,
}); });
// 表单数据(已移至ShopFormModal组件)
// 平台选项(动态加载)
const platformOptions = ref<{ label: string; value: number }[]>([]); const platformOptions = ref<{ label: string; value: number }[]>([]);
const platformCodeById = ref<Record<number, string>>({});
let authPollTimer: null | ReturnType<typeof setInterval> = null;
// VbenVxeGrid 表格配置
const gridOptions: VxeGridProps<any> = { const gridOptions: VxeGridProps<any> = {
columns: [ columns: [
{ {
@@ -66,6 +70,12 @@ const gridOptions: VxeGridProps<any> = {
minWidth: 120, minWidth: 120,
showOverflow: true, showOverflow: true,
}, },
{
title: '外部店铺',
minWidth: 180,
showOverflow: false,
slots: { default: 'externalShop' },
},
{ {
field: 'createTime', field: 'createTime',
title: '创建时间', title: '创建时间',
@@ -78,7 +88,7 @@ const gridOptions: VxeGridProps<any> = {
}, },
{ {
title: '操作', title: '操作',
minWidth: 'auto', minWidth: 360,
fixed: 'right' as const, fixed: 'right' as const,
slots: { default: 'action' }, slots: { default: 'action' },
}, },
@@ -86,7 +96,6 @@ const gridOptions: VxeGridProps<any> = {
height: 'auto', height: 'auto',
border: true, border: true,
stripe: true, stripe: true,
// 行高需容纳店铺 Logo(与商品表一致)
rowConfig: { rowConfig: {
isHover: true, isHover: true,
height: 88, height: 88,
@@ -122,7 +131,6 @@ const gridOptions: VxeGridProps<any> = {
| 'Total' | 'Total'
)[], )[],
}, },
// 配置远程加载
proxyConfig: { proxyConfig: {
ajax: { ajax: {
query: async ({ page }) => { query: async ({ page }) => {
@@ -156,7 +164,6 @@ const gridOptions: VxeGridProps<any> = {
}, },
}; };
// 搜索表单配置
const gridReloadRef = ref<(() => void) | null>(null); const gridReloadRef = ref<(() => void) | null>(null);
const formOptions = computed(() => ({ const formOptions = computed(() => ({
schema: [ schema: [
@@ -173,7 +180,7 @@ const formOptions = computed(() => ({
component: 'Select', component: 'Select',
componentProps: { componentProps: {
placeholder: '请选择平台', placeholder: '请选择平台',
options: platformOptions, options: platformOptions.value,
allowClear: true, allowClear: true,
onChange: (val: any) => { onChange: (val: any) => {
searchForm.value.platformId = val; searchForm.value.platformId = val;
@@ -189,7 +196,6 @@ const formOptions = computed(() => ({
collapsedRows: 1, collapsedRows: 1,
})); }));
// 创建 VbenVxeGrid 实例
const [Grid, gridApi] = useVbenVxeGrid({ const [Grid, gridApi] = useVbenVxeGrid({
gridOptions, gridOptions,
formOptions: formOptions.value, formOptions: formOptions.value,
@@ -198,24 +204,53 @@ const [Grid, gridApi] = useVbenVxeGrid({
}); });
gridReloadRef.value = () => gridApi.reload(); gridReloadRef.value = () => gridApi.reload();
// 刷新表格数据 async function fetchPlatformOptions() {
function refreshTable() { try {
if (gridApi) { const data = await getActivePlatformsApi();
gridApi.reload(); platformOptions.value = data.map((p: PlatformVO.Info) => ({
label: p.platformName,
value: p.id,
}));
const codeMap: Record<number, string> = {};
data.forEach((p: PlatformVO.Info) => {
codeMap[p.id] = p.platformCode;
});
platformCodeById.value = codeMap;
await gridApi.formApi?.updateSchema([
{
fieldName: 'platformId',
componentProps: {
options: platformOptions.value,
},
},
]);
} catch (error) {
console.error('获取平台列表失败:', error);
} }
} }
// 处理添加店铺 function refreshTable() {
gridApi?.reload();
}
function isPddShop(row: ShopVO.Info) {
if (!row.platformId) return false;
return platformCodeById.value[row.platformId] === PLATFORM_CODE_PDD;
}
function hasExternalShop(row: ShopVO.Info) {
return Boolean(row.pddShop || row.externalShopId);
}
function handleAdd() { function handleAdd() {
shopFormModalRef.value?.open(false); shopFormModalRef.value?.open(false);
} }
// 处理编辑店铺
function handleEdit(record: ShopVO.Info) { function handleEdit(record: ShopVO.Info) {
shopFormModalRef.value?.open(true, record); shopFormModalRef.value?.open(true, record);
} }
// 处理删除店铺
async function handleDelete(record: ShopVO.Info) { async function handleDelete(record: ShopVO.Info) {
try { try {
await deleteShopApi(record.id); await deleteShopApi(record.id);
@@ -227,22 +262,71 @@ async function handleDelete(record: ShopVO.Info) {
} }
} }
// 处理模态框成功
function handleModalSuccess() { function handleModalSuccess() {
refreshTable(); refreshTable();
} }
// 处理查看概览
function handleViewOverview(record: ShopVO.Info) { function handleViewOverview(record: ShopVO.Info) {
router.push(`/ecom/shop/overview/${record.id}`); router.push(`/ecom/shop/overview/${record.id}`);
} }
function handleViewExternalShop(record: ShopVO.Info) {
if (!record.pddShop) {
message.warning('暂无外部店铺详情,请先完成授权同步');
return;
}
pddShopDetailModalRef.value?.open(record.pddShop, record.name);
}
function clearAuthPoll() {
if (authPollTimer) {
clearInterval(authPollTimer);
authPollTimer = null;
}
}
async function handleAuthorizePdd(record: ShopVO.Info) {
if (authorizing.value) return;
try {
authorizing.value = true;
const data = await getPddAuthorizeUrlApi(record.id);
if (!data?.authorizeUrl) {
message.error('未获取到授权链接');
return;
}
const win = window.open(data.authorizeUrl, '_blank');
if (!win) {
message.warning('浏览器拦截了弹窗,请允许后重试');
return;
}
message.info('请在新窗口完成拼多多授权,完成后将自动刷新列表');
clearAuthPoll();
authPollTimer = setInterval(() => {
if (win.closed) {
clearAuthPoll();
refreshTable();
}
}, 1000);
} catch (error) {
console.error('获取拼多多授权链接失败:', error);
message.error('获取拼多多授权链接失败');
} finally {
authorizing.value = false;
}
}
onMounted(() => {
fetchPlatformOptions();
});
onUnmounted(() => {
clearAuthPoll();
});
</script> </script>
<template> <template>
<Page auto-content-height> <Page auto-content-height>
<!-- VbenVxeGrid 表格 -->
<Grid :loading="loading" class="shop-grid"> <Grid :loading="loading" class="shop-grid">
<!-- 工具栏工具 -->
<template #toolbar-tools> <template #toolbar-tools>
<Space> <Space>
<Button type="primary" @click="handleAdd"> <Button type="primary" @click="handleAdd">
@@ -252,7 +336,6 @@ function handleViewOverview(record: ShopVO.Info) {
</Space> </Space>
</template> </template>
<!-- Logo 列:64px 图标,需配合更高行高 -->
<template #logo="{ row }: { row: ShopVO.Info }"> <template #logo="{ row }: { row: ShopVO.Info }">
<div class="shop-logo-cell flex items-center justify-center"> <div class="shop-logo-cell flex items-center justify-center">
<img <img
@@ -270,7 +353,6 @@ function handleViewOverview(record: ShopVO.Info) {
</div> </div>
</template> </template>
<!-- 店铺名称列 -->
<template #name="{ row }: { row: ShopVO.Info }"> <template #name="{ row }: { row: ShopVO.Info }">
<a <a
class="text-primary cursor-pointer hover:underline" class="text-primary cursor-pointer hover:underline"
@@ -280,15 +362,57 @@ function handleViewOverview(record: ShopVO.Info) {
</a> </a>
</template> </template>
<!-- 操作列 --> <template #externalShop="{ row }: { row: ShopVO.Info }">
<template #action="{ row }: { row: any }"> <div v-if="isPddShop(row)" class="flex flex-col gap-1">
<Space> <Tag v-if="hasExternalShop(row)" color="success" class="!mr-0 w-fit">
已绑定
</Tag>
<Tag v-else color="default" class="!mr-0 w-fit">未授权</Tag>
<span
v-if="row.pddShop?.mallName"
class="text-primary cursor-pointer text-xs hover:underline"
@click="handleViewExternalShop(row)"
>
{{ row.pddShop.mallName }}
</span>
<span
v-else-if="row.externalShopId"
class="text-xs text-slate-500"
>
mall_id: {{ row.externalShopId }}
</span>
</div>
<span v-else class="text-slate-400">-</span>
</template>
<template #action="{ row }: { row: ShopVO.Info }">
<Space wrap>
<Button size="small" type="primary" @click="handleViewOverview(row)"> <Button size="small" type="primary" @click="handleViewOverview(row)">
查看概览 查看概览
</Button> </Button>
<Button size="small" @click="router.push(`/ecom/shop/details/${row.id}`)"> <Button
size="small"
@click="router.push(`/ecom/shop/details/${row.id}`)"
>
查看详情 查看详情
</Button> </Button>
<Button
v-if="isPddShop(row) && row.pddShop"
size="small"
@click="handleViewExternalShop(row)"
>
外部店铺
</Button>
<Button
v-if="isPddShop(row)"
size="small"
type="primary"
ghost
:loading="authorizing"
@click="handleAuthorizePdd(row)"
>
{{ hasExternalShop(row) ? '重新授权' : '授权拼多多' }}
</Button>
<Button size="small" @click="handleEdit(row)">编辑</Button> <Button size="small" @click="handleEdit(row)">编辑</Button>
<Popconfirm <Popconfirm
title="确定要删除这个店铺吗?" title="确定要删除这个店铺吗?"
@@ -300,13 +424,12 @@ function handleViewOverview(record: ShopVO.Info) {
</template> </template>
</Grid> </Grid>
<!-- 店铺表单模态框 -->
<ShopFormModal ref="shopFormModalRef" @success="handleModalSuccess" /> <ShopFormModal ref="shopFormModalRef" @success="handleModalSuccess" />
<PddShopDetailModal ref="pddShopDetailModalRef" />
</Page> </Page>
</template> </template>
<style scoped> <style scoped>
/* 店铺表行高与 Logo 垂直居中 */
:deep(.shop-grid .vxe-body--column) { :deep(.shop-grid .vxe-body--column) {
vertical-align: middle; vertical-align: middle;
} }