UNPKG

tax-invoice

Version:

发票SDK-提供完整的发票API开票接口

160 lines (159 loc) 5.27 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.InvoiceClient = void 0; const axios_1 = __importDefault(require("axios")); const form_data_1 = __importDefault(require("form-data")); const config_1 = require("./config"); const utils_1 = require("./utils"); /** * 发票API客户端 */ class InvoiceClient { appendFormData(formData, key, value) { if (value === undefined || value === null) { return; } if (Array.isArray(value)) { value.forEach((item, index) => { this.appendFormData(formData, `${key}[${index}]`, item); }); return; } if (typeof value === 'object') { Object.keys(value).forEach((subKey) => { this.appendFormData(formData, `${key}[${subKey}]`, value[subKey]); }); return; } formData.append(key, value); } formatDebugData(data) { try { return JSON.stringify(data, null, 2); } catch (error) { return String(data); } } debugLogRequest(method, path, headers, data) { if (!this.config.debug) { return; } const requestInfo = { url: `${this.config.baseUrl}${path}`, method: method.toUpperCase(), headers, params: data }; console.log('[TaxInvoice SDK][Request]'); console.log(this.formatDebugData(requestInfo)); } debugLogResponse(path, statusCode, responseData) { if (!this.config.debug) { return; } console.log('[TaxInvoice SDK][Response]'); // console.log(this.formatDebugData({ url: `${this.config.baseUrl}${path}`, statusCode, data: responseData })); console.log(this.formatDebugData({ StatusCode: statusCode, data: responseData })); } debugLogError(path, errorData) { if (!this.config.debug) { return; } console.log('[TaxInvoice SDK][Error]'); console.log(this.formatDebugData({ url: `${this.config.baseUrl}${path}`, data: errorData })); } /** * 构造函数 * @param config 配置信息 */ constructor(config) { this.token = ''; this.config = { ...config_1.DEFAULT_CONFIG, ...config }; if (!this.config.appKey || !this.config.appSecret) { throw new Error('AppKey和AppSecret不能为空'); } this.axiosInstance = axios_1.default.create({ baseURL: this.config.baseUrl, timeout: this.config.timeout || 150000, headers: { 'Content-Type': 'multipart/form-data' } }); } /** * 设置授权令牌 * @param token 授权令牌 */ setToken(token) { this.token = token; } /** * 获取授权令牌 * @returns 授权令牌 */ getToken() { return this.token; } /** * 发送请求 * @param method HTTP方法 * @param path 请求路径 * @param data 请求数据 * @returns 响应结果 */ async request(method, path, data = {}) { // 准备请求头参数 const randomString = utils_1.Utils.generateRandomString(20); const timestamp = utils_1.Utils.getTimestamp(); // 计算签名 const signature = utils_1.Utils.calculateSignature(method, path, randomString, timestamp, this.config.appKey, this.config.appSecret); // 设置请求头 const headers = { 'AppKey': this.config.appKey, 'Sign': signature, 'TimeStamp': timestamp, 'RandomString': randomString, 'Sdk': 'Ts1016', }; // 如果有token,添加到请求头 if (this.token) { headers['Authorization'] = this.token; } this.debugLogRequest(method, path, headers, data); const formData = new form_data_1.default(); for (const key in data) { if (Object.prototype.hasOwnProperty.call(data, key)) { this.appendFormData(formData, key, data[key]); } } try { const response = await this.axiosInstance.request({ method, url: path, data: formData, headers: { ...headers, ...formData.getHeaders() } }); this.debugLogResponse(path, response.status, response.data); return response.data; } catch (error) { if (axios_1.default.isAxiosError(error) && error.response) { this.debugLogError(path, { status: error.response.status, data: error.response.data }); throw new Error(`请求失败: ${error.response.status} ${JSON.stringify(error.response.data)}`); } this.debugLogError(path, String(error)); throw error; } } } exports.InvoiceClient = InvoiceClient;