liufumingren a586e3f18b 店小秘接入:拉取店铺商品
- 新增 listProducts:按 /api/<platform>Product/pageList.json 分页拉取,一个规格展开一行
- 字段口径:平台商品ID/规格ID/规格编码、规格名、售价、库存、上下架状态
- 单测覆盖分页、规格展开、未拉全标记、缺少店铺标识报错;补接入文档

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-23 23:56:56 +08:00

675 lines
25 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'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 { resolvePlatform } = require('../platformCode');
/** 平台配置未填链接时的默认站点 */
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';
/** 店铺列表:一个平台一个地址(/api/shop/list/<platform>.json) */
const SHOP_LIST_PATH = '/api/shop/list';
/** 店铺列表页路径(accept/referer 用) */
const SHOP_LIST_PAGE_PATH = '/web/shop/shopList';
/** 商品列表:一个平台一个接口(/api/<platform>Product/pageList.json) */
const PRODUCT_LIST_PAGE_PATH = '/web/shopifyProduct/productList';
/** 商品分页拉取:每页条数 / 最多页数 */
const PRODUCT_PAGE_SIZE = 100;
const PRODUCT_MAX_PAGES = 100;
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('; ');
}
/**
* 是否仍是登录页:未登录访问工作台会 302 到 `/index.htm`(登录页)
* @param {string} finalUrl 最终地址
* @param {string} html 页面 HTML
* @return {boolean} 是否登录页
*/
function isLoginPage(finalUrl, html) {
const url = String(finalUrl || '');
if (/\/index\.htm(\?|#|$)/i.test(url)) return true;
if (/\/(login|user\/login)/i.test(url) && !/\/web\//i.test(url)) return true;
return /id=["']loginForm["']/.test(String(html || ''));
}
/**
* 数字转换:非法/空值按 0,返回值保留原精度
* @param {*} value 原值
* @return {number} 数字
*/
function toNumber(value) {
const num = Number(value);
return Number.isFinite(num) ? num : 0;
}
/**
* 时间戳(毫秒)→ `YYYY-MM-DD HH:mm:ss`(北京时间),空值返回空串
* @param {*} value 毫秒时间戳
* @return {string} 格式化时间
*/
function formatTime(value) {
const ts = Number(value);
if (!Number.isFinite(ts) || ts <= 0) return '';
const date = new Date(ts + 8 * 3600 * 1000);
return date.toISOString().replace('T', ' ').slice(0, 19);
}
/**
* 加密登录字段(账号/密码),与服务端约定的格式见文件头注释
* @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} path 接口路径(以 / 开头,可带查询串)
* @param {Object} [options] 参数
* @param {boolean} [options.auth] 是否要求已登录,默认 true
* @param {string} [options.referer] Referer 页面路径(默认店铺列表页)
* @return {Promise<Object>} 平台 data 字段
*/
async requestJson(path, { auth = true, referer = SHOP_LIST_PAGE_PATH } = {}) {
if (auth && !this.cookie) {
throw new Error(`店小秘账号未登录:请先登录(${path})`);
}
const res = await this.request(`${this.siteUrl}${path}`, {
headers: {
...AJAX_HEADERS,
referer: `${this.siteUrl}${referer}`,
cookie: this.cookie,
},
});
const json = res.json;
if (!json) {
throw new Error(`店小秘接口返回异常(HTTP ${res.status}):${String(res.text || '').slice(0, 100)}`);
}
if (Number(json.code) !== 0) {
throw new Error(`店小秘接口失败:${json.msg || json.message || `code=${json.code}`}(${path})`);
}
return json.data || {};
}
/**
* 已授权店铺的平台标识列表
*
* 各平台的店铺列表接口都会带 `authOfPlatform.authorizePlatform`,
* 这里用 `all` 探一次,拿到账号当前真正授权的平台,再逐个平台拉店铺。
* @return {Promise<string[]>} 平台标识列表(如 shopify / shopee)
*/
async listAuthorizedPlatforms() {
if (!this._authorizedPlatforms) {
this._authorizedPlatforms = (async () => {
const data = await this.requestJson(`${SHOP_LIST_PATH}/all.json`);
const list = data.authOfPlatform && data.authOfPlatform.authorizePlatform;
return Array.isArray(list) ? list.map(item => String(item).trim()).filter(Boolean) : [];
})();
// 失败时清掉缓存,下一次调用重新探
this._authorizedPlatforms.catch(() => {
this._authorizedPlatforms = null;
});
}
return await this._authorizedPlatforms;
}
/**
* 拉取某个平台下的全部店铺(一个平台一次请求)
* @param {string} platform 平台标识(如 shopify)
* @return {Promise<{platform: string, platformName: string, list: Array}>} 平台店铺
*/
async fetchPlatformShops(platform) {
const data = await this.requestJson(`${SHOP_LIST_PATH}/${platform}.json`);
return {
platform,
platformName: String(data.platformZhName || data.platform || platform),
list: Array.isArray(data.list) ? data.list : [],
};
}
/**
* 拉取账号在所有已授权平台下的店铺,按统一结构返回
*
* 店小秘把店铺按电商平台分组(`/api/shop/list/<platform>.json`),这里合并各平台结果,
* 关键词/状态/平台过滤与分页都在本地做(平台侧店铺数量不大,且单平台接口不分页)。
* @param {Object} [options] 查询参数
* @param {string} [options.source] 来源(本平台只有 shop)
* @param {number} [options.pageIndex] 页码,从 1 开始
* @param {number} [options.pageSize] 每页条数
* @param {string} [options.keyword] 关键词(店铺名 / 店铺域名 / 平台)
* @param {string} [options.status] 状态:'' 全部 / '1' 正常 / '0' 已过期或已删除
* @param {string|string[]} [options.platformTypes] 平台过滤(如 shopify,逗号分隔)
* @return {Promise<{total: number, list: Array, source: string}>} 统一店铺列表
*/
async listShops(options = {}) {
const platforms = await this.listAuthorizedPlatforms();
const wanted = this.normalizePlatformFilter(options.platformTypes);
const targets = wanted.length ? platforms.filter(item => wanted.includes(item)) : platforms;
const shops = [];
for (const platform of targets) {
const result = await this.fetchPlatformShops(platform);
for (const shop of result.list) shops.push(this.normalizeShop(shop, result));
}
const keyword = String(options.keyword || '').trim().toLowerCase();
const status = String(options.status == null ? '' : options.status).trim();
const filtered = shops.filter(item => {
if (status === '1' && item.status !== 1) return false;
if (status === '0' && item.status === 1) return false;
if (!keyword) return true;
return `${item.name} ${item.remark} ${item.platform_name} ${item.platform}`.toLowerCase().includes(keyword);
});
filtered.sort((a, b) => (a.platform_name || '').localeCompare(b.platform_name || '') || a.name.localeCompare(b.name));
const pageIndex = Math.max(1, Number.parseInt(options.pageIndex, 10) || 1);
const pageSize = Math.min(200, Math.max(1, Number.parseInt(options.pageSize, 10) || 20));
const start = (pageIndex - 1) * pageSize;
return {
total: filtered.length,
list: filtered.slice(start, start + pageSize),
source: String(options.source || (this.listShopSources()[0] || {}).code || 'shop'),
};
}
/**
* 拉取店铺商品(全量快照),一个 SKU 一行
*
* 店小秘按平台分接口:`/api/<platform>Product/pageList.json`(实测 shopify),
* 参数与页面一致,`shopId` 为平台店铺ID,分页由 `data.page.totalPage` 决定。
* @param {Object} shop OMS 店铺记录(external_data 为平台店铺原始结构)
* @return {Promise<{total: number, verified: boolean, hosts: Array, list: Array}>} 商品快照
*/
async listProducts(shop) {
const data = (shop && shop.external_data) || {};
const shopId = String(data.id || data.Id || '').trim();
const platform = String(data.platform || '').trim();
if (!shopId) throw new Error('店铺缺少平台店铺ID,无法拉取平台商品');
if (!platform) throw new Error('店铺缺少平台标识,无法拉取平台商品');
const rows = [];
let fetched = 0;
let totalPage = 1;
let totalSize = 0;
let pages = 0;
for (let pageNo = 1; pageNo <= Math.min(totalPage, PRODUCT_MAX_PAGES); pageNo += 1) {
const page = await this.fetchProductPage(platform, shopId, pageNo);
pages += 1;
totalPage = page.totalPage || pageNo;
totalSize = page.totalSize || totalSize;
fetched += page.list.length;
for (const product of page.list) rows.push(...this.normalizeProduct(product));
if (!page.list.length) break;
}
// 平台按商品返回总数,本地按 SKU 展开,所以「拉全」用商品级计数判断
const verified = totalSize === 0 ? rows.length === 0 : fetched >= totalSize;
return {
total: rows.length,
verified,
hosts: [{
host: new URL(this.siteUrl).host,
total: totalSize,
unique: rows.length,
pages,
verified,
areas: [],
}],
list: rows,
};
}
/**
* 拉取一页商品
* @param {string} platform 平台标识(如 shopify)
* @param {string} shopId 平台店铺ID
* @param {number} pageNo 页码(1 基)
* @return {Promise<{list: Array, pageNo: number, pageSize: number, totalPage: number, totalSize: number}>} 分页结果
*/
async fetchProductPage(platform, shopId, pageNo = 1) {
const query = new URLSearchParams({
sortName: '2',
pageNo: String(pageNo),
pageSize: String(PRODUCT_PAGE_SIZE),
total: '',
sortValue: '0',
searchType: '1',
searchValue: '',
productSearchType: '0',
sellType: '0',
listingStatus: 'Active',
shopId,
dxmState: 'online',
dxmOfflineState: '',
fullCid: '',
});
const data = await this.requestJson(`/api/${platform}Product/pageList.json?${query.toString()}`, {
referer: PRODUCT_LIST_PAGE_PATH,
});
const page = data.page || {};
return {
list: Array.isArray(page.list) ? page.list : [],
pageNo: Number(page.pageNo) || pageNo,
pageSize: Number(page.pageSize) || PRODUCT_PAGE_SIZE,
totalPage: Number(page.totalPage) || 1,
totalSize: Number(page.totalSize) || 0,
};
}
/**
* 店小秘商品(含规格)→ 店铺商品行(一个规格一行)
*
* `outer_item_id` 用平台商品ID(shopifyProductId),`outer_sku_id` 用平台规格ID(shopifyVariantId),
* `outer_sku_code` 用规格 SKU 编码(可为空,订单明细匹配时按它兜底)。
* @param {Object} product 平台商品原始结构
* @return {Array<Object>} 店铺商品行
*/
normalizeProduct(product) {
const data = product || {};
const variants = Array.isArray(data.variants) && data.variants.length ? data.variants : [ null ];
const productRaw = { ...data };
delete productRaw.variants;
const platformType = resolvePlatform(data.platform).code;
const title = String(data.title || '').slice(0, 255);
const image = String(data.mainImage || '').slice(0, 255);
const status = String(data.dxmState || '') === 'offline' ? 0 : 1;
const externalShopId = String(data.shopId || '').slice(0, 64);
return variants.map(variant => {
const item = variant || {};
const options = [ item.option1, item.option2, item.option3 ].map(value => String(value || '').trim()).filter(Boolean);
const skuCode = String(item.sku || '').trim();
return {
outer_item_id: String(data.shopifyProductId || data.id || ''),
outer_sku_id: String(item.shopifyVariantId || item.id || ''),
outer_sku_code: skuCode ? skuCode.slice(0, 64) : null,
title,
outer_code: String(item.barcode || skuCode || '').slice(0, 100),
spec: options.join(' / ').slice(0, 255),
image: String(item.imageUrl || image).slice(0, 255),
price: toNumber(item.price),
stock: Math.max(0, Math.trunc(toNumber(item.inventoryQuantity))),
status,
platform_type: platformType,
external_shop_id: externalShopId,
raw: { product: productRaw, variant: variant || null },
};
});
}
/**
* 平台过滤参数归一化(支持逗号分隔字符串 / 数组)
* @param {string|string[]} value 过滤值
* @return {string[]} 平台标识列表(小写)
*/
normalizePlatformFilter(value) {
const raw = Array.isArray(value) ? value.join(',') : String(value || '');
return raw.split(',').map(item => item.trim().toLowerCase()).filter(Boolean);
}
/**
* 店小秘店铺 → 统一店铺结构(上层/前端只认这套字段)
* @param {Object} shop 平台店铺原始结构
* @param {Object} platform 平台信息 { platform, platformName }
* @return {Object} 统一店铺结构
*/
normalizeShop(shop, platform) {
const data = shop || {};
const deleted = Number(data.isDel) === 1;
const expired = Number(data.isExpire) === 1 || Number(data.isNewExpire) === 1;
const preset = resolvePlatform(data.platform);
return {
source: 'shop',
external_id: String(data.id == null ? '' : data.id),
name: String(data.name || data.sellerLoginId || data.id || ''),
contact_name: '',
contact_phone: '',
status: deleted || expired ? 0 : 1,
status_label: deleted ? '已删除' : expired ? '授权过期' : '正常',
// 平台原始标识(如 shopify)与系统预设编码(跨境平台多为 OTHER),名字优先用平台给的中文名
platform: String(data.platform || platform.platform || ''),
platform_code: preset.code,
platform_name: platform.platformName || preset.name,
auth_expired: expired,
service_expired: deleted,
auth_time: formatTime(data.authTime),
remark: String(data.sellerLoginId || ''),
raw: data,
};
}
/**
* 统一 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),
};
}
/**
* GET 并按跳跟随重定向,逐跳合并 set-cookie
*
* fetch 的 `redirect: 'follow'` 会丢掉中间跳的 Set-Cookie(平台登录后正是在 302 响应里下发
* dxm_i / dxm_w / rememberMe 等会话 cookie),所以这里手动跟随。
* @param {string} url 起始地址
* @param {string} cookie 起始 cookie
* @param {number} [maxHops] 最多跟随跳数
* @return {Promise<{status: number, finalUrl: string, html: string, cookie: string}>} 最终响应
*/
async followGet(url, cookie, maxHops = 6) {
let currentUrl = url;
let jar = String(cookie || '');
for (let hop = 0; hop < maxHops; hop += 1) {
const res = await fetch(currentUrl, {
redirect: 'manual',
headers: { ...BROWSER_HEADERS, cookie: jar },
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
});
const setCookie = getSetCookies(res);
if (setCookie.length) jar = mergeCookie(jar, setCookie);
if (res.status >= 300 && res.status < 400) {
const location = res.headers.get('location');
await res.arrayBuffer().catch(() => {});
if (!location) return { status: res.status, finalUrl: currentUrl, html: '', cookie: jar };
currentUrl = new URL(location, currentUrl).toString();
continue;
}
return { status: res.status, finalUrl: currentUrl, html: await res.text(), cookie: jar };
}
return { status: 0, finalUrl: currentUrl, html: '', cookie: jar };
}
/**
* 获取登录图形验证码:同时返回验证码图片与绑定的会话 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 访问工作台,最终落到登录页(/index.htm)即失效
*
* 已登录时 `/home.htm` 会 302 到 ERP 后台 `/web/home`,所以不能把 302 直接判为失效;
* 逐跳跟随重定向并合并每跳下发的 cookie(登录后平台会下发 dxm_i / dxm_w / rememberMe 等)。
* @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 page;
try {
page = await this.followGet(url, this.cookie);
} catch (err) {
return { loggedIn: false, message: `检查店小秘登录态失败:${err.message}`, url };
}
const loggedIn = page.status === 200 && !isLoginPage(page.finalUrl, page.html);
if (page.cookie && page.cookie !== this.cookie) await this.saveCookie(page.cookie);
await this.saveLoginStatus(loggedIn ? 1 : 0);
return {
loggedIn,
message: loggedIn ? '登录态有效' : `登录态已失效(访问工作台被重定向到登录页:${page.finalUrl})`,
url: page.finalUrl || 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.followGet(`${this.siteUrl}${HOME_PATH}`, finalCookie);
if (home.status !== 200 || isLoginPage(home.finalUrl, home.html)) {
throw new Error(
`店小秘登录后校验失败:工作台被重定向到登录页(HTTP ${home.status},${home.finalUrl || '未返回地址'})`
);
}
const sessionCookie = home.cookie || finalCookie;
await this.saveCookie(sessionCookie);
await this.saveLoginStatus(1);
return {
cookie: sessionCookie,
token: null,
redirectUrl: json.url || null,
reused: false,
shopName: '',
};
}
}
module.exports = DxmService;