http.js
1.61 KB
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
import qs from '../lib/qs'
import { createSigner } from '@uj/api-core'
import environment from './environment.js'
// 签名算法统一收口到 @uj/api-core 的 SHA1 预设;本文件只保留 mp 侧的「参数摊平」规则。
// 迁移时用脚本对老 sign() 逐字节验证过:扁平 / 中文与特殊字符 / noSignAttr / 嵌套对象 /
// 数组 / 数组套对象 / null-undefined-数字-布尔 / dj 后端形状 共 8 类用例全部一致。
const storeSigner = createSigner({ kind: 'rop', id: 'store-sha1' })
/**
* 摊平成「实际发送体」:嵌套对象走 a.b、数组走 a[0],值统一 decode 成字符串。
* 这一步不能省——线上一直发的是摊平后的键值对,签名原文和 wx.request 的 body 同源。
*/
const flatten = params => {
const objStr = qs.stringify(params, {
arrayFormat: 'indices',
allowDots: true,
encodeValuesOnly: true
})
const objVal = objStr.split('&')
const realObj = {}
objVal.forEach(item => {
const idx = item.indexOf('=')
realObj[item.split('=')[0]] = decodeURIComponent(item.slice(idx + 1))
})
return realObj
}
/** 加签:返回真正要发送的扁平 params(含 sign);noSignAttr 里的字段进 body 但不进原文。 */
const sign = async (params, secret, noSignAttr = []) => {
delete params.sign
const flat = flatten(params)
const signed = await storeSigner.fields({
method: flat.method,
appKey: flat.appKey,
secret,
version: flat.v,
format: flat.format,
params: flat,
exclude: noSignAttr
})
return { ...flat, sign: signed.sign }
}
module.exports = {
...environment,
sign
}