/** * 优时开放平台 · API 客户端示例(Node.js 18+,仅内置模块和全局 fetch) * * 签名串:METHOD + "\n" + path + "\n" + X-Timestamp + "\n" + X-Nonce + "\n" + sha256_hex(body) * 签名: X-Sign = lower_hex(HMAC-SHA256(sign_key, 签名串)) * - path:实际发出的 URL 路径(保持 URL 编码原样),不含域名和查询参数,例如 /v1/tickets * - body:实际发出的请求体原始字节;没有请求体时为空 * - X-Timestamp:秒级时间戳,与服务器相差不能超过 300 秒 * - X-Nonce:16~64 位的字母、数字、下划线或短横线,10 分钟内不能重复 * * 用法: * OPEN_BASE_URL=https://open-api.yours.xyz OPEN_APPID=op_xxx OPEN_SECRET=xxx OPEN_SIGN_KEY=xxx node client.js * node client.js sign # 只计算签名(自检) */ const crypto = require('crypto'); const fs = require('fs'); const TOKEN_REFRESH_MARGIN = 300; // token 到期前多少秒就重新获取 const CODE_TOKEN_INVALID = 40102; // token 无效或过期 /** * 计算请求签名(纯函数,不读取时钟和随机数,方便和服务端对照) * @param {string|Buffer} body 请求体原始字节;字符串按 UTF-8 处理 */ function sign(signKey, method, path, timestamp, nonce, body) { const bodyHash = crypto.createHash('sha256').update(body).digest('hex'); const stringToSign = [method.toUpperCase(), path, timestamp, nonce, bodyHash].join('\n'); return crypto.createHmac('sha256', signKey).update(stringToSign, 'utf8').digest('hex'); } function describeError(title, res) { return `${title}:code=${res.code ?? '-'} msg=${res.msg ?? '-'} request_id=${res.request_id ?? '-'}`; } class YoursOpenClient { /** * @param {string} baseUrl 只写协议和域名(可带端口),不要带 /v1,例如 https://open-api.yours.xyz */ constructor(baseUrl, appid, secret, signKey, timeoutMs = 10000) { this.baseUrl = baseUrl.replace(/\/+$/, ''); this.appid = appid; this.secret = secret; this.signKey = signKey; this.timeoutMs = timeoutMs; this.accessToken = ''; this.tokenExpiresAt = 0; } /** 获取 access_token。有效期内复用;每天获取次数有限,生产环境请在多个进程之间共享缓存。 */ async token(forceRefresh = false) { if (!forceRefresh && this.accessToken && Date.now() / 1000 < this.tokenExpiresAt) { return this.accessToken; } const body = encodeJson({ appid: this.appid, secret: this.secret, grant_type: 'client_credential' }); const res = await this.send('POST', `${this.baseUrl}/oauth/token`, body, { 'Content-Type': 'application/json' }); if (res.code !== 0) { throw new Error(describeError('获取 token 失败', res)); } this.accessToken = res.data.access_token; this.tokenExpiresAt = Date.now() / 1000 + Math.max(0, Number(res.data.expires_in) - TOKEN_REFRESH_MARGIN); return this.accessToken; } /** * 调用开放接口,返回解析后的响应 {code, msg, data, request_id}(业务错误不抛异常,由调用方判断 code)。 * @param {string} path 以 / 开头、已经 URL 编码的路径,例如 /v1/tickets;查询参数放在 query 里(不参与签名) * @param {Object} [query] * @param {Object|null} [body] 请求体,会编码成 JSON;null 表示不带请求体 * @param {boolean} [signed] 是否签名。写接口(*.write)必须签名;读接口签了也没有影响 */ async request(method, path, query = {}, body = null, signed = true) { if (!path.startsWith('/') || /[?#]/.test(path)) { throw new Error('path 必须以 / 开头,且不能包含查询参数'); } const httpMethod = method.toUpperCase(); if (body !== null && body !== undefined && (httpMethod === 'GET' || httpMethod === 'HEAD')) { throw new Error('GET / HEAD 请求不能带请求体(签名包含请求体,但不会被发送)'); } const raw = body === null || body === undefined ? Buffer.alloc(0) : encodeJson(body); const qs = new URLSearchParams(query || {}).toString(); const url = this.baseUrl + path + (qs ? `?${qs}` : ''); let res = await this.sendApi(httpMethod, path, url, raw, signed, false); if (res.code === CODE_TOKEN_INVALID) { // token 被吊销或过期:重新获取一次再试(每次请求都会生成新的 nonce) res = await this.sendApi(httpMethod, path, url, raw, signed, true); } return res; } async sendApi(method, path, url, raw, signed, refreshToken) { const headers = { Authorization: `Bearer ${await this.token(refreshToken)}` }; if (raw.length > 0) { headers['Content-Type'] = 'application/json'; } if (signed) { const timestamp = String(Math.floor(Date.now() / 1000)); const nonce = crypto.randomBytes(16).toString('hex'); headers['X-Timestamp'] = timestamp; headers['X-Nonce'] = nonce; // 签的必须是下面实际发送的 raw,不能重新编码一次 headers['X-Sign'] = sign(this.signKey, method, path, timestamp, nonce, raw); } return this.send(method, url, raw, headers); } async send(method, url, body, headers) { // 不跟随重定向:POST 被重定向后会变成不带请求体的 GET,导致难以排查的签名错误 const init = { method, headers, redirect: 'manual', signal: AbortSignal.timeout(this.timeoutMs) }; if (method !== 'GET' && method !== 'HEAD') { init.body = body; } let resp; try { resp = await fetch(url, init); } catch (e) { throw new Error(`请求失败:${e.cause?.message ?? e.message}`); } const text = await resp.text(); let res = null; try { res = JSON.parse(text); } catch (e) { // 下面统一处理 } if (res === null || typeof res !== 'object' || !('code' in res)) { throw new Error(`响应不是开放平台格式(HTTP ${resp.status})`); } return res; } } function encodeJson(data) { return Buffer.from(JSON.stringify(data), 'utf8'); } /** 演示:获取 token → 查询门店 → 现场取号。需要应用拥有 store.read 和 ticket.write 权限 */ async function demo() { const config = {}; for (const name of ['OPEN_BASE_URL', 'OPEN_APPID', 'OPEN_SECRET', 'OPEN_SIGN_KEY']) { config[name] = process.env[name] || ''; if (!config[name]) { console.error(`请设置环境变量 ${name}`); return 2; } } const client = new YoursOpenClient(config.OPEN_BASE_URL, config.OPEN_APPID, config.OPEN_SECRET, config.OPEN_SIGN_KEY); try { await client.token(); console.log('获取 token 成功'); const stores = await client.request('GET', '/v1/stores'); if (stores.code !== 0 || !stores.data.items.length) { console.error(describeError('查询门店失败', stores)); return 1; } const store = stores.data.items[0]; console.log(`门店:store_id=${store.store_id} name=${store.name}`); // out_ticket_no 是你自己的单号(幂等键):超时重试时必须使用同一个单号 const stamp = new Date().toISOString().replace(/\D/g, '').slice(0, 14); const outTicketNo = `DEMO${stamp}${crypto.randomBytes(3).toString('hex')}`; const ticket = await client.request('POST', '/v1/tickets', {}, { out_ticket_no: outTicketNo, store_id: store.store_id, user: { open_user_id: 'demo_user_1', mobile: '13800000000', name: '张三' }, }); if (ticket.code !== 0) { console.error(describeError('取号失败', ticket)); return 1; } const d = ticket.data; console.log(`取号成功:ticket_id=${d.ticket_id} number=${d.number} status=${d.status} ahead_count=${d.ahead_count}`); return 0; } catch (e) { console.error(e.message); return 1; } } module.exports = { sign, YoursOpenClient }; if (require.main === module) { const args = process.argv.slice(2); if (args[0] === 'sign') { if (args.length !== 7) { console.error('用法:node client.js sign '); process.exit(2); } const [, keyArg, method, path, timestamp, nonce, bodyFile] = args; // 传 - 时从环境变量读取,避免 sign_key 出现在 shell 历史和进程列表里 const key = keyArg === '-' ? process.env.OPEN_SIGN_KEY : keyArg; console.log(sign(key, method, path, timestamp, nonce, fs.readFileSync(bodyFile))); process.exit(0); } demo().then((code) => process.exit(code)); }