@chuxingpay/licheng
Version:
### 安装
123 lines (114 loc) • 3.33 kB
JavaScript
const Teambition = require('teambition')
const UserAgentComposer = require('user-agent-composer')
const debug = require('debug')('@chuxingpay/licheng:Request')
const request = require('requestretry')
const xml2js = require('fast-xml-parser')
const _ = require('lodash')
const md5 = require('crypto')
const cryptojs = require('crypto-js')
/**
* 请求工具类
*/
class Request extends Teambition {
constructor(apiHost, sid, key) {
const protocol = apiHost.startsWith('https:') ? 'https' : 'http'
const temp = _.split(apiHost, `${protocol}://`)
const host = temp.length === 1 ? temp[0] : temp[1]
super(null, {
host: host,
protocol: protocol,
pkg: {
name: '@chuxingpay/licheng',
version: '1.0'
}
})
this.sid = sid
this.key = key
}
/**
* generic request
* @param method
* @param apiURL
* @param params
* @param callback
* @returns {Promise}
*/
invokeGeneric(method, apiURL, params, callback) {
let headers = {}
if (typeof params === 'function') {
callback = params
params = {}
}
params || (params = {})
if (apiURL.indexOf('/') === 0) {
apiURL = `${this.protocol}://${this.host}${this.endpoints}${apiURL}`
}
headers = {
'Content-Type': 'application/json'
}
if (this.token) {
headers['Authorization'] = 'OAuth2 ' + this.token
}
if (params.headers) {
Object.assign(headers, params.headers)
delete params.headers
}
headers['User-Agent'] = new UserAgentComposer()
.product(this.pkg.name, this.pkg.version)
.ext(`Node.js/${process.version}`)
.ext(`pid/${process.pid}`)
.build()
let options = {
method: method,
headers: headers,
url: apiURL,
json: true,
retryStrategy: params.retryStrategy || this.retryStrategy,
maxAttempts: params.maxAttempts || this.maxAttempts
}
delete params.retryStrategy
delete params.maxAttempts
if (!['get', 'delete'].includes(method.toLowerCase())) {
if (headers['Content-Type'].includes('json')) {
options.body = params
} else {
options.form = params
}
} else {
options.qs = params
}
let QueryStringValue = apiURL
if (apiURL.indexOf('cn') && apiURL.indexOf('rezenhotels')) {
QueryStringValue = ''
}
const HmacSHA1 = cryptojs.HmacSHA1
const Base64 = cryptojs.enc.Base64
let strs = []
let timestamp = new Date().getTime()
strs.push(timestamp)
strs.push(this.sid)
strs.push(QueryStringValue)
strs.push(this.key)
strs.push(JSON.stringify(options.body))
strs.sort()
let str = strs.join('')
let token_lc = Base64.stringify(HmacSHA1(str, this.key))
options.headers['Lc-Sid'] = this.sid
options.headers['Lc-Ts'] = timestamp
options.headers['Lc-Sign'] = token_lc
debug('sendRequest', options)
return new Promise((resolve, reject) => {
request(options, (err, resp, body) => {
if (err || (resp && resp.statusCode > 399)) {
err || (err = body)
}
if (typeof callback === 'function') {
resolve(callback(err, body, resp))
} else {
resolve(this.resolveWithFullResponse ? resp : body)
}
})
})
}
}
module.exports = Request