hikvision_prerequest_script.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. function uuidv4() {
  2. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
  3. const r = Math.random() * 16 | 0;
  4. const v = c === 'x' ? r : (r & 0x3 | 0x8);
  5. return v.toString(16);
  6. });
  7. }
  8. function upsertHeader(key, value) {
  9. pm.request.headers.remove(key);
  10. if (value !== undefined && value !== null && String(value) !== '') {
  11. pm.request.headers.add({ key: key, value: String(value) });
  12. }
  13. }
  14. const appKey = pm.variables.get('appKey');
  15. const appSecret = pm.variables.get('appSecret');
  16. const tagId = pm.variables.get('tagId');
  17. const accept = '*/*';
  18. const contentType = 'application/json;charset=UTF-8';
  19. const nonce = uuidv4();
  20. const timestamp = String(Date.now());
  21. const bodyRaw = pm.request.body && pm.request.body.mode === 'raw'
  22. ? pm.variables.replaceIn(pm.request.body.raw || '')
  23. : '';
  24. const contentMd5 = CryptoJS.enc.Base64.stringify(CryptoJS.MD5(CryptoJS.enc.Utf8.parse(bodyRaw)));
  25. const apiPath = '/' + pm.request.url.path.join('/');
  26. const signHeaders = [
  27. ['x-ca-key', appKey],
  28. ['x-ca-nonce', nonce],
  29. ['x-ca-timestamp', timestamp]
  30. ];
  31. const signHeaderNames = signHeaders.map(function(row) { return row[0]; }).join(',');
  32. const signTextLines = [
  33. 'POST',
  34. accept,
  35. contentMd5,
  36. contentType
  37. ];
  38. signHeaders.forEach(function(row) {
  39. signTextLines.push(row[0] + ':' + (row[1] == null ? '' : String(row[1]).trim()));
  40. });
  41. signTextLines.push(apiPath);
  42. const stringToSign = signTextLines.join('\n');
  43. const signature = CryptoJS.enc.Base64.stringify(CryptoJS.HmacSHA256(stringToSign, appSecret));
  44. upsertHeader('Accept', accept);
  45. upsertHeader('Content-Type', contentType);
  46. upsertHeader('Content-MD5', contentMd5);
  47. upsertHeader('X-Ca-Key', appKey);
  48. upsertHeader('X-Ca-Nonce', nonce);
  49. upsertHeader('X-Ca-Timestamp', timestamp);
  50. upsertHeader('X-Ca-Signature-Headers', signHeaderNames);
  51. upsertHeader('X-Ca-Signature', signature);
  52. upsertHeader('tagId', tagId);
  53. pm.environment.set('lastApiPath', apiPath);
  54. pm.environment.set('lastContentMd5', contentMd5);
  55. pm.environment.set('lastStringToSign', stringToSign);
  56. pm.environment.set('lastSignature', signature);