utils.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. const crypto = require('crypto')
  2. const {
  3. isPlainObject
  4. } = require('../../../common/utils')
  5. // 退款通知解密key=md5(key)
  6. function decryptData (encryptedData, key, iv = '') {
  7. // 解密
  8. const decipher = crypto.createDecipheriv('aes-128-cbc', key, iv)
  9. // 设置自动 padding 为 true,删除填充补位
  10. decipher.setAutoPadding(true)
  11. let decoded = decipher.update(encryptedData, 'base64', 'utf8')
  12. decoded += decipher.final('utf8')
  13. return decoded
  14. }
  15. function md5 (str, encoding = 'utf8') {
  16. return crypto
  17. .createHash('md5')
  18. .update(str, encoding)
  19. .digest('hex')
  20. }
  21. function sha256 (str, key, encoding = 'utf8') {
  22. return crypto
  23. .createHmac('sha256', key)
  24. .update(str, encoding)
  25. .digest('hex')
  26. }
  27. function getSignStr (obj) {
  28. return Object.keys(obj)
  29. .filter(key => key !== 'sign' && obj[key] !== undefined && obj[key] !== '')
  30. .sort()
  31. .map(key => key + '=' + obj[key])
  32. .join('&')
  33. }
  34. function getNonceStr (length = 16) {
  35. let str = ''
  36. while (str.length < length) {
  37. str += Math.random().toString(32).substring(2)
  38. }
  39. return str.substring(0, length)
  40. }
  41. // 简易版Object转XML,只可在微信支付时使用,不支持嵌套
  42. function buildXML (obj, rootName = 'xml') {
  43. const content = Object.keys(obj).map(item => {
  44. if (isPlainObject(obj[item])) {
  45. return `<${item}><![CDATA[${JSON.stringify(obj[item])}]]></${item}>`
  46. } else {
  47. return `<${item}><![CDATA[${obj[item]}]]></${item}>`
  48. }
  49. })
  50. return `<${rootName}>${content.join('')}</${rootName}>`
  51. }
  52. function isXML (str) {
  53. const reg = /^(<\?xml.*\?>)?(\r?\n)*<xml>(.|\r?\n)*<\/xml>$/i
  54. return reg.test(str.trim())
  55. };
  56. // 简易版XML转Object,只可在微信支付时使用,不支持嵌套
  57. function parseXML (xml) {
  58. const xmlReg = /<(?:xml|root).*?>([\s|\S]*)<\/(?:xml|root)>/
  59. const str = xmlReg.exec(xml)[1]
  60. const obj = {}
  61. const nodeReg = /<(.*?)>(?:<!\[CDATA\[){0,1}(.*?)(?:\]\]>){0,1}<\/.*?>/g
  62. let matches = null
  63. // eslint-disable-next-line no-cond-assign
  64. while ((matches = nodeReg.exec(str))) {
  65. obj[matches[1]] = matches[2]
  66. }
  67. return obj
  68. }
  69. module.exports = {
  70. decryptData,
  71. md5,
  72. sha256,
  73. getSignStr,
  74. getNonceStr,
  75. buildXML,
  76. parseXML,
  77. isXML
  78. }