http.js 1.77 KB
/**
 * @file ROP 请求签名;摘要走 @uj/api-core 的 SHA1 预设,序列化仍依赖 lib/qs
 * (indices / allowDots / encodeValuesOnly)。
 * 替换 qs 前须跑 tests/httpSign.qs.test.mjs 并做全量接口回归。
 */
import environment from './environment.js'
import qs from '~/utils/lib/qs'
import { createSigner } from '@uj/api-core'

const path = '/rop-dj-car-boutique/router'

// 与老 sign 的摘要算法字节级一致(迁移时用脚本验过:扁平 / 中文 / noSignAttr / 嵌套对象 /
// 数组 / 数组套对象 / null-undefined / merchants 域名形状 全部通过)。
const usedcarSigner = createSigner({ kind: 'rop', id: 'usedcar-sha1' })

/**
 * 摊平成「实际发送体」:嵌套对象走 a.b、数组走 a[0],值统一 decode 成字符串。
 * 这一步不能省——线上发的就是摊平后的键值对,签名原文和 wx.request 的 body 同源。
 */
const flatten = params => {
  var objStr = qs.stringify(params, {
    arrayFormat: 'indices',
    allowDots: true,
    encodeValuesOnly: true
  })
  var objVal = objStr.split('&')
  var realObj = {}
  objVal.forEach(item => {
    const idx = item.indexOf('=')
    realObj[item.split('=')[0]] = decodeURIComponent(item.slice(idx + 1))
  })
  return realObj
}

const sign = async (params, secret, noSignAttr = []) => {
  delete params.sign

  // if (params.sessionId&&params.method!='dj.api.smartcarlife.workWechat.listSelectAccount') {
  //   delete params.sessionId
  // }
  const flat = flatten(params)
  const signed = await usedcarSigner.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,
  path,
  sign
}