码迷,mamicode.com
首页 > 微信 > 详细

微信小程序request请求封装,验签

时间:2019-12-02 17:11:16      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:parse   efi   date()   stp   方法   pre   push   null   data   

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);
}

3/  util文件引入

const app = getApp()
const sha256 = require(‘../libs/sha256.min.js‘);

 

 

 

 

 

 

微信小程序request请求封装,验签

标签:parse   efi   date()   stp   方法   pre   push   null   data   

原文地址:https://www.cnblogs.com/shuihanxiao/p/11971365.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!