tax-invoice
Version:
发票SDK-提供完整的发票API开票接口
77 lines (76 loc) • 2.7 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Utils = void 0;
const crypto_1 = __importDefault(require("crypto"));
const decimal_js_1 = require("decimal.js");
/**
* 工具类 - 提供签名、随机字符串等通用功能
*/
class Utils {
/**
* 生成随机字符串
* @param length 字符串长度,默认20
* @returns 随机字符串
*/
static generateRandomString(length = 20) {
const characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
let randomString = '';
for (let i = 0; i < length; i++) {
randomString += characters.charAt(Math.floor(Math.random() * characters.length));
}
return randomString;
}
/**
* 获取当前时间戳(秒)
* @returns 时间戳字符串
*/
static getTimestamp() {
return Math.floor(Date.now() / 1000).toString();
}
/**
* 计算签名
* @param method HTTP方法
* @param path 请求路径
* @param randomString 随机字符串
* @param timestamp 时间戳
* @param appKey 应用密钥
* @param appSecret 应用密钥
* @returns 签名
*/
static calculateSignature(method, path, randomString, timestamp, appKey, appSecret) {
// 构建签名字符串
const signContent = `Method=${method}&Path=${path}&RandomString=${randomString}&TimeStamp=${timestamp}&AppKey=${appKey}`;
// 使用HMAC-SHA256计算签名
const hmac = crypto_1.default.createHmac('sha256', appSecret);
hmac.update(signContent);
const signature = hmac.digest('hex');
// 转为大写
return signature.toUpperCase();
}
/**
* 计算税额
* @param amount 金额
* @param taxRate 税率
* @param isIncludeTax 是否含税,默认为false
* @param scale 小数位数,默认2位
* @returns 税额
*/
static calculateTax(amount, taxRate, isIncludeTax = false, scale = 2) {
const amountDecimal = new decimal_js_1.Decimal(amount);
const taxRateDecimal = new decimal_js_1.Decimal(taxRate);
let tax;
if (isIncludeTax) {
// 含税计算:税额 = 金额 / (1 + 税率) * 税率
tax = amountDecimal.div(taxRateDecimal.add(1)).mul(taxRateDecimal);
}
else {
// 不含税计算:税额 = 金额 * 税率
tax = amountDecimal.mul(taxRateDecimal);
}
return tax.toFixed(scale);
}
}
exports.Utils = Utils;