29 lines
933 B
TypeScript
29 lines
933 B
TypeScript
import { createHash, createHmac } from 'crypto';
|
|
import type { XiaofeixiaSignType } from '../courier.config';
|
|
|
|
type SignParams = Record<string, string | number | undefined | null>;
|
|
|
|
function isEmpty(value: unknown): boolean {
|
|
return value === undefined || value === null || value === '';
|
|
}
|
|
|
|
/** 按 ASCII 字典序拼接并生成签名 */
|
|
export function buildXiaofeixiaSign(
|
|
params: SignParams,
|
|
apiKey: string,
|
|
signType: XiaofeixiaSignType = 'MD5',
|
|
): string {
|
|
const sortedKeys = Object.keys(params)
|
|
.filter((key) => key !== 'sign' && !isEmpty(params[key]))
|
|
.sort();
|
|
|
|
const stringA = sortedKeys.map((key) => `${key}=${params[key]}`).join('&');
|
|
const stringSignTemp = `${stringA}&key=${apiKey}`;
|
|
|
|
if (signType === 'HMAC-SHA256') {
|
|
return createHmac('sha256', apiKey).update(stringSignTemp).digest('hex').toUpperCase();
|
|
}
|
|
|
|
return createHash('md5').update(stringSignTemp).digest('hex').toUpperCase();
|
|
}
|