- 新增 external_print_platforms(平台基础资料,开发者维护)与 external_print_accounts(账号/密码/cookie/token/登录状态) - 新增平台账号 CRUD、登录态检查、登录接口;店铺管理下新增「外部打单平台」菜单 - 平台服务按 code 独立存放于 app/lib/printPlatform(dgj.js 实现店管家登录与 GetUserInfo 登录态检查) - 平台接口 401 自动记录账号登录状态,前端展示状态并支持检查/登录 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
393 lines
14 KiB
JavaScript
393 lines
14 KiB
JavaScript
'use strict';
|
||
|
||
const PrintPlatformService = require('./base');
|
||
|
||
/** 店管家商家门户站点 */
|
||
const PORTAL_ORIGIN = 'https://tfxportal.dgjapp.com';
|
||
/** 门户登录页入口(用于登录前建立会话 cookie;未登录时访问会停在登录页) */
|
||
const PORTAL_URL = `${PORTAL_ORIGIN}/ffaccount`;
|
||
/** 登录前置接口:判断是否需要提示绑定微信 */
|
||
const BIND_WECHAT_PROMPT_URL = `${PORTAL_ORIGIN}/FFAccount/BindWeChatPrompt`;
|
||
/** 登录接口:返回 Token 与跳转地址,并通过 set-cookie 下发登录态 */
|
||
const LOGIN_URL = `${PORTAL_ORIGIN}/FFAccount/LoginPortal`;
|
||
|
||
/** 登录后的工作台域名(需同时带 token 与 cookie 才能打开) */
|
||
const WORKBENCH_HOST = 'fxali.dgjapp.com';
|
||
/** 工作台入口:?token=<登录接口返回的 Token> */
|
||
const WORKBENCH_URL = `https://${WORKBENCH_HOST}/GeneralizeIndex/`;
|
||
/** 工作台用户信息接口:返回当前登录账号的店铺/昵称等信息(需 token + cookie) */
|
||
const USER_INFO_URL = `https://${WORKBENCH_HOST}/api/user/GetUserInfo`;
|
||
|
||
/** 单次请求超时(毫秒) */
|
||
const REQUEST_TIMEOUT_MS = 15000;
|
||
|
||
/**
|
||
* 模拟 Chrome 访问 html 页面的请求头(取自真实抓包)。
|
||
* 说明:HTTP/2 伪头(:authority / :method / :path / :scheme)由客户端按 URL 自动生成,不能手动设置;
|
||
* accept-encoding 交给 fetch 自动协商并解压,手动声明会导致响应不解压。
|
||
*/
|
||
const BROWSER_HEADERS = {
|
||
accept:
|
||
'text/html,application/xhtml+xml,application/xml;q=0.9,image/jxl,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
|
||
'accept-language': 'zh-CN,zh;q=0.9',
|
||
'cache-control': 'max-age=0',
|
||
priority: 'u=0, i',
|
||
'sec-ch-ua': '"Not:A-Brand";v="8", "Chromium";v="156", "Google Chrome";v="156"',
|
||
'sec-ch-ua-mobile': '?0',
|
||
'sec-ch-ua-platform': '"Windows"',
|
||
'sec-fetch-dest': 'document',
|
||
'sec-fetch-mode': 'navigate',
|
||
'sec-fetch-site': 'none',
|
||
'sec-fetch-user': '?1',
|
||
'upgrade-insecure-requests': '1',
|
||
'user-agent':
|
||
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/156.0.0.0 Safari/537.36',
|
||
};
|
||
|
||
/** 模拟浏览器 ajax 表单提交的请求头(登录接口为同源 XHR) */
|
||
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',
|
||
origin: PORTAL_ORIGIN,
|
||
referer: PORTAL_URL,
|
||
'sec-ch-ua': '"Not:A-Brand";v="8", "Chromium";v="156", "Google Chrome";v="156"',
|
||
'sec-ch-ua-mobile': '?0',
|
||
'sec-ch-ua-platform': '"Windows"',
|
||
'sec-fetch-dest': 'empty',
|
||
'sec-fetch-mode': 'cors',
|
||
'sec-fetch-site': 'same-origin',
|
||
'user-agent':
|
||
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/156.0.0.0 Safari/537.36',
|
||
'x-requested-with': 'XMLHttpRequest',
|
||
};
|
||
|
||
/** 模拟工作台 ajax(GET 接口)的请求头,Referer 指向工作台 */
|
||
const WORKBENCH_AJAX_HEADERS = {
|
||
accept: 'application/json, text/javascript, */*; q=0.01',
|
||
'accept-language': 'zh-CN,zh;q=0.9',
|
||
referer: WORKBENCH_URL,
|
||
'sec-ch-ua': '"Not:A-Brand";v="8", "Chromium";v="156", "Google Chrome";v="156"',
|
||
'sec-ch-ua-mobile': '?0',
|
||
'sec-ch-ua-platform': '"Windows"',
|
||
'user-agent':
|
||
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/156.0.0.0 Safari/537.36',
|
||
'x-requested-with': 'XMLHttpRequest',
|
||
};
|
||
|
||
/**
|
||
* 登录表单字段加密:店管家要求 IsEnc=1 时字段值做 base64(URLSearchParams 会再对 = 等字符做 URL 编码)
|
||
* @param {string} value 原始值
|
||
* @return {string} base64 值
|
||
*/
|
||
function encodeField(value) {
|
||
return Buffer.from(String(value), 'utf8').toString('base64');
|
||
}
|
||
|
||
/**
|
||
* 读取响应里的 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 {{status: number, json: Object|null}} res 接口响应
|
||
* @return {string} 失败原因
|
||
*/
|
||
function describeFailure(res) {
|
||
const json = (res && res.json) || {};
|
||
const message = json.Message || json.ErrorCode || '未知错误';
|
||
return `${message}(HTTP ${res ? res.status : '-'})`;
|
||
}
|
||
|
||
/**
|
||
* 店管家(dgj)外部打单平台服务。
|
||
*
|
||
* 平台记录:external_print_platforms.code = 'dgj'(名称「店管家」,fetch_waybill_no = 0 即不回平台取号)。
|
||
* 该平台的全部处理逻辑(登录、打单、取号等)都写在本文件里,不要散落到别处;
|
||
* 新增平台时同样新建 `<平台 code>.js`,并把 static code 改成对应平台标识。
|
||
*
|
||
* 登录流程(与浏览器一致):
|
||
* 1. GET /ffaccount 建立会话(拿到 WAF/ASP.NET 基础 cookie)
|
||
* 2. POST /FFAccount/BindWeChatPrompt(是否需要提示绑定微信)
|
||
* 3. POST /FFAccount/LoginPortal(返回 Token / RedirectUrl,并通过 set-cookie 下发登录态)
|
||
* 4. GET /api/user/GetUserInfo?token=<Token>(需同时带 cookie)确认登录态并拿账号信息
|
||
* 成功后把 token 与 cookie 一并写回账号表,后续检查/调用复用。
|
||
*
|
||
* 注意:店管家工作台同时依赖 token 与 cookie,仅保存 cookie 无法获取账号信息(返回 401)。
|
||
* 登录态检查走 GetUserInfo(轻量 JSON,避免每次拉取 500KB 的工作台页面)。
|
||
*/
|
||
class DgjService extends PrintPlatformService {
|
||
static get code() {
|
||
return 'dgj';
|
||
}
|
||
|
||
/**
|
||
* 店管家站点根地址(平台配置的链接未带协议时补 https://)
|
||
* @return {string} 站点根地址
|
||
*/
|
||
get siteUrl() {
|
||
const url = String(this.platform.url || '').trim();
|
||
if (!url) throw new Error('店管家平台未配置链接地址(external_print_platforms.url)');
|
||
return /^https?:\/\//i.test(url) ? url : `https://${url}`;
|
||
}
|
||
|
||
/**
|
||
* 统一平台请求入口(请求拦截器)。
|
||
* 平台接口返回 401 表示登录已失效,这里统一把账号登录状态记为 0;
|
||
* 其余状态交由调用方按业务判断。
|
||
* @param {string} url 完整请求地址
|
||
* @param {Object} [options] fetch 选项(method / headers / body 等)
|
||
* @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;
|
||
}
|
||
|
||
if (res.status === 401) {
|
||
await this.saveLoginStatus(0);
|
||
}
|
||
|
||
return { status: res.status, json, text, setCookies: getSetCookies(res) };
|
||
}
|
||
|
||
/**
|
||
* 拉取工作台当前登录账号信息(需 token + cookie,缺一不可)
|
||
* @param {string} [token] 登录 token,默认取账号已保存的 token
|
||
* @param {string} [cookie] 会话 cookie,默认取账号已保存的 cookie
|
||
* @return {Promise<{success: boolean, status: number, message: string, data: Object|null, setCookies: string[]}>} 账号信息
|
||
*/
|
||
async getUserInfo(token = this.token, cookie = this.cookie) {
|
||
const tk = String(token || '').trim();
|
||
if (!tk) throw new Error('店管家账号未保存登录 token,无法获取账号信息');
|
||
|
||
const query = new URLSearchParams({
|
||
traceId: '',
|
||
dbname: '',
|
||
dataFlag: '',
|
||
IsCustomerOrder: 'false',
|
||
FxPageType: '1',
|
||
_: String(Date.now()),
|
||
token: tk,
|
||
});
|
||
|
||
const headers = { ...WORKBENCH_AJAX_HEADERS };
|
||
if (cookie) headers.cookie = cookie;
|
||
|
||
const res = await this.request(`${USER_INFO_URL}?${query.toString()}`, { method: 'GET', headers });
|
||
|
||
const success = res.status === 200 && !!res.json && res.json.Success === true;
|
||
if (success) await this.saveLoginStatus(1);
|
||
|
||
return {
|
||
success,
|
||
status: res.status,
|
||
message: (res.json && res.json.Message) || '',
|
||
data: success && res.json.Data ? res.json.Data : null,
|
||
setCookies: res.setCookies,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 登录:token + cookie 有效时直接复用;否则用账号密码登录,
|
||
* 成功后把 token 与 cookie 写回账号表,避免上下文丢失
|
||
* @return {Promise<{cookie: string, token: string|null, redirectUrl: string|null, reused: boolean}>} 登录结果
|
||
*/
|
||
async login() {
|
||
if (this.cookie && this.token) {
|
||
const status = await this.checkSession();
|
||
if (status.loggedIn) {
|
||
return { cookie: this.cookie, token: this.token, redirectUrl: null, reused: true, shopName: status.shopName || '' };
|
||
}
|
||
}
|
||
return this.loginByPassword();
|
||
}
|
||
|
||
/**
|
||
* 检查当前账号登录态:token/cookie 缺失视为未登录;
|
||
* 都有则打开工作台校验(未登录会被重定向回门户登录页)
|
||
* @return {Promise<{loggedIn: boolean, message: string, url: string}>} 登录态检查结果
|
||
*/
|
||
async checkSession() {
|
||
if (!this.token) {
|
||
await this.saveLoginStatus(0);
|
||
return { loggedIn: false, message: '账号未保存登录 token,尚未登录', url: USER_INFO_URL };
|
||
}
|
||
if (!this.cookie) {
|
||
await this.saveLoginStatus(0);
|
||
return { loggedIn: false, message: '账号未保存会话 cookie,尚未登录', url: USER_INFO_URL };
|
||
}
|
||
|
||
const info = await this.getUserInfo(this.token, this.cookie);
|
||
const loggedIn = info.success;
|
||
if (!loggedIn) await this.saveLoginStatus(0);
|
||
|
||
return {
|
||
loggedIn,
|
||
message: loggedIn ? '登录态有效' : `登录态已失效${info.message ? `(${info.message})` : ''}`,
|
||
url: USER_INFO_URL,
|
||
nickname: info.data ? info.data.FxUserNickName || info.data.NickName || '' : '',
|
||
shopName: info.data ? info.data.ShopName || '' : '',
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 账号密码登录(两次 POST:BindWeChatPrompt → LoginPortal)
|
||
* @return {Promise<{cookie: string, token: string|null, redirectUrl: string|null, reused: boolean}>} 登录结果
|
||
*/
|
||
async loginByPassword() {
|
||
const { account, password } = this.getCredentials();
|
||
let cookie = await this.bootstrapSession();
|
||
|
||
const prompt = await this.postForm(BIND_WECHAT_PROMPT_URL, this.buildLoginForm(account, password, false), cookie);
|
||
cookie = mergeCookie(cookie, prompt.setCookies);
|
||
if (!this.isSuccess(prompt)) {
|
||
throw new Error(`店管家登录前置校验失败:${describeFailure(prompt)}`);
|
||
}
|
||
|
||
const result = await this.postForm(LOGIN_URL, this.buildLoginForm(account, password, true), cookie);
|
||
cookie = mergeCookie(cookie, result.setCookies);
|
||
const data = result.json && result.json.Data;
|
||
if (!this.isSuccess(result) || !data || !data.Token) {
|
||
throw new Error(`店管家登录失败:${describeFailure(result)}`);
|
||
}
|
||
|
||
// 用登录返回的 token + cookie 拉取账号信息,确认登录态真正可用后再落库
|
||
const info = await this.getUserInfo(data.Token, cookie);
|
||
if (!info.success) {
|
||
throw new Error(`店管家登录后校验失败:${info.message || '获取账号信息失败'}`);
|
||
}
|
||
|
||
await this.saveCookie(cookie);
|
||
await this.saveToken(data.Token);
|
||
return {
|
||
cookie,
|
||
token: data.Token,
|
||
redirectUrl: data.RedirectUrl || null,
|
||
reused: false,
|
||
shopName: info.data ? info.data.ShopName || '' : '',
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 访问门户建立会话,拿到 WAF / ASP.NET 基础 cookie
|
||
* @return {Promise<string>} 新建的 cookie
|
||
*/
|
||
async bootstrapSession() {
|
||
const res = await fetch(PORTAL_URL, {
|
||
method: 'GET',
|
||
headers: BROWSER_HEADERS,
|
||
redirect: 'follow',
|
||
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
||
});
|
||
// 只需要响应头里的 set-cookie,正文丢弃
|
||
await res.arrayBuffer().catch(() => {});
|
||
return mergeCookie('', getSetCookies(res));
|
||
}
|
||
|
||
/**
|
||
* 组装登录表单(IsEnc=1:Mobile/Password 做 base64;LoginPortal 额外带空参数)
|
||
* @param {string} account 登录账号
|
||
* @param {string} password 登录密码
|
||
* @param {boolean} forPortal 是否为 LoginPortal 接口
|
||
* @return {URLSearchParams} 表单
|
||
*/
|
||
buildLoginForm(account, password, forPortal) {
|
||
const form = new URLSearchParams();
|
||
form.set('Mobile', encodeField(account));
|
||
form.set('Password', encodeField(password));
|
||
form.set('ValidCode', '');
|
||
form.set('IsEnc', '1');
|
||
form.set('NotUseAliyunCaptcha', 'true');
|
||
if (forPortal) {
|
||
form.set('ShopId', '');
|
||
form.set('From', '');
|
||
form.set('PlatformType', '');
|
||
}
|
||
return form;
|
||
}
|
||
|
||
/**
|
||
* 以浏览器 ajax 方式提交登录表单
|
||
* @param {string} url 接口地址
|
||
* @param {URLSearchParams} form 表单
|
||
* @param {string} cookie 会话 cookie
|
||
* @return {Promise<{status: number, json: Object|null, text: string, setCookies: string[]}>} 接口响应
|
||
*/
|
||
async postForm(url, form, cookie) {
|
||
const headers = { ...AJAX_HEADERS };
|
||
if (cookie) headers.cookie = cookie;
|
||
|
||
return this.request(url, {
|
||
method: 'POST',
|
||
headers,
|
||
body: form.toString(),
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 接口是否返回 Success = true
|
||
* @param {{json: Object|null}} res 接口响应
|
||
* @return {boolean} 是否成功
|
||
*/
|
||
isSuccess(res) {
|
||
return !!(res && res.json && res.json.Success === true);
|
||
}
|
||
|
||
/**
|
||
* 把订单推送到店管家打印
|
||
* @param {Object} order 订单数据(字段口径由店管家协议决定)
|
||
* @return {Promise<Object>} 平台响应
|
||
*/
|
||
async print(order) {
|
||
throw new Error(`店管家未实现 print(),订单:${order && order.id}`);
|
||
}
|
||
|
||
/**
|
||
* 店管家不回平台取号(平台配置 fetch_waybill_no = 0),调用即视为错误
|
||
* @return {Promise<never>} 固定抛错
|
||
*/
|
||
async fetchWaybillNo() {
|
||
throw new Error('店管家不回平台取号(fetch_waybill_no=0),不应调用 fetchWaybillNo()');
|
||
}
|
||
}
|
||
|
||
module.exports = DgjService;
|