#Javascript Signature Generator
#index.js
const secret = 'YOUR-API-SECRET';
const getValues = function (obj) {
let values = [];
obj = Object.keys(obj).sort().reduce(function (r, k) {
return (r[k] = obj[k], r);
}, {});
for (const key in obj) {
const value = obj[key];
if (Array.isArray(value) || (typeof value === 'object' && value !== null)) {
values.push(...getValues(value));
continue;
}
if (typeof value == 'boolean') {
values.push(value ? '1' : '0');
continue;
}
values.push(value ? value.toString() : '');
}
return values;
};
const hmac = async (message, secret) => {
const msgBuffer = new TextEncoder().encode(message);
const secretBuffer = new TextEncoder().encode(secret);
const key = await crypto.subtle.importKey('raw', secretBuffer, { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
const signatureBuffer = await crypto.subtle.sign('HMAC', key, msgBuffer);
const signatureArray = Array.from(new Uint8Array(signatureBuffer));
return signatureArray.map(b => b.toString(16).padStart(2, '0')).join('');
};
async function generateSignature(url, params, secret, salt) {
const path = (new URL(url)).pathname;
const toSign = path + getValues(params).join('') + (salt || '');
const signature = await hmac(toSign, secret);
return {
signature: signature,
salt: salt
};
}