亲宝软件园·资讯

展开

微信小程序request请求封装,验签代码实例

shuihanxiao 人气:0

这篇文章主要介绍了微信小程序request请求封装,验签代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

1.公共文件util添加

request请求

//简单封装请求
function request(params, path, isShowLoading = true, goBack = false, type = 'none', obj={}) {
 try {
  console.log(path)
  let NowTime = Date.parse(new Date()) / 1000;
  let defaultParams = {
   platform: app.globalData.platform,
   appVersion: app.globalData.version,
   deviceId: uuId(),
   timestamp: params.timestamp ? params.timestamp : NowTime
  };
 
  params = Object.assign(params, defaultParams);
  let requestParams = signature(params)
  isShowLoading && wx.showLoading && wx.showLoading({
   title: '加
中...'
  })
  return new Promise((resolve, reject) => {
   let header;
   obj.header = obj.header || {};
   console.log('获取ptkey')
   console.log(plugin.getJdListStorage(['guid', 'pt_key', 'pt_token', 'pt_pin']))
   let [GUID = '', KEY = '', TOKEN = '', PIN = ''] = plugin.getJdListStorage(['guid', 'pt_key', 'pt_token', 'pt_pin']),
    _cookie = `guid=${GUID}; pt_pin=${encodeURIComponent(PIN)}; pt_key=${KEY}; pt_token=${TOKEN};${wx.getStorageSync("accessToken_v1")}`, {
     cookie
    } = obj.header;
   console.log(cookie)
   obj.header.cookie = cookie ? `${cookie};${_cookie}` : _cookie;
   if (!isEmpty(getToken())) {
    obj.header.authorization = 'Bearer ' + getToken()
   }
   console.log(obj.header)

   wx.request({
    url: getApp().globalData.host + path, //获取app.js 全局ip
    data: requestParams,
    method: 'POST',
    header: obj.header,
    success: function(res) {
     console.log(res)
     isShowLoading && wx.hideLoading && wx.hideLoading()
     // 缺少登录失效的处理方法
     if (res.statusCode == 200 && res.data.code == 200) {
      if (isEmpty(res.data.data) || res.data.data == true) {
       resolve('true')
       return
      }
      if (res.data.data) {
       resolve(res.data.data);
      } else if (res.data.data == 0){
       resolve(res.data.data);
      } else {
       resolve('true')
      }
     } else if (res.statusCode == 200 && res.data.code == 401) { //token过期
      Login();
      resolve(false);
      return;
     } else {
      //需要再判断code码
      // errorShow(res.data.msg, goBack, type);
      errorShow(res.data.msg);
      resolve(false);
      // reject(res.data.res);
     }
    },
    fail: function(err) {
     console.log(err)
     // 因为hide会让showToast隐藏
     isShowLoading && wx.hideLoading && wx.hideLoading()
     errorShow('网络请求失败');
     reject(new Error('Network request failed'))
     // throw new Error('Network request failed')
    },
    complete: function() {}
   })
  })
 } catch (err) {
  console.log(err)
  errorShow('网络请求失败');
  return false;
 }
}

2.signature 签名

//生成签名
function signature(params) {
 let keyArr = []
 for (let key in params) {
  keyArr.push(key)
 }
 let arr = keyArr.sort();
 let result = "";
 arr.map((item, index) => {
  if (params[item] == null || params[item] == undefined) {
   delete params[item];
   arr.splice(index, 1);
  }
 })
 console.log("arr")
 console.log(arr)
 arr.map((item, index) => {
  if (Array.isArray(params[item]) == true) {
   let res = ''
   let arr = params[item]
   arr.map(obj => {
    console.log(typeof(obj))
    if (typeof(obj) != 'object') {
     res += obj
    } else {
     for (let key in obj) {
      if (Array.isArray(obj[key])) {
       let val = '';
       obj[key].map(item => {
        val += item
       })
       res += key + val
      } else {
       res += key + obj[key]
      }
     }
    }
   })
   result += '' + item + '' + res
  } else {
   result += '' + item + '' + params[item]
  }
 })
 console.log("result")
 console.log(result)

 let pos;
 if (isEmpty(getToken())) {
  pos = result
 } else {
  pos = result + getToken()
 }
 console.log(pos)
 console.log("signature")
 let signature = sha256.hmac.create('pos_secret').update(pos).hex().toLowerCase(); //需要引入sha256.min.js
 console.log(signature)
 let obj = {
  'signature': signature
 }
 return Object.assign(params, obj);
}

加载全部内容

相关教程
猜你喜欢
用户评论