'use strict'; const crypto = require('node:crypto'); const http = require('node:http'); const https = require('node:https'); /** 京东物流开放平台默认网关 */ const DEFAULT_BASE_URI = 'https://api.jdl.com'; /** 京东物流开放平台协议版本 */ const DEFAULT_VERSION = '2.0'; /** 默认签名算法(md5(content) 小写十六进制) */ const DEFAULT_ALGORITHM = 'md5-salt'; /** 单次请求默认超时时间(毫秒) */ const DEFAULT_TIMEOUT = 15000; /** 标识调用方 HTTP 客户端(与京东示例一致,仅作统计用途) */ const DEFAULT_USER_AGENT = 'lop-http/nodejs'; /** HMac 系列算法名 → node:crypto 摘要名 */ const HMAC_ALGORITHMS = { HMacMD5: 'md5', HMacSHA1: 'sha1', HMacSHA256: 'sha256', HMacSHA512: 'sha512', }; /** 只能在 request() 传入的请求级参数(init 里传会被忽略,因此显式报错) */ const REQUEST_ONLY_KEYS = [ 'path', 'method', 'body', 'query', 'headers', 'timestamp', 'now', 'raw' ]; /** * 判断输入是否为普通对象。 * @param {*} value 任意输入值。 * @return {boolean} 是否为普通对象。 */ function isPlainObject(value) { return Object.prototype.toString.call(value) === '[object Object]'; } /** * 按京东开放平台规则生成签名。 * @param {string} algorithm 算法名:md5-salt / HMacMD5 / HMacSHA1 / HMacSHA256 / HMacSHA512。 * @param {string} data 待签名原文(见 buildSignContent)。 * @param {string} [secret] 密钥(仅 HMac 系列使用)。 * @return {string} 签名值:md5-salt 为小写十六进制,HMac 系列为 base64。 * @throws {Error} 算法不支持时抛出。 */ function sign(algorithm, data, secret) { const name = String(algorithm || DEFAULT_ALGORITHM); const text = String(data === undefined || data === null ? '' : data); if (name === 'md5-salt') { return crypto.createHash('md5').update(text, 'utf8').digest('hex'); } const hmacName = HMAC_ALGORITHMS[name]; if (!hmacName) { throw new Error(`Algorithm ${name} not supported yet`); } return crypto.createHmac(hmacName, String(secret === undefined || secret === null ? '' : secret)) .update(text, 'utf8') .digest('base64'); } /** * 格式化签名为 `YYYY-MM-DD HH:mm:ss`(服务器本地时区,与京东 PHP 示例 date() 口径一致)。 * @param {Date} [date] 时间对象,默认当前时间。 * @return {string} 格式化后的时间戳。 */ function formatTimestamp(date = new Date()) { const pad = num => String(num).padStart(2, '0'); return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ` + `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`; } /** * 格式化当前时区相对 UTC 的小时数,用于 lop-tz 请求头(东八区为 '8')。 * @param {Date} [date] 时间对象,默认当前时间。 * @return {string} 时区小时数(如 '8'、'5.5'、'-5')。 */ function formatTimezoneOffset(date = new Date()) { return String(-date.getTimezoneOffset() / 60); } /** * 拼接签名原文。 * * 与京东 PHP 示例完全一致: * `secret + 'access_token' + token + 'app_key' + key + 'method' + path + * 'param_json' + body + 'timestamp' + ts + 'v' + version + secret` * * @param {Object} options 签名要素。 * @param {string} options.appSecret 应用密钥。 * @param {string} [options.accessToken] 访问令牌。 * @param {string} options.appKey 应用 AppKey。 * @param {string} options.method 接口路径(京东协议中 method 即 path)。 * @param {string} [options.paramJson] 业务报文原文。 * @param {string} options.timestamp 请求时间戳。 * @param {string} options.version 协议版本。 * @return {string} 签名原文。 */ function buildSignContent({ appSecret, accessToken, appKey, method, paramJson, timestamp, version }) { const toString = value => String(value === undefined || value === null ? '' : value); return [ toString(appSecret), 'access_token', toString(accessToken), 'app_key', toString(appKey), 'method', toString(method), 'param_json', toString(paramJson), 'timestamp', toString(timestamp), 'v', toString(version), toString(appSecret), ].join(''); } /** * 京东物流开放平台客户端(api.jdl.com)。 * * 使用方式: * ```js * const jdClient = require('./jd_client'); * jdClient.init(appKey, appSecret, { accessToken }); * const res = await jdClient.request({ * path: '/jd/tracking/query', * domain: 'Tracking_JD', * body: [{ referenceNumber: 'JDAP20626092313', referenceType: '20000', phone: '7068' }], * }); * ``` */ class JdClient { /** * @param {Object} [options={}] 默认配置。 */ constructor(options = {}) { this.options = { baseUri: DEFAULT_BASE_URI, version: DEFAULT_VERSION, algorithm: DEFAULT_ALGORITHM, timeout: DEFAULT_TIMEOUT, userAgent: DEFAULT_USER_AGENT, appKey: '', appSecret: '', accessToken: '', domain: '', logger: null, ...options, }; } /** * 初始化凭据与默认配置(可重复调用覆盖)。 * * 只能传「请求之间不变」的配置;`path` / `body` / `method` / `query` / `headers` / * `timestamp` 等请求级参数请传给 request(),误传到这里会直接报错。 * * @param {string} appKey 应用 AppKey。 * @param {string} appSecret 应用 AppSecret。 * @param {Object} [options={}] 可选默认配置。 * @param {string} [options.accessToken] 访问令牌,也可后续用 setAccessToken 设置。 * @param {string} [options.domain] 接口域(LOP-DN),如 Tracking_JD。 * @param {string} [options.baseUri] 网关地址,默认 https://api.jdl.com。 * @param {string} [options.version] 协议版本,默认 2.0。 * @param {string} [options.algorithm] 签名算法,默认 md5-salt。 * @param {number} [options.timeout] 超时毫秒数,默认 15000。 * @param {string} [options.userAgent] UA,默认 lop-http/nodejs。 * @param {Object} [options.logger] 可选日志器(需实现 warn)。 * @return {JdClient} 当前实例(便于链式调用)。 * @throws {Error} options 里出现请求级参数时抛出。 */ init(appKey, appSecret, options = {}) { const safeOptions = isPlainObject(options) ? options : {}; const invalidKeys = Object.keys(safeOptions).filter(key => REQUEST_ONLY_KEYS.includes(key)); if (invalidKeys.length > 0) { throw new Error( `init 不支持请求级参数:${invalidKeys.join(', ')},请在 request() 中传入` ); } this.options = { ...this.options, ...safeOptions, appKey: String(appKey || '').trim(), appSecret: String(appSecret || '').trim(), }; return this; } /** * 更新访问令牌。 * @param {string} accessToken 访问令牌。 * @return {JdClient} 当前实例。 */ setAccessToken(accessToken) { this.options.accessToken = String(accessToken || '').trim(); return this; } /** * 解析本次请求的凭据与配置(请求级参数优先于 init 默认值)。 * @param {Object} [options={}] 请求参数。 * @return {Object} 解析后的配置。 */ resolveOptions(options = {}) { const source = isPlainObject(options) ? options : {}; const pick = key => (source[key] === undefined || source[key] === null ? this.options[key] : source[key]); const appKey = String(pick('appKey') || '').trim(); const appSecret = String(pick('appSecret') || '').trim(); if (!appKey || !appSecret) { throw new Error('京东开放平台 appKey / appSecret 未配置'); } return { appKey, appSecret, accessToken: String(pick('accessToken') || '').trim(), domain: String(pick('domain') || '').trim(), baseUri: String(pick('baseUri') || DEFAULT_BASE_URI).replace(/\/+$/, ''), version: String(pick('version') || DEFAULT_VERSION), algorithm: String(pick('algorithm') || DEFAULT_ALGORITHM), timeout: Number(pick('timeout')) || DEFAULT_TIMEOUT, userAgent: String(pick('userAgent') || DEFAULT_USER_AGENT), logger: pick('logger') || null, }; } /** * 序列化业务报文:字符串原样使用(签名与发送必须完全一致),其余按 JSON 序列化。 * @param {*} body 业务报文。 * @return {string} param_json 原文。 */ normalizeParamJson(body) { if (body === undefined || body === null) return ''; if (typeof body === 'string') return body; return JSON.stringify(body); } /** * 构建已签名的请求参数(不发请求,便于日志与单测)。 * @param {Object} [options={}] 请求参数。 * @param {string} options.path 接口路径(如 /jd/tracking/query),京东协议中同时作为签名 method。 * @param {string} [options.method='POST'] HTTP 方法。 * @param {*} [options.body] 业务报文(对象/数组/字符串),序列化后作为 param_json。 * @param {Object} [options.query={}] 额外查询参数(如京东要求的业务 query 参数)。 * @param {Object} [options.headers={}] 额外请求头。 * @param {string} [options.timestamp] 指定时间戳(默认当前本地时间),便于复现。 * @param {Date} [options.now] 指定当前时间对象(影响时间戳与 lop-tz)。 * @return {Object} { url, method, headers, body, paramJson, sign, timestamp, content, query }。 */ buildRequestOptions(options = {}) { const { path: apiPath, method = 'POST', body, query: extraQuery = {}, headers: extraHeaders = {}, timestamp, now, } = options; const config = this.resolveOptions(options); const path = String(apiPath || '').trim(); if (!path) { throw new Error('京东接口 path 不能为空'); } const httpMethod = String(method || 'POST').toUpperCase(); const paramJson = this.normalizeParamJson(body); const nowDate = now instanceof Date ? now : new Date(); const requestTimestamp = timestamp ? String(timestamp) : formatTimestamp(nowDate); const content = buildSignContent({ appSecret: config.appSecret, accessToken: config.accessToken, appKey: config.appKey, method: path, paramJson, timestamp: requestTimestamp, version: config.version, }); const signValue = sign(config.algorithm, content, config.appSecret); const queryPairs = []; if (config.domain) queryPairs.push([ 'LOP-DN', config.domain ]); queryPairs.push([ 'app_key', config.appKey ]); queryPairs.push([ 'access_token', config.accessToken ]); queryPairs.push([ 'timestamp', requestTimestamp ]); queryPairs.push([ 'v', config.version ]); queryPairs.push([ 'sign', signValue ]); queryPairs.push([ 'algorithm', config.algorithm ]); if (httpMethod === 'GET' && paramJson) { queryPairs.push([ 'param_json', paramJson ]); } for (const [ key, value ] of Object.entries(isPlainObject(extraQuery) ? extraQuery : {})) { if (value === undefined || value === null) continue; queryPairs.push([ key, String(value) ]); } const search = new URLSearchParams(); for (const [ key, value ] of queryPairs) { search.append(key, value); } const url = `${config.baseUri}${path}${search.toString() ? `?${search.toString()}` : ''}`; const headers = { 'content-type': 'application/json;charset=utf-8', 'lop-tz': formatTimezoneOffset(nowDate), 'user-agent': config.userAgent, ...(isPlainObject(extraHeaders) ? extraHeaders : {}), }; const requestBody = httpMethod === 'GET' ? null : paramJson; if (requestBody !== null && headers['content-length'] === undefined) { headers['content-length'] = String(Buffer.byteLength(requestBody, 'utf8')); } return { url, method: httpMethod, headers, body: requestBody, paramJson, sign: signValue, timestamp: requestTimestamp, content, query: Object.fromEntries(queryPairs), timeout: config.timeout, }; } /** * 调用京东开放平台接口。 * @param {Object} [options={}] 请求参数,见 buildRequestOptions。 * @param {boolean} [options.raw=false] 为 true 时返回 { status, headers, text } 原始响应。 * @return {Promise} 默认返回 { success, status, headers, data, text, url }。 */ async request(options = {}) { const prepared = this.buildRequestOptions(options); const response = await this.send(prepared); const text = response.text; let data = null; try { data = text ? JSON.parse(text) : null; } catch (_e) { data = text; } const result = { success: response.status >= 200 && response.status < 300, status: response.status, headers: response.headers, data, text, url: prepared.url, }; if (options && options.raw === true) { return { status: response.status, headers: response.headers, text, url: prepared.url }; } return result; } /** * 发送 HTTP 请求(内置 http/https,不依赖第三方请求库)。 * @param {Object} prepared buildRequestOptions 的返回值。 * @return {Promise<{status: number, headers: Object, text: string}>} 响应。 */ send(prepared) { return new Promise((resolve, reject) => { const target = new URL(prepared.url); const transport = target.protocol === 'http:' ? http : https; const req = transport.request({ protocol: target.protocol, hostname: target.hostname, port: target.port || (target.protocol === 'http:' ? 80 : 443), path: `${target.pathname}${target.search}`, method: prepared.method, headers: prepared.headers, timeout: prepared.timeout, }, res => { const chunks = []; res.on('data', chunk => chunks.push(chunk)); res.on('end', () => { resolve({ status: Number(res.statusCode) || 0, headers: res.headers, text: Buffer.concat(chunks).toString('utf8'), }); }); res.on('error', reject); }); req.on('timeout', () => { req.destroy(new Error(`京东接口请求超时(${prepared.timeout}ms)`)); }); req.on('error', reject); if (prepared.body !== null && prepared.body !== undefined) { req.write(prepared.body); } req.end(); }); } /** * 驱动式调用:兼容 `execute({ url, body })` 写法(与其它快递驱动保持一致)。 * * - `url` 可传完整地址(自动拆成 baseUri + path + query),也可只传 path; * - `body` 为对象/数组时自动 JSON.stringify,字符串原样使用(签名与发送同一份); * - 返回类 fetch 响应对象,支持 `await res.text()` / `await res.json()`。 * * @param {Object} [request={}] 请求参数。 * @param {string} request.url 接口地址(完整 URL 或 path)。 * @param {*} [request.body] 业务报文。 * @param {string} [request.method='POST'] HTTP 方法。 * @param {Object} [request.query] 额外 query 参数。 * @param {Object} [request.headers] 额外请求头。 * @param {string} [request.domain] 接口域(LOP-DN)。 * @param {string} [request.accessToken] 覆盖默认 access_token。 * @return {Promise} { ok, status, statusText, headers, url, data, text(), json() }。 */ async execute(request = {}) { const safeRequest = isPlainObject(request) ? request : {}; const targetUrl = String(safeRequest.url || '').trim(); if (!targetUrl) { throw new Error('京东接口 url 不能为空'); } const isAbsolute = /^https?:\/\//i.test(targetUrl); const parsed = isAbsolute ? new URL(targetUrl) : null; const urlQuery = {}; if (parsed) { for (const [ key, value ] of parsed.searchParams.entries()) { urlQuery[key] = value; } } const result = await this.request({ ...safeRequest, baseUri: parsed ? `${parsed.protocol}//${parsed.host}` : safeRequest.baseUri, path: parsed ? parsed.pathname : targetUrl, query: { ...urlQuery, ...(isPlainObject(safeRequest.query) ? safeRequest.query : {}) }, }); const text = result.text === undefined || result.text === null ? '' : String(result.text); return { ok: result.success, status: result.status, statusText: result.success ? 'OK' : 'ERROR', headers: result.headers || {}, url: result.url, data: result.data, text: async () => text, json: async () => { if (text) return JSON.parse(text); return null; }, }; } } const defaultClient = new JdClient(); module.exports = { JdClient, buildSignContent, formatTimestamp, formatTimezoneOffset, sign, /** * 初始化默认客户端。 * @param {string} appKey 应用 AppKey。 * @param {string} appSecret 应用 AppSecret。 * @param {Object} [options={}] 默认配置。 * @return {JdClient} 默认客户端实例。 */ init(appKey, appSecret, options) { return defaultClient.init(appKey, appSecret, options); }, /** * 更新默认客户端的访问令牌。 * @param {string} accessToken 访问令牌。 * @return {JdClient} 默认客户端实例。 */ setAccessToken(accessToken) { return defaultClient.setAccessToken(accessToken); }, /** * 用默认客户端构建签名请求参数。 * @param {Object} [options={}] 请求参数。 * @return {Object} 已签名请求参数。 */ buildRequestOptions(options) { return defaultClient.buildRequestOptions(options); }, /** * 用默认客户端调用接口。 * @param {Object} [options={}] 请求参数。 * @return {Promise} 响应。 */ request(options) { return defaultClient.request(options); }, /** * 用默认客户端做驱动式调用(兼容 execute({ url, body }))。 * @param {Object} [request={}] 请求参数。 * @return {Promise} 类 fetch 响应(支持 text() / json())。 */ execute(request) { return defaultClient.execute(request); }, /** * 默认客户端实例。 * @return {JdClient} 实例。 */ get client() { return defaultClient; }, };