http.js 5.68 KB
import sign from './sign.js'
import {
  defaultMerchantId,
  secretKey,
  pathEnum,
  domain,
  gscDomain,
  djDomain,
  djSecretKey
} from '../env/index'
const HOST = {
  scrm: domain,
  dj: djDomain
}
/**接口 */
class Request {
  get(params, returnAll = false, hostType = 'scrm') {
    return this.request('GET', params, returnAll, hostType)
  }
  post(params, returnAll = false, hostType = 'scrm') {
    return this.request('POST', params, returnAll, hostType)
  }
  fetch(method, data, returnAll = true, hostType = 'scrm') {
    return this.post({
        method,
        ...data,
      },
      returnAll,
      hostType
    );
  }
  wx_request({
    url,
    method = 'GET',
    data = {},
    header = {},
    dataType = 'json',
    responseType = "text"
  }) {
    return new Promise((resolve) => {
      wx.request({
        url,
        data,
        method,
        header,
        dataType,
        responseType,
        success(response) {
          resolve(response.data)
        }
      })
    })
  }
  reportTrack(params) {
    return this.request('POST', params, true)
  }
  request(RequestMethods, params, returnAll , hostType = 'scrm') {
    return new Promise((resolve, reject) => {
      wx.showNavigationBarLoading()
      let header = RequestMethods === 'POST' ? {
        'content-type': 'application/x-www-form-urlencoded'
      } : {
        'Cache-Control': 'no-cache'
      }
      let {
        merchantId
      } = wx.p.storage.get('merchant_info')
      header.merchantId = wx.$merchant_id || merchantId || defaultMerchantId
      let projectName = params.projectName
      if (!projectName) projectName = this.getRopProject(params.method)
      const path = pathEnum[projectName]
      params = this.getData(params, hostType)
      wx.request({
        url: `${HOST[hostType]}${path}router?method=${params.method}`,
        data: params,
        method: RequestMethods,
        header,
        dataType: 'json',
        responseType: 'text',
        success(response) {
          /**业务代码 */
          let {
            data: {
              code,
              message
            },
            data
          } = response
          if (returnAll) {
            resolve(data)
            return
          }
          if (code == 20 || code == 21) {
            wx.hideLoading()
            const thisPage = wx.p.router.getPageInstance(),
              options = Object.keys(thisPage.options)
            let currentRoute = thisPage.route,
              query = []
            if (options.length) {
              options.map(key => {
                query.push(`${key}=${thisPage.options[key]}`)
              })
            }
            if (query.length) currentRoute += `?${query.join('&')}`
            return wx.p.router.redirectTo('/pages/loading/loading', {
              url: `/${currentRoute}`
            })
          } else {
            if (code == '0') {
              resolve(data.data)
            } else {
              wx.showToast({
                title: message || '系统异常',
                icon: 'none'
              })
            }
          }
        },
        fail(error) {
          wx.hideLoading()
          console.error(`接口异常:`, error)
          wx.showToast({
            title: typeof error == 'string' ? error : JSON.stringify(error) || '系统异常',
            icon: 'error'
          })
          reject(error)
        },
        complete() {
          wx.stopPullDownRefresh()
          wx.hideNavigationBarLoading()
        }
      })
    })
  }
  getData(params,hostType) {
    let projectName = params.projectName
    if (!projectName) projectName = this.getRopProject(params.method)
    else delete params.projectName
    let appKey = '48e5e13229b82c1b4e6e8c96151f0637'
    let secret = 'c24619ed7fef02a0ae16328146bca5f97cc6493957a2137b'
    if (secretKey[projectName]) {
      appKey = secretKey[projectName].appKey
      secret = secretKey[projectName].secret
    }
    if(hostType == 'dj'){
      appKey = djSecretKey.appKey
      secret = djSecretKey.secret
    }
    let {
      sessionId
    } = wx.p.storage.get()
    let noSignAttr = []
    if (!params.sessionId && sessionId) params.sessionId = sessionId
    if (params.delSessionId) {
      delete params.sessionId
      delete params.delSessionId
    }
    if (params.noSignAttr) {
      noSignAttr = params.noSignAttr
      delete params.noSignAttr
    }
    params.v = '1.0.0'
    params.format = 'json'
    params.locale = 'zh_CN'
    params.source = 'dj-wechat'
    params.appKey = appKey
    return sign(params, secret, noSignAttr)
  }
  getRopProject(method) {
    const projectName = method.split('.')[2]
    return projectName
  }
  gscGet(url, data = {}, returnAll = false) {
    return this.gscRequest(url, params, 'GET', returnAll)
  }
  gscPost(url, data = {}, returnAll = false) {
    return this.gscRequest(url, data, 'POST', returnAll)
  }
  gscRequest(url, data = {}, method = 'GET', returnAll) {
    return new Promise((resolve, reject) => {
      wx.showNavigationBarLoading()
      wx.request({
        url: `${gscDomain}/gsc-agent-manage-biz/${url}`,
        data,
        method,
        success(response) {
          let {
            data
          } = response
          if (returnAll) {
            resolve(data)
            return
          }
          resolve(data.data)
        },
        fail(error) {
          wx.hideLoading()
          reject(error)
        },
        complete() {
          wx.stopPullDownRefresh()
          wx.hideNavigationBarLoading()
        }
      })
    })
  }
}
export default new Request()