店小秘接入基础:图形验证码登录
- 新增 dxm 平台实现:取图形验证码、AES 加密账号密码登录、登录态检查 - 账号接口返回 requires_login_captcha;新增 GET /external-print-accounts/:id/login-captcha - 验证码绑定的会话存 Redis,登录成功/失败后都清理,支持多实例 - 前端登录按钮按平台能力弹出验证码输入框 - 补 dxm 平台字典迁移、接入文档与单元测试 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
parent
2b8fcc2286
commit
78f07651f1
@ -1409,6 +1409,7 @@ module.exports = {
|
||||
has_cookie: { type: 'boolean', description: '是否已保存会话 cookie(cookie 本身不回显)' },
|
||||
has_token: { type: 'boolean', description: '是否已保存登录 token(token 本身不回显)' },
|
||||
login_status: { type: 'integer', description: '登录状态:1已登录 0未登录/已失效(最近一次平台交互结果)' },
|
||||
requires_login_captcha: { type: 'boolean', description: '登录是否需要图形验证码(前端据此弹出验证码输入)' },
|
||||
platform: { type: 'externalPrintPlatformItem', description: '所属外部打单平台' },
|
||||
created_at: { type: 'string', description: '创建时间' },
|
||||
updated_at: { type: 'string', description: '更新时间' },
|
||||
@ -1448,6 +1449,15 @@ module.exports = {
|
||||
message: { type: 'string', description: '提示信息' },
|
||||
data: { type: 'externalPrintAccountLoginResult', description: '登录结果' },
|
||||
},
|
||||
externalPrintAccountLoginCaptchaResult: {
|
||||
image: { type: 'string', description: '验证码图片(data:image/jpeg;base64,...)' },
|
||||
expires_in: { type: 'integer', description: '验证码有效秒数' },
|
||||
},
|
||||
externalPrintAccountLoginCaptchaResponse: {
|
||||
code: { type: 'integer', description: '业务状态码,0 成功' },
|
||||
message: { type: 'string', description: '提示信息' },
|
||||
data: { type: 'externalPrintAccountLoginCaptchaResult', description: '登录验证码' },
|
||||
},
|
||||
externalPrintShopSource: {
|
||||
code: { type: 'string', description: '来源标识(平台自定义,如 agent / my_shop)' },
|
||||
name: { type: 'string', description: '来源名称(如「平台商家」「我的店铺」)' },
|
||||
|
||||
@ -7,7 +7,11 @@
|
||||
|
||||
const { Controller } = require('egg');
|
||||
const { parsePagination, buildPageResult } = require('../lib/pagination');
|
||||
const { createPrintPlatformService, hasPrintPlatformService } = require('../lib/printPlatform');
|
||||
const {
|
||||
createPrintPlatformService,
|
||||
hasPrintPlatformService,
|
||||
getPrintPlatformServiceClass,
|
||||
} = require('../lib/printPlatform');
|
||||
|
||||
/**
|
||||
* 列表/详情不回显密码与 cookie,仅返回是否已设置
|
||||
@ -22,6 +26,9 @@ function toSafeAccount(row) {
|
||||
delete plain.password;
|
||||
delete plain.cookie;
|
||||
delete plain.token;
|
||||
// 登录能力由平台实现声明,前端据此决定是否弹验证码
|
||||
const Service = plain.platform && getPrintPlatformServiceClass(plain.platform.code);
|
||||
plain.requires_login_captcha = !!(Service && Service.loginRequiresCaptcha);
|
||||
return plain;
|
||||
}
|
||||
|
||||
@ -336,12 +343,52 @@ class ExternalPrintAccountController extends Controller {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 获取登录图形验证码
|
||||
* @description 仅登录需要验证码的平台可用;返回验证码图片,并把验证码绑定的会话暂存在缓存中
|
||||
* @router get /api/external-print-accounts/{id}/login-captcha
|
||||
* @apikey
|
||||
* @request path integer *id 账号主键ID
|
||||
* @response 200 externalPrintAccountLoginCaptchaResponse success
|
||||
*/
|
||||
async loginCaptcha() {
|
||||
const { ctx } = this;
|
||||
const account = await this.findAccount(ctx.params.id, { withPlatform: true });
|
||||
|
||||
if (!account) {
|
||||
ctx.status = 404;
|
||||
ctx.body = { code: 404, message: '打单账号不存在' };
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const service = this.createPlatformService(account);
|
||||
if (!service.constructor.loginRequiresCaptcha) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { code: 400, message: '当前打单平台登录不需要验证码' };
|
||||
return;
|
||||
}
|
||||
const result = await service.getLoginCaptcha();
|
||||
const expiresIn = 300;
|
||||
await ctx.service.cache.saveExternalPrintCaptcha(account.id, result.session, expiresIn);
|
||||
ctx.body = {
|
||||
code: 0,
|
||||
message: 'success',
|
||||
data: { image: result.image, expires_in: expiresIn },
|
||||
};
|
||||
} catch (err) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { code: 400, message: err.message };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 登录外部打单账号
|
||||
* @description cookie 有效时直接复用;否则用账号密码登录,成功后把会话 cookie 写回账号表
|
||||
* @description cookie 有效时直接复用;否则用账号密码登录(需要验证码的平台须先取验证码并回传 captcha)
|
||||
* @router post /api/external-print-accounts/{id}/login
|
||||
* @apikey
|
||||
* @request path integer *id 账号主键ID
|
||||
* @request body string captcha 图形验证码(登录需要验证码的平台必填)
|
||||
* @response 200 externalPrintAccountLoginResponse success
|
||||
*/
|
||||
async login() {
|
||||
@ -356,7 +403,15 @@ class ExternalPrintAccountController extends Controller {
|
||||
|
||||
try {
|
||||
const service = this.createPlatformService(account);
|
||||
const result = await service.login();
|
||||
const captcha = ctx.request.body && ctx.request.body.captcha ? String(ctx.request.body.captcha) : '';
|
||||
const session = captcha ? await ctx.service.cache.getExternalPrintCaptcha(account.id) : '';
|
||||
let result;
|
||||
try {
|
||||
result = await service.login({ captcha, session });
|
||||
} finally {
|
||||
// 验证码一次性使用:无论成功失败都清理,避免重放
|
||||
await ctx.service.cache.invalidateExternalPrintCaptcha(account.id);
|
||||
}
|
||||
ctx.body = {
|
||||
code: 0,
|
||||
message: 'success',
|
||||
|
||||
@ -37,6 +37,14 @@ class PrintPlatformService {
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 登录是否需要图形验证码:前端据此决定是否弹出验证码输入框
|
||||
* @return {boolean} 是否需要验证码
|
||||
*/
|
||||
static get loginRequiresCaptcha() {
|
||||
return false;
|
||||
}
|
||||
|
||||
/** 平台标识(与平台配置的 code 对应) */
|
||||
get platformCode() {
|
||||
return this.constructor.code;
|
||||
@ -131,11 +139,20 @@ class PrintPlatformService {
|
||||
if (this._saveLoginStatus) await this._saveLoginStatus(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取登录图形验证码(loginRequiresCaptcha=true 的平台必须实现)
|
||||
* @return {Promise<{image: string, session: string}>} 验证码图片(data URL)与绑定的会话
|
||||
*/
|
||||
async getLoginCaptcha() {
|
||||
throw new Error(`外部打单平台 ${this.platformName} 未实现 getLoginCaptcha()`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 登录外部打单平台(获取会话/令牌),由各平台实现
|
||||
* @param {Object} [options] 登录参数(如验证码 captcha / 验证码会话 session)
|
||||
* @return {Promise<Object>} 登录结果(会话、令牌等,由各实现定义)
|
||||
*/
|
||||
async login() {
|
||||
async login(options) { // eslint-disable-line no-unused-vars
|
||||
throw new Error(`外部打单平台 ${this.platformName} 未实现 login()`);
|
||||
}
|
||||
|
||||
|
||||
310
backend/app/lib/printPlatform/dxm.js
Normal file
310
backend/app/lib/printPlatform/dxm.js
Normal file
@ -0,0 +1,310 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 店小秘(dianxiaomi)外部打单平台服务。
|
||||
*
|
||||
* 平台记录:external_print_platforms.code = 'dxm'。
|
||||
* 当前实现「接入基础」:图形验证码 + 账号密码登录 + 登录态检查;
|
||||
* 店铺/商品/订单/取号等业务接口待按平台真实报文补齐(基类会明确报未实现)。
|
||||
*
|
||||
* 登录协议(2026-11-23 实测):
|
||||
* 1. GET /verify/code.htm?t=<时间戳> 返回 4 位图形验证码,响应同时下发
|
||||
* JSESSIONID 与 dxm_vc(验证码绑定会话),登录必须带上同一组 cookie;
|
||||
* 2. POST /user/userLoginNew2.json 表单字段 account / password(AES 加密串)、
|
||||
* dxmVerify(验证码)、loginVerifyCode / remeber / loginRedUrl / url;
|
||||
* 返回 { code: 0 成功, error, url },code=-1 为验证码错误;
|
||||
* 3. GET /home.htm 未登录会 302 到 /index.htm,200 即登录态有效。
|
||||
*
|
||||
* 账号密码加密格式(与前端 dxmEncrypt.js 一致):
|
||||
* "0" + 4位随机hex + 16字节IV(hex) + 16字节Key(hex) + AES-128-CBC 密文(hex)
|
||||
*/
|
||||
|
||||
const crypto = require('crypto');
|
||||
const PrintPlatformService = require('./base');
|
||||
|
||||
/** 平台配置未填链接时的默认站点 */
|
||||
const DEFAULT_SITE_URL = 'https://www.dianxiaomi.com';
|
||||
|
||||
/** 图形验证码 */
|
||||
const CAPTCHA_PATH = '/verify/code.htm';
|
||||
|
||||
/** 账号密码登录 */
|
||||
const LOGIN_PATH = '/user/userLoginNew2.json';
|
||||
|
||||
/** 工作台首页:未登录会 302 到登录页 */
|
||||
const HOME_PATH = '/home.htm';
|
||||
|
||||
const REQUEST_TIMEOUT_MS = 30000;
|
||||
|
||||
const USER_AGENT =
|
||||
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36';
|
||||
|
||||
const BROWSER_HEADERS = {
|
||||
accept:
|
||||
'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8',
|
||||
'accept-language': 'zh-CN,zh;q=0.9',
|
||||
'user-agent': USER_AGENT,
|
||||
};
|
||||
|
||||
const AJAX_HEADERS = {
|
||||
accept: 'application/json, text/javascript, */*; q=0.01',
|
||||
'accept-language': 'zh-CN,zh;q=0.9',
|
||||
'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
|
||||
'user-agent': USER_AGENT,
|
||||
'x-requested-with': 'XMLHttpRequest',
|
||||
};
|
||||
|
||||
/**
|
||||
* 读取响应里的 set-cookie(兼容没有 getSetCookie 的运行时)
|
||||
* @param {Response} res fetch 响应
|
||||
* @return {string[]} set-cookie 列表
|
||||
*/
|
||||
function getSetCookies(res) {
|
||||
if (typeof res.headers.getSetCookie === 'function') return res.headers.getSetCookie();
|
||||
const raw = res.headers.get('set-cookie');
|
||||
return raw ? [ raw ] : [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 合并 set-cookie 到已有 cookie:同名覆盖,其余保留
|
||||
* @param {string} cookie 已有 cookie
|
||||
* @param {string[]} setCookies 响应头 set-cookie
|
||||
* @return {string} 合并后的 cookie
|
||||
*/
|
||||
function mergeCookie(cookie, setCookies) {
|
||||
const jar = new Map();
|
||||
for (const item of String(cookie || '').split(';')) {
|
||||
const kv = item.trim();
|
||||
const idx = kv.indexOf('=');
|
||||
if (idx > 0) jar.set(kv.slice(0, idx), kv.slice(idx + 1));
|
||||
}
|
||||
for (const raw of setCookies || []) {
|
||||
const kv = String(raw).split(';')[0].trim();
|
||||
const idx = kv.indexOf('=');
|
||||
if (idx > 0) jar.set(kv.slice(0, idx), kv.slice(idx + 1));
|
||||
}
|
||||
return Array.from(jar, ([ key, value ]) => `${key}=${value}`).join('; ');
|
||||
}
|
||||
|
||||
/**
|
||||
* 加密登录字段(账号/密码),与服务端约定的格式见文件头注释
|
||||
* @param {string} value 明文
|
||||
* @return {string} 加密串
|
||||
*/
|
||||
function encryptLoginField(value) {
|
||||
const key = crypto.randomBytes(16);
|
||||
const iv = crypto.randomBytes(16);
|
||||
const cipher = crypto.createCipheriv('aes-128-cbc', key, iv);
|
||||
const encrypted = Buffer.concat([ cipher.update(String(value), 'utf8'), cipher.final() ]);
|
||||
return `0${crypto.randomBytes(2).toString('hex')}${iv.toString('hex')}${key.toString('hex')}${encrypted.toString('hex')}`;
|
||||
}
|
||||
|
||||
class DxmService extends PrintPlatformService {
|
||||
static get code() {
|
||||
return 'dxm';
|
||||
}
|
||||
|
||||
/** 店小秘登录必须带图形验证码 */
|
||||
static get loginRequiresCaptcha() {
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 加密登录字段(导出给测试/排查用)
|
||||
* @param {string} value 明文
|
||||
* @return {string} 加密串
|
||||
*/
|
||||
static encryptLoginField(value) {
|
||||
return encryptLoginField(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* 店铺来源:店小秘按「已授权店铺」拉取
|
||||
* @return {Array<{code: string, name: string}>} 来源清单
|
||||
*/
|
||||
listShopSources() {
|
||||
return [{ code: 'shop', name: '店铺' }];
|
||||
}
|
||||
|
||||
/**
|
||||
* 站点根地址(平台配置的链接为空时用默认域名)
|
||||
* @return {string} 站点根地址,不带结尾斜杠
|
||||
*/
|
||||
get siteUrl() {
|
||||
const url = String(this.platform.url || '').trim();
|
||||
if (!url) return DEFAULT_SITE_URL;
|
||||
const withProtocol = /^https?:\/\//i.test(url) ? url : `https://${url}`;
|
||||
return withProtocol.replace(/\/+$/, '');
|
||||
}
|
||||
|
||||
/**
|
||||
* 统一 JSON/文本请求入口(各实现可被测试替换)
|
||||
* @param {string} url 完整请求地址
|
||||
* @param {Object} [options] fetch 选项
|
||||
* @return {Promise<{status: number, json: Object|null, text: string, setCookies: string[]}>} 响应
|
||||
*/
|
||||
async request(url, options = {}) {
|
||||
const res = await fetch(url, {
|
||||
redirect: 'follow',
|
||||
...options,
|
||||
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
||||
});
|
||||
const text = await res.text();
|
||||
let json = null;
|
||||
try {
|
||||
json = JSON.parse(text);
|
||||
} catch {
|
||||
json = null;
|
||||
}
|
||||
return { status: res.status, json, text, setCookies: getSetCookies(res) };
|
||||
}
|
||||
|
||||
/**
|
||||
* 二进制请求(图形验证码是图片)
|
||||
* @param {string} url 完整请求地址
|
||||
* @param {Object} [options] fetch 选项
|
||||
* @return {Promise<{status: number, buffer: Buffer, contentType: string, setCookies: string[]}>} 响应
|
||||
*/
|
||||
async requestBinary(url, options = {}) {
|
||||
const res = await fetch(url, {
|
||||
redirect: 'follow',
|
||||
...options,
|
||||
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
||||
});
|
||||
const buffer = Buffer.from(await res.arrayBuffer());
|
||||
return {
|
||||
status: res.status,
|
||||
buffer,
|
||||
contentType: String(res.headers.get('content-type') || ''),
|
||||
setCookies: getSetCookies(res),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取登录图形验证码:同时返回验证码图片与绑定的会话 cookie
|
||||
* @return {Promise<{image: string, session: string}>} 图片 data URL 与登录会话 cookie
|
||||
*/
|
||||
async getLoginCaptcha() {
|
||||
const res = await this.requestBinary(`${this.siteUrl}${CAPTCHA_PATH}?t=${Date.now()}`, {
|
||||
headers: { ...BROWSER_HEADERS, referer: `${this.siteUrl}/` },
|
||||
});
|
||||
if (res.status !== 200 || !res.buffer.length) {
|
||||
throw new Error(`店小秘获取验证码失败:HTTP ${res.status}`);
|
||||
}
|
||||
const mime = (res.contentType.split(';')[0] || '').trim() || 'image/jpeg';
|
||||
return {
|
||||
image: `data:${mime};base64,${res.buffer.toString('base64')}`,
|
||||
session: mergeCookie('', res.setCookies),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 登录:cookie 有效时直接复用;否则用「账号 + 密码 + 图形验证码」登录
|
||||
* @param {Object} [options] 登录参数
|
||||
* @param {string} [options.captcha] 图形验证码(平台要求验证码时为必填)
|
||||
* @param {string} [options.session] 获取验证码时绑定的会话 cookie
|
||||
* @return {Promise<{cookie: string, token: null, redirectUrl: string|null, reused: boolean, shopName: string}>} 登录结果
|
||||
*/
|
||||
async login(options = {}) {
|
||||
if (this.cookie) {
|
||||
const status = await this.checkSession();
|
||||
if (status.loggedIn) {
|
||||
return { cookie: this.cookie, token: null, redirectUrl: null, reused: true, shopName: status.shopName || '' };
|
||||
}
|
||||
}
|
||||
return this.loginByPassword(options);
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查登录态:带 cookie 访问工作台,302 到登录页即失效
|
||||
* @return {Promise<{loggedIn: boolean, message: string, url: string}>} 登录态检查结果
|
||||
*/
|
||||
async checkSession() {
|
||||
const url = `${this.siteUrl}${HOME_PATH}`;
|
||||
if (!this.cookie) {
|
||||
await this.saveLoginStatus(0);
|
||||
return { loggedIn: false, message: '账号未保存会话 cookie,尚未登录', url };
|
||||
}
|
||||
|
||||
let res;
|
||||
try {
|
||||
res = await this.request(url, {
|
||||
headers: { ...BROWSER_HEADERS, cookie: this.cookie },
|
||||
redirect: 'manual',
|
||||
});
|
||||
} catch (err) {
|
||||
return { loggedIn: false, message: `检查店小秘登录态失败:${err.message}`, url };
|
||||
}
|
||||
|
||||
const loggedIn = res.status === 200;
|
||||
if (!loggedIn) await this.saveLoginStatus(0);
|
||||
return {
|
||||
loggedIn,
|
||||
message: loggedIn ? '登录态有效' : '登录态已失效(访问工作台被重定向到登录页)',
|
||||
url,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 账号密码 + 图形验证码登录
|
||||
* @param {Object} [options] 登录参数
|
||||
* @param {string} [options.captcha] 图形验证码
|
||||
* @param {string} [options.session] 获取验证码时绑定的会话 cookie
|
||||
* @return {Promise<{cookie: string, token: null, redirectUrl: string|null, reused: boolean, shopName: string}>} 登录结果
|
||||
*/
|
||||
async loginByPassword({ captcha = '', session = '' } = {}) {
|
||||
const code = String(captcha || '').trim();
|
||||
if (!code) throw new Error('店小秘登录需要图形验证码:请先获取验证码');
|
||||
const cookie = String(session || '').trim();
|
||||
if (!cookie) throw new Error('店小秘验证码已过期:请刷新验证码后重试');
|
||||
|
||||
const { account, password } = this.getCredentials();
|
||||
const body = new URLSearchParams({
|
||||
account: encryptLoginField(account),
|
||||
password: encryptLoginField(password),
|
||||
dxmVerify: code,
|
||||
loginVerifyCode: '',
|
||||
remeber: '',
|
||||
loginRedUrl: '',
|
||||
url: '',
|
||||
});
|
||||
|
||||
const res = await this.request(`${this.siteUrl}${LOGIN_PATH}`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
...AJAX_HEADERS,
|
||||
origin: this.siteUrl,
|
||||
referer: `${this.siteUrl}/index.htm`,
|
||||
cookie,
|
||||
},
|
||||
body: body.toString(),
|
||||
});
|
||||
|
||||
const json = res.json || {};
|
||||
if (Number(json.code) !== 0) {
|
||||
const reason = String(json.error || '').trim() || `平台返回 code=${json.code}`;
|
||||
throw new Error(`店小秘登录失败:${reason}`);
|
||||
}
|
||||
|
||||
const finalCookie = mergeCookie(cookie, res.setCookies);
|
||||
const home = await this.request(`${this.siteUrl}${HOME_PATH}`, {
|
||||
headers: { ...BROWSER_HEADERS, cookie: finalCookie },
|
||||
redirect: 'manual',
|
||||
});
|
||||
if (home.status !== 200) {
|
||||
throw new Error(`店小秘登录后校验失败:访问工作台被重定向(HTTP ${home.status})`);
|
||||
}
|
||||
|
||||
await this.saveCookie(finalCookie);
|
||||
await this.saveLoginStatus(1);
|
||||
return {
|
||||
cookie: finalCookie,
|
||||
token: null,
|
||||
redirectUrl: json.url || null,
|
||||
reused: false,
|
||||
shopName: '',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = DxmService;
|
||||
@ -181,6 +181,7 @@ module.exports = app => {
|
||||
router.get('/api/external-print-platforms', jwtAuth, groupScope(), controller.externalPrintPlatform.index);
|
||||
// 账号登录态检查 / 登录(需在 resources 之前注册,避免被 /:id 误匹配)
|
||||
router.post('/api/external-print-accounts/:id/check', jwtAuth, principalCheck({ model: 'ExternalPrintAccount' }), groupScope(), controller.externalPrintAccount.check);
|
||||
router.get('/api/external-print-accounts/:id/login-captcha', jwtAuth, principalCheck({ model: 'ExternalPrintAccount' }), groupScope(), controller.externalPrintAccount.loginCaptcha);
|
||||
router.post('/api/external-print-accounts/:id/login', jwtAuth, principalCheck({ model: 'ExternalPrintAccount' }), groupScope(), controller.externalPrintAccount.login);
|
||||
// 平台侧店铺来源(如店管家的平台商家 / 我的店铺)与店铺列表、创建到 OMS 店铺
|
||||
// 前端按账号ID调用,后端按平台服务分发,接口对平台无关
|
||||
|
||||
@ -13,6 +13,7 @@ const KEYS = {
|
||||
principal: principalId => `${PREFIX}:principal:${principalId}`,
|
||||
shopBasic: shopId => `${PREFIX}:shop-basic:${shopId}`,
|
||||
externalPrintAccount: accountId => `${PREFIX}:external-print-account:${accountId}`,
|
||||
externalPrintCaptcha: accountId => `${PREFIX}:external-print-captcha:${accountId}`,
|
||||
expressTemplate: (accountId, platformCode, expressCode) => `${PREFIX}:express-template:${accountId}:${platformCode}:${expressCode}`,
|
||||
};
|
||||
|
||||
@ -332,6 +333,36 @@ class CacheService extends Service {
|
||||
// 绑定关系按(账号 + 平台 + 编码)建 key,只能按账号前缀批量清除
|
||||
await this.forgetByPrefix(`${PREFIX}:express-template:${accountId}:`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存登录验证码绑定的会话(多实例部署下取验证码与提交登录可能落到不同进程,必须走共享缓存)
|
||||
* @param {Number} accountId 打单账号ID
|
||||
* @param {String} session 获取验证码时的 cookie
|
||||
* @param {Number} [ttl] 有效秒数,默认 300
|
||||
* @return {Promise<void>} 无返回值
|
||||
*/
|
||||
async saveExternalPrintCaptcha(accountId, session, ttl = 300) {
|
||||
await this.write(KEYS.externalPrintCaptcha(accountId), { session }, ttl);
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取登录验证码绑定的会话
|
||||
* @param {Number} accountId 打单账号ID
|
||||
* @return {Promise<String>} 会话 cookie,不存在为空串
|
||||
*/
|
||||
async getExternalPrintCaptcha(accountId) {
|
||||
const cached = await this.read(KEYS.externalPrintCaptcha(accountId));
|
||||
return cached && cached.session ? String(cached.session) : '';
|
||||
}
|
||||
|
||||
/**
|
||||
* 清除登录验证码会话(登录成功后立即失效,避免复用已用过的验证码)
|
||||
* @param {Number} accountId 打单账号ID
|
||||
* @return {Promise<void>} 无返回值
|
||||
*/
|
||||
async invalidateExternalPrintCaptcha(accountId) {
|
||||
await this.forget(KEYS.externalPrintCaptcha(accountId));
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = CacheService;
|
||||
|
||||
@ -0,0 +1,26 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 写入店小秘平台记录(开发者维护的平台字典)。
|
||||
*
|
||||
* 代码已按 external_print_platforms.code = 'dxm' 注册实现;
|
||||
* 这里只补本地/新环境的字典数据,已有同名平台时不动(避免覆盖线上维护的配置)。
|
||||
*/
|
||||
module.exports = {
|
||||
async up(queryInterface) {
|
||||
await queryInterface.sequelize.query(`
|
||||
INSERT INTO external_print_platforms
|
||||
(code, name, url, fetch_waybill_no, has_own_waybill, sort, status, created_at, updated_at)
|
||||
SELECT 'dxm', '店小秘', 'www.dianxiaomi.com', 1, 1, 0, 1, NOW(), NOW()
|
||||
FROM DUAL
|
||||
WHERE NOT EXISTS (
|
||||
SELECT 1 FROM external_print_platforms WHERE code = 'dxm'
|
||||
)
|
||||
`);
|
||||
},
|
||||
|
||||
// 平台字典可能已被使用(账号/店铺关联),回滚不删数据
|
||||
async down() {
|
||||
return null;
|
||||
},
|
||||
};
|
||||
150
backend/test/app/lib/printPlatformDxm.test.js
Normal file
150
backend/test/app/lib/printPlatformDxm.test.js
Normal file
@ -0,0 +1,150 @@
|
||||
'use strict';
|
||||
|
||||
const { assert } = require('egg-mock/bootstrap');
|
||||
const crypto = require('crypto'); // eslint-disable-line no-restricted-modules
|
||||
const DxmService = require('../../../app/lib/printPlatform/dxm');
|
||||
|
||||
/**
|
||||
* 解出 encryptLoginField 的明文,验证加密格式与服务端约定一致
|
||||
* @param {string} value 加密串
|
||||
* @return {string} 明文
|
||||
*/
|
||||
function decryptLoginField(value) {
|
||||
const body = String(value);
|
||||
assert.strictEqual(body[0], '0');
|
||||
const iv = Buffer.from(body.slice(5, 37), 'hex');
|
||||
const key = Buffer.from(body.slice(37, 69), 'hex');
|
||||
const data = Buffer.from(body.slice(69), 'hex');
|
||||
const decipher = crypto.createDecipheriv('aes-128-cbc', key, iv);
|
||||
return Buffer.concat([ decipher.update(data), decipher.final() ]).toString('utf8');
|
||||
}
|
||||
|
||||
function createService(overrides = {}) {
|
||||
const platform = { code: 'dxm', name: '店小秘', url: '', ...overrides.platform };
|
||||
const account = { id: 1, account: 'user@example.com', password: 'secret', cookie: '' };
|
||||
const saved = { cookie: '', status: null };
|
||||
const service = new DxmService({
|
||||
platform,
|
||||
account: { ...account, ...overrides.account },
|
||||
saveCookie: async cookie => {
|
||||
saved.cookie = cookie;
|
||||
},
|
||||
saveLoginStatus: async status => {
|
||||
saved.status = status;
|
||||
},
|
||||
});
|
||||
return { service, saved };
|
||||
}
|
||||
|
||||
describe('printPlatform/dxm encryptLoginField', () => {
|
||||
it('格式为 0 + 随机串 + IV + Key + 密文,且可还原明文', () => {
|
||||
const encrypted = DxmService.encryptLoginField('user@example.com');
|
||||
assert.match(encrypted, /^0[0-9a-f]{4}[0-9a-f]{32}[0-9a-f]{32}[0-9a-f]+$/);
|
||||
assert.strictEqual(decryptLoginField(encrypted), 'user@example.com');
|
||||
});
|
||||
});
|
||||
|
||||
describe('printPlatform/dxm getLoginCaptcha', () => {
|
||||
it('返回 data URL,并带上验证码绑定会话', async () => {
|
||||
const { service } = createService();
|
||||
service.requestBinary = async () => ({
|
||||
status: 200,
|
||||
buffer: Buffer.from('jpeg-bytes'),
|
||||
contentType: 'image/jpeg;charset=UTF-8',
|
||||
setCookies: [ 'JSESSIONID=abc123; Path=/; HttpOnly', 'dxm_vc=token456; Path=/; HttpOnly' ],
|
||||
});
|
||||
|
||||
const result = await service.getLoginCaptcha();
|
||||
assert.strictEqual(result.image, `data:image/jpeg;base64,${Buffer.from('jpeg-bytes').toString('base64')}`);
|
||||
assert.strictEqual(result.session, 'JSESSIONID=abc123; dxm_vc=token456');
|
||||
});
|
||||
|
||||
it('验证码接口失败时抛错', async () => {
|
||||
const { service } = createService();
|
||||
service.requestBinary = async () => ({ status: 500, buffer: Buffer.alloc(0), contentType: '', setCookies: [] });
|
||||
await assert.rejects(service.getLoginCaptcha(), /获取验证码失败/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('printPlatform/dxm loginByPassword', () => {
|
||||
it('没有验证码 / 验证码会话时直接提示', async () => {
|
||||
const { service } = createService();
|
||||
await assert.rejects(service.login({ session: 'JSESSIONID=abc' }), /需要图形验证码/);
|
||||
await assert.rejects(service.login({ captcha: '1234' }), /验证码已过期/);
|
||||
});
|
||||
|
||||
it('提交加密账号密码与验证码,成功后保存会话并校验登录态', async () => {
|
||||
const { service, saved } = createService();
|
||||
const calls = [];
|
||||
service.request = async (url, options) => {
|
||||
calls.push({ url, options });
|
||||
if (url.endsWith('/user/userLoginNew2.json')) {
|
||||
const form = new URLSearchParams(options.body);
|
||||
assert.strictEqual(form.get('dxmVerify'), '1234');
|
||||
assert.strictEqual(decryptLoginField(form.get('account')), 'user@example.com');
|
||||
assert.strictEqual(decryptLoginField(form.get('password')), 'secret');
|
||||
assert.match(options.headers.cookie, /dxm_vc=token456/);
|
||||
return {
|
||||
status: 200,
|
||||
json: { code: 0, url: '/home.htm' },
|
||||
text: '',
|
||||
setCookies: [ 'JSESSIONID=logged-in; Path=/' ],
|
||||
};
|
||||
}
|
||||
assert.match(url, /\/home\.htm$/);
|
||||
assert.match(options.headers.cookie, /JSESSIONID=logged-in/);
|
||||
return { status: 200, json: null, text: '', setCookies: [] };
|
||||
};
|
||||
|
||||
const result = await service.login({ captcha: '1234', session: 'JSESSIONID=abc; dxm_vc=token456' });
|
||||
|
||||
assert.strictEqual(result.reused, false);
|
||||
assert.strictEqual(result.cookie, 'JSESSIONID=logged-in; dxm_vc=token456');
|
||||
assert.strictEqual(saved.cookie, result.cookie);
|
||||
assert.strictEqual(saved.status, 1);
|
||||
assert.strictEqual(calls.length, 2);
|
||||
});
|
||||
|
||||
it('平台返回验证码错误时抛出可读原因且不保存会话', async () => {
|
||||
const { service, saved } = createService();
|
||||
service.request = async () => ({
|
||||
status: 200,
|
||||
json: { code: -1, error: '验证码填写错误' },
|
||||
text: '',
|
||||
setCookies: [],
|
||||
});
|
||||
|
||||
await assert.rejects(
|
||||
service.login({ captcha: '0000', session: 'JSESSIONID=abc; dxm_vc=token456' }),
|
||||
/店小秘登录失败:验证码填写错误/
|
||||
);
|
||||
assert.strictEqual(saved.cookie, '');
|
||||
});
|
||||
});
|
||||
|
||||
describe('printPlatform/dxm checkSession', () => {
|
||||
it('访问工作台 200 视为已登录', async () => {
|
||||
const { service, saved } = createService({ account: { cookie: 'JSESSIONID=ok' } });
|
||||
service.request = async () => ({ status: 200, json: null, text: '', setCookies: [] });
|
||||
|
||||
const result = await service.checkSession();
|
||||
assert.strictEqual(result.loggedIn, true);
|
||||
assert.strictEqual(saved.status, null);
|
||||
});
|
||||
|
||||
it('访问工作台被 302 到登录页时标记未登录', async () => {
|
||||
const { service, saved } = createService({ account: { cookie: 'JSESSIONID=expired' } });
|
||||
service.request = async () => ({ status: 302, json: null, text: '', setCookies: [] });
|
||||
|
||||
const result = await service.checkSession();
|
||||
assert.strictEqual(result.loggedIn, false);
|
||||
assert.strictEqual(saved.status, 0);
|
||||
});
|
||||
|
||||
it('没有 cookie 时直接返回未登录', async () => {
|
||||
const { service } = createService();
|
||||
const result = await service.checkSession();
|
||||
assert.strictEqual(result.loggedIn, false);
|
||||
assert.match(result.message, /未保存会话/);
|
||||
});
|
||||
});
|
||||
@ -15,7 +15,9 @@ export interface ExternalPrintAccountItem {
|
||||
has_token?: boolean
|
||||
/** 登录状态:1 已登录 0 未登录/已失效(最近一次平台交互结果) */
|
||||
login_status: number
|
||||
platform?: Pick<ExternalPrintPlatformItem, 'id' | 'code' | 'name' | 'url' | 'fetch_waybill_no'> | null
|
||||
/** 登录是否需要图形验证码(前端据此弹出验证码输入) */
|
||||
requires_login_captcha?: boolean
|
||||
platform?: Pick<ExternalPrintPlatformItem, 'id' | 'code' | 'name' | 'url' | 'fetch_waybill_no' | 'has_own_waybill'> | null
|
||||
created_at?: string
|
||||
updated_at?: string
|
||||
}
|
||||
@ -67,11 +69,16 @@ export function checkExternalPrintAccount(id: number) {
|
||||
})
|
||||
}
|
||||
|
||||
/** 登录账号:cookie 有效时复用,否则用账号密码登录并把 cookie 写回 */
|
||||
export function loginExternalPrintAccount(id: number) {
|
||||
/** 获取登录图形验证码(登录需要验证码的平台) */
|
||||
export function getExternalPrintLoginCaptcha(id: number) {
|
||||
return get<{ image: string; expires_in: number }>(`/external-print-accounts/${id}/login-captcha`)
|
||||
}
|
||||
|
||||
/** 登录账号:cookie 有效时复用,否则用账号密码登录;需要验证码的平台须回传 captcha */
|
||||
export function loginExternalPrintAccount(id: number, data?: { captcha?: string }) {
|
||||
return post<{ logged_in: boolean; reused: boolean; shop_name?: string }>(
|
||||
`/external-print-accounts/${id}/login`,
|
||||
undefined,
|
||||
data,
|
||||
{ timeout: 60000 },
|
||||
)
|
||||
}
|
||||
|
||||
@ -12,6 +12,7 @@ import {
|
||||
deleteExternalPrintAccount,
|
||||
checkExternalPrintAccount,
|
||||
loginExternalPrintAccount,
|
||||
getExternalPrintLoginCaptcha,
|
||||
getExternalPrintMerchants,
|
||||
getExternalPrintShopSources,
|
||||
refreshExternalPrintShopsArea,
|
||||
@ -193,11 +194,11 @@ async function handleCheck(row: ExternalPrintAccountItem) {
|
||||
}
|
||||
}
|
||||
|
||||
async function handleLogin(row: ExternalPrintAccountItem) {
|
||||
async function doLogin(row: ExternalPrintAccountItem, captcha?: string) {
|
||||
acting.id = row.id
|
||||
acting.type = 'login'
|
||||
try {
|
||||
const res = await loginExternalPrintAccount(row.id)
|
||||
const res = await loginExternalPrintAccount(row.id, captcha ? { captcha } : undefined)
|
||||
loginStatus[row.id] = {
|
||||
loggedIn: true,
|
||||
message: res.reused ? '已复用登录态' : '登录成功',
|
||||
@ -205,15 +206,59 @@ async function handleLogin(row: ExternalPrintAccountItem) {
|
||||
}
|
||||
const shop = res.shop_name ? `(${res.shop_name})` : ''
|
||||
ElMessage.success(res.reused ? `当前已是登录态,无需重新登录${shop}` : `登录成功,已保存登录态${shop}`)
|
||||
captchaVisible.value = false
|
||||
await fetchList()
|
||||
} catch {
|
||||
loginStatus[row.id] = { loggedIn: false }
|
||||
if (captchaVisible.value) await loadCaptcha(row)
|
||||
} finally {
|
||||
acting.id = null
|
||||
acting.type = ''
|
||||
}
|
||||
}
|
||||
|
||||
async function handleLogin(row: ExternalPrintAccountItem) {
|
||||
if (row.requires_login_captcha) {
|
||||
captchaAccount.value = row
|
||||
captchaCode.value = ''
|
||||
captchaVisible.value = true
|
||||
await loadCaptcha(row)
|
||||
return
|
||||
}
|
||||
await doLogin(row)
|
||||
}
|
||||
|
||||
/* -------------------- 登录图形验证码 -------------------- */
|
||||
const captchaVisible = ref(false)
|
||||
const captchaAccount = ref<ExternalPrintAccountItem | null>(null)
|
||||
const captchaImage = ref('')
|
||||
const captchaCode = ref('')
|
||||
const captchaLoading = ref(false)
|
||||
|
||||
async function loadCaptcha(row: ExternalPrintAccountItem) {
|
||||
captchaLoading.value = true
|
||||
captchaCode.value = ''
|
||||
try {
|
||||
const res = await getExternalPrintLoginCaptcha(row.id)
|
||||
captchaImage.value = res.image
|
||||
} catch {
|
||||
captchaImage.value = ''
|
||||
} finally {
|
||||
captchaLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function submitCaptchaLogin() {
|
||||
const row = captchaAccount.value
|
||||
if (!row) return
|
||||
const code = captchaCode.value.trim()
|
||||
if (!code) {
|
||||
ElMessage.warning('请输入验证码')
|
||||
return
|
||||
}
|
||||
await doLogin(row, code)
|
||||
}
|
||||
|
||||
/* -------------------- 快递接口(面单模板) -------------------- */
|
||||
const expressVisible = ref(false)
|
||||
const expressAccount = ref<ExternalPrintAccountItem | null>(null)
|
||||
@ -559,6 +604,40 @@ onBeforeUnmount(() => {
|
||||
<el-button size="small" type="primary" :loading="submitting" @click="submitForm">确定</el-button>
|
||||
</template>
|
||||
</TaskPanelDialog>
|
||||
|
||||
<TaskPanelDialog
|
||||
v-model="captchaVisible"
|
||||
:title="captchaAccount ? `登录 - ${captchaAccount.account}` : '登录验证码'"
|
||||
subtitle="请输入平台登录验证码"
|
||||
width="min(420px, 92vw)"
|
||||
body-max-height="60vh"
|
||||
>
|
||||
<div class="captcha-login">
|
||||
<el-input
|
||||
v-model="captchaCode"
|
||||
maxlength="4"
|
||||
placeholder="请输入验证码"
|
||||
@keyup.enter="submitCaptchaLogin"
|
||||
/>
|
||||
<div class="captcha-image" @click="captchaAccount && loadCaptcha(captchaAccount)">
|
||||
<img v-if="captchaImage" :src="captchaImage" alt="验证码" />
|
||||
<span v-else>{{ captchaLoading ? '加载中…' : '点击加载验证码' }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<template #hint>看不清?点击图片刷新</template>
|
||||
<template #actions>
|
||||
<el-button size="small" @click="captchaVisible = false">取消</el-button>
|
||||
<el-button
|
||||
size="small"
|
||||
type="primary"
|
||||
:loading="captchaAccount ? isActing(captchaAccount, 'login') : false"
|
||||
@click="submitCaptchaLogin"
|
||||
>
|
||||
登录
|
||||
</el-button>
|
||||
</template>
|
||||
</TaskPanelDialog>
|
||||
|
||||
<TaskPanelDialog
|
||||
v-model="shopsDialogVisible"
|
||||
:title="shopsAccount ? `店铺列表 - ${shopsAccount.account}` : '店铺列表'"
|
||||
@ -719,4 +798,29 @@ onBeforeUnmount(() => {
|
||||
color: var(--el-text-color-secondary);
|
||||
white-space: nowrap;
|
||||
}
|
||||
.captcha-login {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
}
|
||||
.captcha-image {
|
||||
flex: 0 0 auto;
|
||||
width: 117px;
|
||||
height: 40px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
border: 1px solid var(--el-border-color);
|
||||
border-radius: 4px;
|
||||
cursor: pointer;
|
||||
overflow: hidden;
|
||||
font-size: 12px;
|
||||
color: var(--el-text-color-secondary);
|
||||
background: var(--el-fill-color-blank);
|
||||
}
|
||||
.captcha-image img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: contain;
|
||||
}
|
||||
</style>
|
||||
|
||||
65
店小秘接入.md
Normal file
65
店小秘接入.md
Normal file
@ -0,0 +1,65 @@
|
||||
# 店小秘(dxm)接入
|
||||
|
||||
> 平台实现:`backend/app/lib/printPlatform/dxm.js`
|
||||
> 平台字典:`external_print_platforms.code = 'dxm'`(`url` 留空时默认 `https://www.dianxiaomi.com`)
|
||||
> 当前范围:**接入基础** = 图形验证码 + 账号密码登录 + 登录态检查;店铺/商品/订单/取号待按真实报文补齐。
|
||||
|
||||
---
|
||||
|
||||
## 1. 登录协议(2026-11-23 实测)
|
||||
|
||||
```
|
||||
① GET /verify/code.htm?t=<时间戳>
|
||||
└─ 返回 4 位图形验证码(image/jpeg),同时下发 JSESSIONID 与 dxm_vc(验证码绑定会话)
|
||||
|
||||
② POST /user/userLoginNew2.json (x-www-form-urlencoded)
|
||||
├─ account / password:AES 加密串(见下)
|
||||
├─ dxmVerify:验证码
|
||||
├─ loginVerifyCode / remeber / loginRedUrl / url:固定空串
|
||||
└─ 返回 { code, error, url }:code=0 成功;code=-1 等为失败(error 可直接展示)
|
||||
必须带 ① 的 cookie(尤其 dxm_vc),否则验证码必然校验失败
|
||||
|
||||
③ GET /home.htm
|
||||
├─ 未登录:302 → /index.htm
|
||||
└─ 已登录:200(登录成功后用它确认会话真正可用,再落库)
|
||||
```
|
||||
|
||||
### 账号密码加密格式
|
||||
|
||||
与前端 `dxmEncrypt.js` 一致:
|
||||
|
||||
```
|
||||
"0" + 4 位随机 hex + 16 字节 IV(hex) + 16 字节 Key(hex) + AES-128-CBC 密文(hex)
|
||||
```
|
||||
|
||||
`dxm.js#encryptLoginField()` 负责实现;账号、密码各自独立加密。
|
||||
|
||||
---
|
||||
|
||||
## 2. 验证码会话的存放
|
||||
|
||||
浏览器端「取验证码 → 输入 → 登录」是两次接口请求,可能落到不同 worker,
|
||||
因此验证码绑定的 cookie 不能放内存:
|
||||
|
||||
- 后端:`GET /api/external-print-accounts/{id}/login-captcha` 取图并把会话写入 Redis
|
||||
(`service/cache.js#saveExternalPrintCaptcha`,TTL 300 秒);
|
||||
- 前端:登录按钮根据账号响应里的 `requires_login_captcha` 决定是否弹验证码框;
|
||||
- 提交登录:`POST /api/external-print-accounts/{id}/login`,body `{ captcha }`;
|
||||
后端取出会话、交给 `dxm.login({ captcha, session })`,**无论成功失败都清理验证码会话**。
|
||||
|
||||
`requires_login_captcha` 由平台实现声明(`static get loginRequiresCaptcha`),
|
||||
前端不写死平台 code。
|
||||
|
||||
---
|
||||
|
||||
## 3. 待接入
|
||||
|
||||
`dxm.js` 目前只实现 `getLoginCaptcha / login / checkSession / listShopSources`,
|
||||
其余方法继承基类会明确报「未实现」。后续按以下顺序补:
|
||||
|
||||
1. 店铺列表(授权店铺)→ `listShops`
|
||||
2. 店铺商品快照 → `listProducts`
|
||||
3. 订单列表(含明細)→ `listOrders`
|
||||
4. 取号 / 打单 / 发货回传 → `fetchWaybillNo` / `print`
|
||||
|
||||
每补一个接口,先抓真实报文确认字段口径,再补 `backend/test/app/lib/printPlatformDxm.test.js` 用例。
|
||||
Loading…
x
Reference in New Issue
Block a user