xml - json 微信签名

安装:npm install xml2js

使用:

  var xml2js = require('xml2js');

  var builder = new xml2js.Builder();  // JSON->xml
  var parser = new xml2js.Parser({ explicitArray: false });   //xml -> json 

parser.parseString(body, function(err, result) {
  console.log(err)
  console.log(result)
})

 

  。。。。。

  xml =  builder.buildObject(json)  

 

/********************************************************************************************************/

 


function ksort(o) {
let sorted = {},
keys = Object.keys(o);
keys.sort();
keys.forEach((key)=>{
sorted[key] = o[key];
})
return sorted;
}
function toXml(_json){
var xml = '<xml>';
for (let key in _json) {
let val = _json[key];
if (
typeof val == 'string' ||
typeof val == 'number'
){
xml=xml+"<"+key+">"+val+"</"+key+">";
}else{
xml=xml+"<"+key+"><![CDATA["+val+"]]></"+key+">";
}
}
xml=xml+ '</xml>';
return xml;
}
function xmlToJson(xml){
var xmlParser = require('xml2js').Parser({explicitArray : false, ignoreAttrs : true})
var promise = new Promise(function(resolve, reject){
xmlParser.parseString(xml,function (err, result) {
resolve(result.xml);
});
});
return promise;
}

//微信支付签名
function makeSign(array,WX_KEY){
array = ksort(array);
var string = '';
for (let k in array) {
//console.log(k);
let v = array[k];
if(k != "sign" && v != "" && !(typeof v == 'array') ){string=string+k+"="+v+"&";}
}
string = string.substring(0, string.length - 1);
//签名步骤二:在string后加入KEY
string = string+"&key="+WX_KEY;
//签名步骤三:MD5加密
const md5 = require('md5-node');
string = md5(string);
//签名步骤四:所有字符转为大写
let result = string.toUpperCase();
return result;
}

function mrtqid(){  //随机字符串
const md5 = require('md5-node');
return md5( new Date().getTime() );
}

posted @ 2020-05-07 13:37  mrt_yy  阅读(195)  评论(0编辑  收藏  举报