signCore.js 1.1 KB
const qs = require("qs");
const md5 = require("md5");
const sha1 = require("sha1");

function deepClone(obj) {
	return JSON.parse(JSON.stringify(obj));
}

/**
 * ROP 请求签名(与 src/api/sign.js 逻辑一致)
 */
function sign(params, noSignAttr = [], secret, way = "sha1") {
	const payload = { ...params };
	delete payload.sign;
	const objStr = qs.stringify(deepClone(payload), {
		arrayFormat: "indices",
		allowDots: true,
		encodeValuesOnly: true,
	});
	const realObj = {};
	objStr.split("&").forEach((item) => {
		const idx = item.indexOf("=");
		realObj[item.slice(0, idx)] = decodeURIComponent(item.slice(idx + 1));
	});
	const keys = Object.keys(realObj).sort();
	const str = [];
	for (const key in realObj) {
		let obj = realObj[key];
		if (obj === null) {
			obj = "";
		} else if (typeof obj === "object") {
			obj = JSON.stringify(obj);
		}
		realObj[key] = obj;
	}
	keys.forEach((e) => {
		if (!noSignAttr.includes(e)) {
			str.push(e + realObj[e]);
		}
	});
	const signObj = { sha1, md5 };
	realObj.sign = signObj[way](secret + str.join("") + secret).toUpperCase();
	return realObj;
}

module.exports = sign;