/** * 版权 © 2024 棱雨云网络信息服务有限公司 * 开发者:小天 */ 'use strict'; const crypto = require('crypto'); class LingyuOpenApi { constructor(appkey, secret, baseUrl, timeout = 15000) { this.appkey = String(appkey); this.secret = String(secret); this.baseUrl = String(baseUrl).replace(/\/+$/, ''); this.timeout = timeout; } categories() { return this.request('GET', 'categories'); } goodsList(page = 1, perPage = 20, categoryId = 0, keyword = '') { const query = { page, per_page: perPage }; if (categoryId > 0) query.category_id = categoryId; if (keyword !== '') query.keyword = keyword; return this.request('GET', 'goods', null, query); } goodsDetail(goodsId) { return this.request('GET', 'goods/' + parseInt(goodsId, 10)); } stock(goodsIds) { return this.request('GET', 'stock', null, { goods_ids: goodsIds.map(Number).join(',') }); } createOrder(params) { return this.request('POST', 'order', params); } queryOrder(orderNo) { return this.request('GET', 'order/' + encodeURIComponent(String(orderNo))); } summary() { return this.request('GET', 'summary'); } refund(orderNo, reason = '') { return this.request('POST', 'order/refund', { order_no: String(orderNo), reason }); } async request(method, route, body = null, query = {}) { const m = String(method).toUpperCase(); const bodyRaw = body === null ? '' : JSON.stringify(body); const ts = String(Math.floor(Date.now() / 1000)); const nonce = crypto.randomBytes(8).toString('hex'); const canonical = `${m}\n${route}\n${ts}\n${nonce}\n` + crypto.createHash('sha256').update(bodyRaw).digest('hex'); const signature = crypto.createHmac('sha256', this.secret).update(canonical).digest('hex'); let url = `${this.baseUrl}/openapi.php?route=${encodeURIComponent(route)}`; const qs = new URLSearchParams(query).toString(); if (qs) url += '&' + qs; const controller = new AbortController(); const timer = setTimeout(() => controller.abort(), this.timeout); let resp; try { resp = await fetch(url, { method: m, headers: { 'Content-Type': 'application/json', appkey: this.appkey, timestamp: ts, nonce, signature, }, body: bodyRaw === '' ? undefined : bodyRaw, signal: controller.signal, }); } finally { clearTimeout(timer); } const text = await resp.text(); let data; try { data = JSON.parse(text); } catch (e) { throw new Error(`响应解析失败(HTTP ${resp.status}): ${text.slice(0, 200)}`); } if (!data || !('code' in data)) { throw new Error(`响应缺少 code 字段(HTTP ${resp.status})`); } return data; } } module.exports = { LingyuOpenApi };