修正店小秘面单 PDF 取错接口(取到「发货单不存在」的错误 PDF)
问题:之前用 /api/pddkjInventory/printExpressNote.json?id=<包裹ID> 取面单, 那是「拼多多跨境备货单」的标签接口,传订单包裹ID 会返回一张解压后文字为 「发货单不存在」的 PDF(同样以 %PDF 开头,只看前缀查不出来)。 修正:改用服务端打印页 printMb.htm GET /printMb.htm?packageIds=<包裹ID>&authId=<店铺授权ID>&isCos=1 → 302 https://print.dianxiaomi.com/<日期>/<uuid>.pdf → 200 application/pdf - 新增 requestPdf(手动处理跳转,跨域那一跳不带 OMS 账号 cookie) - fetchPrintPdf 改走 printMb.htm;仍保留 checkPrint 取面单格式/校验 - 单测改为验证两跳链路(打印页带 cookie、跨域 PDF 不带 cookie),补 302 缺 location 的用例 - 文档 6/6.1 更新下载方式,并记下 printExpressNote 的坑 实测(包裹 184804424061188407 / 运单 3CAB6112200001): 面单 base64 150,136 字符,解码文字含收件人 Daniel Puccio / 92223 / +19515057679; 取号记录 pdf_base64 落库 150,136、result_data 仅 417 字节。 本地已清掉两条用错误接口生成的取号记录与幂等记录。 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
parent
368e1c19fc
commit
db2c232aad
@ -58,8 +58,13 @@ const ORDER_MAX_PAGES = 100;
|
||||
/** 打印数据校验:返回面单格式与平台侧缓存文件名(fileName 不能直接访问) */
|
||||
const CHECK_PRINT_PATH = '/api/checkPrint.json';
|
||||
|
||||
/** 面单文件下载:按包裹ID 返回 application/pdf(前端打印页也是走这个接口取 blob) */
|
||||
const PRINT_FILE_PATH = '/api/pddkjInventory/printExpressNote.json';
|
||||
/**
|
||||
* 面单打印页:`printMb.htm?packageIds=<包裹ID>&authId=<店铺授权ID>&isCos=1`
|
||||
*
|
||||
* 服务端渲染的 PDF 下载入口(前端「打印面单」就是 `window.open` 这个地址):
|
||||
* 首次请求 302 到 `https://print.dianxiaomi.com/<yyyy-MM-dd>/<uuid>.pdf`,再取真实 PDF。
|
||||
*/
|
||||
const PRINT_MB_PATH = '/printMb.htm';
|
||||
|
||||
/** 标记「已打印面单」:入参 packageId(实测:isPrintMd true + mdSignTime 写入) */
|
||||
const SET_PRINT_PATH = '/api/package/setPrint.json';
|
||||
@ -679,12 +684,36 @@ class DxmService extends PrintPlatformService {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 二进制/PDF 请求(手动处理跳转,便于把跨域那一段的账号 cookie 去掉)
|
||||
* @param {string} url 完整请求地址
|
||||
* @param {Object} [options] fetch 选项
|
||||
* @return {Promise<{status: number, buffer: Buffer, contentType: string, location: string}>} 响应
|
||||
*/
|
||||
async requestPdf(url, options = {}) {
|
||||
const res = await fetch(url, {
|
||||
redirect: 'manual',
|
||||
...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') || ''),
|
||||
location: String(res.headers.get('location') || ''),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 取面单 PDF(打印数据)
|
||||
*
|
||||
* 两步:`checkPrint.json` 校验该包裹可打印并返回面单格式(同时生成平台侧缓存),
|
||||
* 再 `printExpressNote.json?id=<包裹ID>` 拿真正的 PDF 流。返回的 `fileName` 是店小秘
|
||||
* 服务器内部相对路径(拼域名访问 404),只能留痕,不能当下载链接。
|
||||
* 再走服务端打印页 `printMb.htm?packageIds=<包裹ID>&authId=<授权ID>&isCos=1`
|
||||
* 拿真正的 PDF(首次 302 到 `print.dianxiaomi.com/<日期>/<uuid>.pdf`,跟随后才是 PDF 流)。
|
||||
*
|
||||
* 注意:不能用 `/api/pddkjInventory/printExpressNote.json`——那是拼多多跨境备货单的标签接口,
|
||||
* 传订单包裹ID 会返回一张写着「发货单不存在」的错误 PDF。
|
||||
* @param {Object} params 参数
|
||||
* @param {string} params.authId 店铺授权ID(订单报文 authId)
|
||||
* @param {string} params.packageId 包裹ID(= OMS external_order_id)
|
||||
@ -694,29 +723,38 @@ class DxmService extends PrintPlatformService {
|
||||
if (!this.cookie) throw new Error('店小秘账号未登录:请先登录');
|
||||
const id = String(packageId || '').trim();
|
||||
if (!id) throw new Error('缺少包裹ID,无法取打印数据');
|
||||
const shopAuthId = String(authId || '').trim();
|
||||
|
||||
let meta = {};
|
||||
if (String(authId || '').trim()) {
|
||||
const form = new URLSearchParams({ authId: String(authId).trim(), packageIds: id });
|
||||
if (shopAuthId) {
|
||||
const form = new URLSearchParams({ authId: shopAuthId, packageIds: id });
|
||||
meta = await this.requestForm(CHECK_PRINT_PATH, form, { referer: ORDER_LIST_PAGE_PATH });
|
||||
}
|
||||
|
||||
const res = await this.requestBinary(`${this.siteUrl}${PRINT_FILE_PATH}?id=${encodeURIComponent(id)}`, {
|
||||
headers: {
|
||||
...AJAX_HEADERS,
|
||||
accept: 'application/pdf,*/*',
|
||||
referer: `${this.siteUrl}${ORDER_LIST_PAGE_PATH}`,
|
||||
cookie: this.cookie,
|
||||
},
|
||||
const query = new URLSearchParams({ packageIds: id, isCos: '1' });
|
||||
if (shopAuthId) query.set('authId', shopAuthId);
|
||||
const url = `${this.siteUrl}${PRINT_MB_PATH}?${query.toString()}`;
|
||||
const referer = `${this.siteUrl}${ORDER_LIST_PAGE_PATH}`;
|
||||
|
||||
let res = await this.requestPdf(url, {
|
||||
headers: { ...BROWSER_HEADERS, accept: 'application/pdf,*/*', referer, cookie: this.cookie },
|
||||
});
|
||||
// 302 → print.dianxiaomi.com/...pdf:跨域取文件不带 OMS 账号的 cookie
|
||||
if (res.status >= 300 && res.status < 400 && res.location) {
|
||||
const target = new URL(res.location, url).toString();
|
||||
res = await this.requestPdf(target, {
|
||||
headers: { accept: 'application/pdf,*/*', 'user-agent': USER_AGENT },
|
||||
});
|
||||
}
|
||||
if (res.status !== 200 || !res.buffer.length) {
|
||||
throw new Error(`店小秘取面单文件失败:HTTP ${res.status}`);
|
||||
}
|
||||
const mime = (res.contentType.split(';')[0] || '').trim().toLowerCase();
|
||||
if (!mime.includes('pdf')) {
|
||||
const isPdf = mime.includes('pdf') || res.buffer.slice(0, 4).toString('latin1') === '%PDF';
|
||||
if (!isPdf) {
|
||||
throw new Error(`店小秘取面单文件失败:返回的不是 PDF(${mime || 'unknown'}):${res.buffer.toString('utf8').slice(0, 100)}`);
|
||||
}
|
||||
return { mime, base64: res.buffer.toString('base64'), meta };
|
||||
return { mime: mime.includes('pdf') ? mime : 'application/pdf', base64: res.buffer.toString('base64'), meta };
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@ -493,43 +493,56 @@ describe('printPlatform/dxm fetchWaybillNo', () => {
|
||||
});
|
||||
|
||||
describe('printPlatform/dxm fetchPrintPdf', () => {
|
||||
it('先 checkPrint 校验,再按包裹ID 下载 PDF 并转 base64', async () => {
|
||||
it('先 checkPrint 校验,再走 printMb.htm 拿 PDF(302 后跟到 print 域名)', async () => {
|
||||
const { service } = createService({ account: { cookie: 'JSESSIONID=ok' } });
|
||||
const forms = [];
|
||||
service.requestForm = async (path, form) => {
|
||||
forms.push({ path, authId: form.get('authId'), packageIds: form.get('packageIds') });
|
||||
return { fileName: 'singleCache/x.pdf', printFormat: '标签纸(10*10厘米)+标签(PDF)' };
|
||||
};
|
||||
const urls = [];
|
||||
service.requestBinary = async url => {
|
||||
urls.push(url);
|
||||
return { status: 200, buffer: Buffer.from('%PDF-1.4 test'), contentType: 'application/pdf;charset=UTF-8', setCookies: [] };
|
||||
const requests = [];
|
||||
service.requestPdf = async (url, options) => {
|
||||
requests.push({ url, cookie: (options && options.headers && options.headers.cookie) || '' });
|
||||
if (requests.length === 1) {
|
||||
return { status: 302, buffer: Buffer.alloc(0), contentType: '', location: 'https://print.dianxiaomi.com/2026-11-24/abc.pdf' };
|
||||
}
|
||||
return { status: 200, buffer: Buffer.from('%PDF-1.4 test'), contentType: 'application/pdf', location: '' };
|
||||
};
|
||||
|
||||
const result = await service.fetchPrintPdf({ authId: '182586000431422845', packageId: '184804424059302467' });
|
||||
const result = await service.fetchPrintPdf({ authId: '182586000431422845', packageId: '184804424061188407' });
|
||||
|
||||
assert.deepStrictEqual(forms, [{ path: '/api/checkPrint.json', authId: '182586000431422845', packageIds: '184804424059302467' }]);
|
||||
assert.match(urls[0], /\/api\/pddkjInventory\/printExpressNote\.json\?id=184804424059302467$/);
|
||||
assert.deepStrictEqual(forms, [{ path: '/api/checkPrint.json', authId: '182586000431422845', packageIds: '184804424061188407' }]);
|
||||
// 第一跳打打印页(带账号 cookie),第二跳取跨域 PDF(不带账号 cookie)
|
||||
assert.match(requests[0].url, /\/printMb\.htm\?packageIds=184804424061188407&isCos=1&authId=182586000431422845$/);
|
||||
assert.match(requests[0].cookie, /JSESSIONID=ok/);
|
||||
assert.strictEqual(requests[1].url, 'https://print.dianxiaomi.com/2026-11-24/abc.pdf');
|
||||
assert.strictEqual(requests[1].cookie, '');
|
||||
assert.strictEqual(result.mime, 'application/pdf');
|
||||
assert.strictEqual(Buffer.from(result.base64, 'base64').toString('utf8'), '%PDF-1.4 test');
|
||||
assert.strictEqual(result.meta.printFormat, '标签纸(10*10厘米)+标签(PDF)');
|
||||
});
|
||||
|
||||
it('没有 authId 时跳过 checkPrint,直接下载', async () => {
|
||||
it('没有 authId 时跳过 checkPrint,直接打打印页', async () => {
|
||||
const { service } = createService({ account: { cookie: 'JSESSIONID=ok' } });
|
||||
service.requestForm = async () => {
|
||||
throw new Error('不该调用 checkPrint');
|
||||
};
|
||||
service.requestBinary = async () => ({ status: 200, buffer: Buffer.from('%PDF'), contentType: 'application/pdf', setCookies: [] });
|
||||
service.requestPdf = async () => ({ status: 200, buffer: Buffer.from('%PDF'), contentType: 'application/pdf', location: '' });
|
||||
const result = await service.fetchPrintPdf({ packageId: '123' });
|
||||
assert.deepStrictEqual(result.meta, {});
|
||||
});
|
||||
|
||||
it('返回不是 PDF 时报可读错误', async () => {
|
||||
const { service } = createService({ account: { cookie: 'JSESSIONID=ok' } });
|
||||
service.requestBinary = async () => ({ status: 200, buffer: Buffer.from('<html>err</html>'), contentType: 'text/html', setCookies: [] });
|
||||
service.requestPdf = async () => ({ status: 200, buffer: Buffer.from('<html>err</html>'), contentType: 'text/html', location: '' });
|
||||
await assert.rejects(service.fetchPrintPdf({ packageId: '123' }), /返回的不是 PDF/);
|
||||
});
|
||||
|
||||
it('跳转目标缺失时按 HTTP 状态报错', async () => {
|
||||
const { service } = createService({ account: { cookie: 'JSESSIONID=ok' } });
|
||||
service.requestPdf = async () => ({ status: 302, buffer: Buffer.alloc(0), contentType: '', location: '' });
|
||||
await assert.rejects(service.fetchPrintPdf({ packageId: '123' }), /HTTP 302/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('printPlatform/dxm 打印状态', () => {
|
||||
|
||||
17
店小秘接入.md
17
店小秘接入.md
@ -258,15 +258,17 @@ POST /api/checkPrint.json (x-www-form-urlencoded,需登录 cookie
|
||||
authId=<店铺授权ID>&packageIds=<包裹ID>
|
||||
→ { code: 0, data: { success: 1, printMbFormats: "物流商系统面单",
|
||||
printFormat: "标签纸(10*10厘米)+标签(PDF)",
|
||||
fileName: "singleCache/<uuid>/2026-11-21/<包裹ID>_<运单号>_20103_0.pdf" } }
|
||||
fileName: "singleCache/<uuid>/2026-11-24/<包裹ID>_<运单号>_20103_0.pdf" } }
|
||||
|
||||
GET /api/pddkjInventory/printExpressNote.json?id=<包裹ID>
|
||||
→ application/pdf(实测 200,约 66KB,内容以 %PDF-1.4 开头)
|
||||
GET /printMb.htm?packageIds=<包裹ID>&authId=<店铺授权ID>&isCos=1
|
||||
→ 302 Location: https://print.dianxiaomi.com/<yyyy-MM-dd>/<uuid>.pdf
|
||||
→ 200 application/pdf(真实面单:收件人/地址/电话/条码都在里面)
|
||||
```
|
||||
|
||||
`fileName` 是店小秘服务器上的相对路径,**不能直接拼域名访问**(`/singleCache/...` 等均 404);
|
||||
真正取文件走 `printExpressNote.json?id=<包裹ID>`(前端打印页 `printPage` 也是这么做的,
|
||||
拿到 blob 后塞进 iframe 打印)。
|
||||
`checkPrint` 返回的 `fileName` 是店小秘服务器上的内部相对路径,**不能直接拼域名访问**(`/singleCache/...` 均 404);
|
||||
真正下载面单走 `printMb.htm`(前端「打印面单」就是 `window.open` 这个地址,见 `usePackage` 里的 `printMb`)。
|
||||
⚠️ 不要用 `/api/pddkjInventory/printExpressNote.json`——那是**拼多多跨境备货单**标签接口,
|
||||
传订单包裹ID 会返回一张写着「发货单不存在」的 PDF(踩过这个坑,PDF 前缀同样是 `%PDF`,只能靠解码文字才能发现)。
|
||||
|
||||
`dxm.js` 目前实现 `getLoginCaptcha / login / checkSession / listShopSources / listShops / listProducts /
|
||||
listOrders / fetchWaybillNo / fetchPrintPdf / markPrinted / print`,发货回传仍继承基类报「未实现」。
|
||||
@ -285,7 +287,8 @@ listOrders / fetchWaybillNo / fetchPrintPdf / markPrinted / print`,发货回
|
||||
采用「**现拉 → base64**」,不落盘、不进 COS:
|
||||
|
||||
- `dxm.js#fetchPrintPdf({authId, packageId})`:先用 `checkPrint.json` 校验并拿到面单格式,
|
||||
再 `GET printExpressNote.json?id=<包裹ID>` 取 PDF 流,返回 `{ mime, base64, meta }`;
|
||||
再 `GET printMb.htm?packageIds=…&authId=…&isCos=1`,跟随 302 到 `print.dianxiaomi.com/<日期>/<uuid>.pdf`
|
||||
取 PDF 流(跨域那一跳不带账号 cookie),返回 `{ mime, base64, meta }`;
|
||||
- `fetchWaybillNo` 取号时顺带拉面单,以 **`pdf_base64`(纯 base64,不含 `data:` 前缀)** 返回,
|
||||
由取号链路(`waybillGet`)透传给 WMS 并写进 `waybill_fetch_records.pdf_base64`
|
||||
(`TEXT('medium')`,上限 16MB);`printinfo` 留空。PDF 拉取失败只记 `raw.print_error`,
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user