-
Notifications
You must be signed in to change notification settings - Fork 0
/
wechat_util.js
64 lines (61 loc) · 1.58 KB
/
wechat_util.js
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
// https://github.com/node-weixin/node-weixin-util
const crypto = require('validator')
export default {
getNonce: function (length) {
length = length || 32
var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
var pos = chars.length
var nonces = []
var i
for (i = 0; i < length; i++) {
nonces.push(chars.charAt(Math.floor(Math.random() * pos)))
}
return nonces.join('')
},
/**
* Marshalling object keys to be sorted alphabetically and then translated to url parameters
*
* @param params
* @returns {string}
*/
marshall: function (params) {
params = params || {}
var keys = Object.keys(params).sort()
var obj = {}, kvs = []
for (var i = 0; i < keys.length; i++) {
var k = keys[i]
if (params[k]) {
obj[k] = params[k]
kvs.push(keys[i] + '=' + params[k])
}
}
return kvs.join('&')
},
toXml: function (params) {
var lines = []
lines.push('<xml>')
for (var k in params) {
if (!params[k]) {
continue
}
if (isNumeric(params[k])) {
lines.push('<' + k + '>' + params[k] + '</' + k + '>')
} else {
lines.push('<' + k + '><![CDATA[' + params[k] + ']]></' + k + '>')
}
}
lines.push('</xml>')
return lines.join('')
},
toParam: function (params) {
params = params || {}
var keys = []
for (var k in params) {
keys.push(encodeURIComponent(k) + '=' + encodeURIComponent(params[k]))
}
return keys.join('&')
}
}
function isNumeric (n) {
return !isNaN(parseFloat(n)) && isFinite(n)
}