1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
| <!DOCTYPE html> <html> <head> <title>签名测试</title> <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/crypto-js.min.js"></script> </head> <body> <button onclick="sendRequest()">发送请求</button>
<script>
const config = { appId: "appId", secretKey: "secretKey", version: "1.0.0", apiUrl: "https://wds7788.github.io/api/v1/test/test" };
function generateSignature(config, data) { const timestamp = Math.floor(Date.now() / 1000); const nonce = generateUniqueId();
const bodyStr = data ? JSON.stringify(data, jsonSafeReplacer) : '';
const signParams = { appid: config.appId, version: config.version, timestamp: timestamp, nonce: nonce, body: bodyStr };
console.log('参与签名参数:', JSON.stringify(signParams, null, 2));
const sortedParams = Object.keys(signParams) .sort() .map(key => `${key}=${signParams[key]}`) .join('&');
console.log('签名字符串:', sortedParams);
const signature = CryptoJS.HmacSHA256( sortedParams, config.secretKey ).toString(CryptoJS.enc.Hex);
console.log('signature:', signature);
return { headers: { 'X-App-Id': config.appId, 'X-Version': config.version, 'X-Timestamp': timestamp, 'X-Nonce': nonce, 'X-Signature': signature }, body: bodyStr }; }
function generateUniqueId() { var length = 12; const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; let result = ''; const charactersLength = characters.length; for (let i = 0; i < length; i++) { result += characters.charAt(Math.floor(Math.random() * charactersLength)); } return result; }
function jsonSafeReplacer(key, value) { if (typeof value === 'bigint') { return value.toString(); } if (typeof value === 'symbol' || typeof value === 'function' || typeof value === 'undefined') { return undefined; } return value; }
async function sendRequest() { try {
const requestData = { userId: 123, action: 'testAction' };
const {headers, body} = generateSignature(config, requestData);
console.log('最终请求头:', headers); console.log('请求体:', body);
const response = await axios.post(config.apiUrl, body, { headers: { ...headers, 'Content-Type': 'application/json' } });
console.log('请求成功:', response.data); } catch (error) { console.log('请求失败:', error); } }
sendRequest(); </script> </body> </html>
|